code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowercase_ ( __SCREAMING_SNAKE_CASE ): __lowerCamelCase = ["image_processor", "tokenizer"] __lowerCamelCase = "BlipImageProcessor" __lowerCamelCase = "AutoTokenizer" def __init__( self , __A , __A , __A ) -> Optional[int]: super().__init__(_a , _a ) # add QFormer tokenizer SCREAMING_SNAKE_CASE_ : Dict =qformer_tokenizer def __call__( self , __A = None , __A = None , __A = True , __A = False , __A = None , __A = None , __A = 0 , __A = None , __A = None , __A = False , __A = False , __A = False , __A = False , __A = False , __A = True , __A = None , **__A , ) -> List[Any]: if images is None and text is None: raise ValueError('''You have to specify at least images or text.''' ) SCREAMING_SNAKE_CASE_ : Any =BatchFeature() if text is not None: SCREAMING_SNAKE_CASE_ : Tuple =self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) encoding.update(_a ) SCREAMING_SNAKE_CASE_ : List[Any] =self.qformer_tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) SCREAMING_SNAKE_CASE_ : List[Any] =qformer_text_encoding.pop('''input_ids''' ) SCREAMING_SNAKE_CASE_ : Dict =qformer_text_encoding.pop('''attention_mask''' ) if images is not None: SCREAMING_SNAKE_CASE_ : List[Any] =self.image_processor(_a , return_tensors=_a ) encoding.update(_a ) return encoding def _snake_case ( self , *__A , **__A ) -> List[Any]: return self.tokenizer.batch_decode(*_a , **_a ) def _snake_case ( self , *__A , **__A ) -> Optional[Any]: return self.tokenizer.decode(*_a , **_a ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _snake_case ( self ) -> str: SCREAMING_SNAKE_CASE_ : Tuple =self.tokenizer.model_input_names SCREAMING_SNAKE_CASE_ : Tuple =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def _snake_case ( self , __A , **__A ) -> Tuple: if os.path.isfile(_a ): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(_a , exist_ok=_a ) SCREAMING_SNAKE_CASE_ : List[Any] =os.path.join(_a , '''qformer_tokenizer''' ) self.qformer_tokenizer.save_pretrained(_a ) return super().save_pretrained(_a , **_a ) @classmethod def _snake_case ( cls , __A , **__A ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ : str =AutoTokenizer.from_pretrained(_a , subfolder='''qformer_tokenizer''' ) SCREAMING_SNAKE_CASE_ : Dict =cls._get_arguments_from_pretrained(_a , **_a ) args.append(_a ) return cls(*_a )
443
'''simple docstring''' import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __magic_name__ = 16 __magic_name__ = 32 def lowerCamelCase ( lowerCamelCase : Accelerator , lowerCamelCase : int = 16): A_ : Any = AutoTokenizer.from_pretrained("""bert-base-cased""") A_ : str = load_dataset("""glue""" , """mrpc""") def tokenize_function(lowerCamelCase : Dict): # max_length=None => use the model max length (it's actually the default) A_ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCamelCase , max_length=lowerCamelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): A_ : Tuple = datasets.map( lowerCamelCase , batched=lowerCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A_ : List[str] = tokenized_datasets.rename_column("""label""" , """labels""") def collate_fn(lowerCamelCase : Tuple): # On TPU it's best to pad everything to the same length or training will be very slow. A_ : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": A_ : List[Any] = 16 elif accelerator.mixed_precision != "no": A_ : Any = 8 else: A_ : Tuple = None return tokenizer.pad( lowerCamelCase , padding="""longest""" , max_length=lowerCamelCase , pad_to_multiple_of=lowerCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. A_ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase , drop_last=lowerCamelCase) A_ : str = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase , drop_last=(accelerator.mixed_precision == """fp8""") , ) return train_dataloader, eval_dataloader def lowerCamelCase ( lowerCamelCase : Any , lowerCamelCase : Dict): # Initialize accelerator A_ : Tuple = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A_ : List[Any] = config["""lr"""] A_ : List[Any] = int(config["""num_epochs"""]) A_ : int = int(config["""seed"""]) A_ : Dict = int(config["""batch_size"""]) A_ : Union[str, Any] = evaluate.load("""glue""" , """mrpc""") # If the batch size is too big we use gradient accumulation A_ : int = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: A_ : Any = batch_size // MAX_GPU_BATCH_SIZE A_ : Union[str, Any] = MAX_GPU_BATCH_SIZE set_seed(lowerCamelCase) A_ , A_ : List[str] = get_dataloaders(lowerCamelCase , lowerCamelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A_ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=lowerCamelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). A_ : str = model.to(accelerator.device) # Instantiate optimizer A_ : str = AdamW(params=model.parameters() , lr=lowerCamelCase) # Instantiate scheduler A_ : Tuple = get_linear_schedule_with_warmup( optimizer=lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(lowerCamelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A_ , A_ , A_ , A_ , A_ : Union[str, Any] = accelerator.prepare( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase) # Now we train the model for epoch in range(lowerCamelCase): model.train() for step, batch in enumerate(lowerCamelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) A_ : Optional[int] = model(**lowerCamelCase) A_ : List[Any] = outputs.loss A_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(lowerCamelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCamelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): A_ : Union[str, Any] = model(**lowerCamelCase) A_ : Any = outputs.logits.argmax(dim=-1) A_ , A_ : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""])) metric.add_batch( predictions=lowerCamelCase , references=lowerCamelCase , ) A_ : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , lowerCamelCase) def lowerCamelCase ( ): A_ : Optional[int] = argparse.ArgumentParser(description="""Simple example of training script.""") parser.add_argument( """--mixed_precision""" , type=lowerCamelCase , default=lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""") A_ : Dict = parser.parse_args() A_ : Dict = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(lowerCamelCase , lowerCamelCase) if __name__ == "__main__": main()
665
0
def snake_case__ ( lowercase = 3 , lowercase = 7 , lowercase = 1000000 ): lowerCAmelCase_: str = 0 lowerCAmelCase_: List[str] = 1 for current_denominator in range(1 , limit + 1 ): lowerCAmelCase_: Union[str, Any] = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: lowerCAmelCase_: List[Any] = current_numerator lowerCAmelCase_: Dict = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_0_0_0_0_0_0))
613
'''simple docstring''' import functools def lowerCamelCase ( lowerCamelCase : list[int] , lowerCamelCase : list[int]): # Validation if not isinstance(lowerCamelCase , lowerCamelCase) or not all(isinstance(lowerCamelCase , lowerCamelCase) for day in days): raise ValueError("""The parameter days should be a list of integers""") if len(lowerCamelCase) != 3 or not all(isinstance(lowerCamelCase , lowerCamelCase) for cost in costs): raise ValueError("""The parameter costs should be a list of three integers""") if len(lowerCamelCase) == 0: return 0 if min(lowerCamelCase) <= 0: raise ValueError("""All days elements should be greater than 0""") if max(lowerCamelCase) >= 366: raise ValueError("""All days elements should be less than 366""") A_ : Tuple = set(lowerCamelCase) @functools.cache def dynamic_programming(lowerCamelCase : int) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1) return min( costs[0] + dynamic_programming(index + 1) , costs[1] + dynamic_programming(index + 7) , costs[2] + dynamic_programming(index + 30) , ) return dynamic_programming(1) if __name__ == "__main__": import doctest doctest.testmod()
665
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCAmelCase : str = 16 UpperCAmelCase : int = 32 def _A ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : int = 16 ): """simple docstring""" a__ : Optional[int] =AutoTokenizer.from_pretrained("bert-base-cased" ) a__ : Any =load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) a__ : Dict =tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a__ : Union[str, Any] =datasets.map( SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a__ : Any =tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. a__ : Optional[int] =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a__ : Optional[int] =16 elif accelerator.mixed_precision != "no": a__ : Tuple =8 else: a__ : List[Any] =None return tokenizer.pad( SCREAMING_SNAKE_CASE , padding="longest" , max_length=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_tensors="pt" , ) # Instantiate dataloaders. a__ : Optional[int] =DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) a__ : Dict =DataLoader( tokenized_datasets["validation"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCAmelCase : Dict = mocked_dataloaders # noqa: F811 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE ) == "1": a__ : Any =2 # New Code # a__ : Any =int(args.gradient_accumulation_steps ) # Initialize accelerator a__ : str =Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=SCREAMING_SNAKE_CASE ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ : Union[str, Any] =config["""lr"""] a__ : Union[str, Any] =int(config["num_epochs"] ) a__ : str =int(config["seed"] ) a__ : Any =int(config["batch_size"] ) a__ : Tuple =evaluate.load("glue" , "mrpc" ) set_seed(SCREAMING_SNAKE_CASE ) a__ : int =get_dataloaders(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a__ : str =AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a__ : List[Any] =model.to(accelerator.device ) # Instantiate optimizer a__ : Tuple =AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE ) # Instantiate scheduler a__ : str =get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(SCREAMING_SNAKE_CASE ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a__ : str =accelerator.prepare( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(SCREAMING_SNAKE_CASE ): a__ : Optional[Any] =model(**SCREAMING_SNAKE_CASE ) a__ : Any =output.loss accelerator.backward(SCREAMING_SNAKE_CASE ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a__ : str =model(**SCREAMING_SNAKE_CASE ) a__ : Union[str, Any] =outputs.logits.argmax(dim=-1 ) a__ : Optional[int] =accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , ) a__ : Tuple =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , SCREAMING_SNAKE_CASE ) def _A ( ): """simple docstring""" a__ : Optional[Any] =argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=SCREAMING_SNAKE_CASE , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) a__ : Tuple =parser.parse_args() a__ : List[Any] ={"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
563
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowerCamelCase ( lowerCamelCase : NDArray[floataa] , lowerCamelCase : NDArray[floataa] , lowerCamelCase : list[int] , lowerCamelCase : int , ): A_ , A_ : int = coefficient_matrix.shape A_ , A_ : Union[str, Any] = constant_matrix.shape if rowsa != colsa: A_ : Any = F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(lowerCamelCase) if colsa != 1: A_ : Tuple = F'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(lowerCamelCase) if rowsa != rowsa: A_ : Dict = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(lowerCamelCase) if len(lowerCamelCase) != rowsa: A_ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'matrix but received {len(lowerCamelCase)} and {rowsa}' ) raise ValueError(lowerCamelCase) if iterations <= 0: raise ValueError("""Iterations must be at least 1""") A_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1) A_ , A_ : int = table.shape strictly_diagonally_dominant(lowerCamelCase) # Iterates the whole matrix for given number of times for _ in range(lowerCamelCase): A_ : List[Any] = [] for row in range(lowerCamelCase): A_ : int = 0 for col in range(lowerCamelCase): if col == row: A_ : List[str] = table[row][col] elif col == cols - 1: A_ : str = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] A_ : Union[str, Any] = (temp + val) / denom new_val.append(lowerCamelCase) A_ : Tuple = new_val return [float(lowerCamelCase) for i in new_val] def lowerCamelCase ( lowerCamelCase : NDArray[floataa]): A_ , A_ : Dict = table.shape A_ : Union[str, Any] = True for i in range(0 , lowerCamelCase): A_ : str = 0 for j in range(0 , cols - 1): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""") return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Tuple = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE : str = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } SCREAMING_SNAKE_CASE : List[Any] = { "facebook/nllb-large-en-ro": 1024, "facebook/nllb-200-distilled-600M": 1024, } # fmt: off SCREAMING_SNAKE_CASE : List[Any] = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" _a = VOCAB_FILES_NAMES _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = PRETRAINED_VOCAB_FILES_MAP _a = ["""input_ids""", """attention_mask"""] _a = NllbTokenizer _a = [] _a = [] def __init__( self, _lowercase=None, _lowercase=None, _lowercase="<s>", _lowercase="</s>", _lowercase="</s>", _lowercase="<s>", _lowercase="<unk>", _lowercase="<pad>", _lowercase="<mask>", _lowercase=None, _lowercase=None, _lowercase=None, _lowercase=False, **_lowercase, ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = AddedToken(_a, lstrip=_a, rstrip=_a ) if isinstance(_a, _a ) else mask_token SCREAMING_SNAKE_CASE_ = legacy_behaviour super().__init__( vocab_file=_a, tokenizer_file=_a, bos_token=_a, eos_token=_a, sep_token=_a, cls_token=_a, unk_token=_a, pad_token=_a, mask_token=_a, src_lang=_a, tgt_lang=_a, additional_special_tokens=_a, legacy_behaviour=_a, **_a, ) SCREAMING_SNAKE_CASE_ = vocab_file SCREAMING_SNAKE_CASE_ = False if not self.vocab_file else True SCREAMING_SNAKE_CASE_ = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'additional_special_tokens': _additional_special_tokens} ) SCREAMING_SNAKE_CASE_ = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE_ = src_lang if src_lang is not None else """eng_Latn""" SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE_ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def a__ ( self ) -> Tuple: return self._src_lang @src_lang.setter def a__ ( self, _lowercase ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def a__ ( self, _lowercase, _lowercase = None ) -> Dict: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def a__ ( self, _lowercase, _lowercase = None ) -> Tuple: SCREAMING_SNAKE_CASE_ = [self.sep_token_id] SCREAMING_SNAKE_CASE_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def a__ ( self, _lowercase, _lowercase, _lowercase, _lowercase, **_lowercase ) -> Union[str, Any]: if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) SCREAMING_SNAKE_CASE_ = src_lang SCREAMING_SNAKE_CASE_ = self(_a, add_special_tokens=_a, return_tensors=_a, **_a ) SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(_a ) SCREAMING_SNAKE_CASE_ = tgt_lang_id return inputs def a__ ( self, _lowercase, _lowercase = "eng_Latn", _lowercase = None, _lowercase = "fra_Latn", **_lowercase, ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = src_lang SCREAMING_SNAKE_CASE_ = tgt_lang return super().prepare_seqaseq_batch(_a, _a, **_a ) def a__ ( self ) -> List[str]: return self.set_src_lang_special_tokens(self.src_lang ) def a__ ( self ) -> Optional[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def a__ ( self, _lowercase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE_ = [self.cur_lang_code] SCREAMING_SNAKE_CASE_ = [self.eos_token_id] SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE_ = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str, pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str, special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens ) ), ) def a__ ( self, _lowercase ) -> Tuple: SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE_ = [self.cur_lang_code] SCREAMING_SNAKE_CASE_ = [self.eos_token_id] SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE_ = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str, pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str, special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens ) ), ) def a__ ( self, _lowercase, _lowercase = None ) -> Any: if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory.""" ) return SCREAMING_SNAKE_CASE_ = os.path.join( _a, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file, _a ) return (out_vocab_file,)
294
'''simple docstring''' def lowerCamelCase ( lowerCamelCase : str , lowerCamelCase : str): A_ : Any = len(lowerCamelCase) A_ : Optional[Any] = len(lowerCamelCase) A_ : Optional[int] = [[False for _ in range(m + 1)] for _ in range(n + 1)] A_ : Union[str, Any] = True for i in range(lowerCamelCase): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: A_ : Optional[int] = True if a[i].islower(): A_ : List[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
665
0
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" @register_to_config def __init__( self : int , *, lowerCAmelCase : int = 4 , lowerCAmelCase : int = 7_68 , lowerCAmelCase : int , lowerCAmelCase : Union[str, Any] , ) -> List[Any]: """simple docstring""" super().__init__() __lowerCAmelCase : List[Any] = nn.Parameter(torch.zeros(_a ) ) # parameters for additional clip time embeddings __lowerCAmelCase : List[str] = nn.Linear(_a , _a ) __lowerCAmelCase : int = nn.Linear(_a , _a ) # parameters for encoder hidden states __lowerCAmelCase : Any = clip_extra_context_tokens __lowerCAmelCase : List[str] = nn.Linear( _a , self.clip_extra_context_tokens * cross_attention_dim ) __lowerCAmelCase : Optional[int] = nn.Linear(_a , _a ) __lowerCAmelCase : Tuple = nn.LayerNorm(_a ) def SCREAMING_SNAKE_CASE ( self : str , *, lowerCAmelCase : Tuple , lowerCAmelCase : List[str] , lowerCAmelCase : Dict , lowerCAmelCase : int ) -> Optional[Any]: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings __lowerCAmelCase : str = image_embeddings.shape[0] __lowerCAmelCase : Tuple = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) __lowerCAmelCase : List[str] = classifier_free_guidance_embeddings.expand( _a , -1 ) __lowerCAmelCase : Optional[int] = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] __lowerCAmelCase : Any = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... __lowerCAmelCase : Dict = self.embedding_proj(_a ) __lowerCAmelCase : Any = self.clip_image_embeddings_project_to_time_embeddings(_a ) __lowerCAmelCase : Union[str, Any] = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" __lowerCAmelCase : Optional[Any] = self.clip_extra_context_tokens_proj(_a ) __lowerCAmelCase : Tuple = clip_extra_context_tokens.reshape(_a , -1 , self.clip_extra_context_tokens ) __lowerCAmelCase : Union[str, Any] = clip_extra_context_tokens.permute(0 , 2 , 1 ) __lowerCAmelCase : str = self.encoder_hidden_states_proj(_a ) __lowerCAmelCase : Union[str, Any] = self.text_encoder_hidden_states_norm(_a ) __lowerCAmelCase : Tuple = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
651
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class __lowerCAmelCase : '''simple docstring''' a_ = 42 a_ = 42 class __lowerCAmelCase : '''simple docstring''' def __init__( self : Union[str, Any] ,_a : int ): '''simple docstring''' A_ : list[list[Edge]] = [[] for _ in range(_a )] A_ : List[Any] = size def __getitem__( self : int ,_a : int ): '''simple docstring''' return iter(self._graph[vertex] ) @property def _a ( self : str ): '''simple docstring''' return self._size def _a ( self : str ,_a : int ,_a : int ,_a : int ): '''simple docstring''' if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(_a ,_a ) ) def _a ( self : Dict ,_a : int ,_a : int ): '''simple docstring''' A_ : Tuple = deque([start_vertex] ) A_ : list[int | None] = [None] * self.size A_ : Union[str, Any] = 0 while queue: A_ : List[Any] = queue.popleft() A_ : Tuple = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: A_ : Union[str, Any] = current_distance + edge.weight A_ : Optional[Any] = distances[edge.destination_vertex] if ( isinstance(_a ,_a ) and new_distance >= dest_vertex_distance ): continue A_ : Tuple = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
665
0
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class A__ : @property def UpperCamelCase__ ( self ): return self.get_dummy_input() @property def UpperCamelCase__ ( self ): if self.block_type == "down": return (4, 3_2, 1_6, 1_6) elif self.block_type == "mid": return (4, 3_2, 3_2, 3_2) elif self.block_type == "up": return (4, 3_2, 6_4, 6_4) raise ValueError(F'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.''' ) def UpperCamelCase__ ( self , __magic_name__=True , __magic_name__=False , __magic_name__=False , __magic_name__=False , ): lowerCamelCase : str = 4 lowerCamelCase : Tuple = 3_2 lowerCamelCase : Union[str, Any] = (3_2, 3_2) lowerCamelCase : Optional[Any] = torch.manual_seed(0 ) lowerCamelCase : Dict = torch.device(_a ) lowerCamelCase : Optional[int] = (batch_size, num_channels) + sizes lowerCamelCase : List[str] = randn_tensor(_a , generator=_a , device=_a ) lowerCamelCase : str = {"""hidden_states""": hidden_states} if include_temb: lowerCamelCase : List[str] = 1_2_8 lowerCamelCase : str = randn_tensor((batch_size, temb_channels) , generator=_a , device=_a ) if include_res_hidden_states_tuple: lowerCamelCase : List[str] = torch.manual_seed(1 ) lowerCamelCase : Union[str, Any] = (randn_tensor(_a , generator=_a , device=_a ),) if include_encoder_hidden_states: lowerCamelCase : List[Any] = floats_tensor((batch_size, 3_2, 3_2) ).to(_a ) if include_skip_sample: lowerCamelCase : Any = randn_tensor(((batch_size, 3) + sizes) , generator=_a , device=_a ) return dummy_input def UpperCamelCase__ ( self ): lowerCamelCase : Optional[int] = { """in_channels""": 3_2, """out_channels""": 3_2, """temb_channels""": 1_2_8, } if self.block_type == "up": lowerCamelCase : int = 3_2 if self.block_type == "mid": init_dict.pop("""out_channels""" ) lowerCamelCase : Optional[int] = self.dummy_input return init_dict, inputs_dict def UpperCamelCase__ ( self , __magic_name__ ): lowerCamelCase : Union[str, Any] = self.prepare_init_args_and_inputs_for_common() lowerCamelCase : Optional[Any] = self.block_class(**_a ) unet_block.to(_a ) unet_block.eval() with torch.no_grad(): lowerCamelCase : Union[str, Any] = unet_block(**_a ) if isinstance(_a , _a ): lowerCamelCase : Union[str, Any] = output[0] self.assertEqual(output.shape , self.output_shape ) lowerCamelCase : Any = output[0, -1, -3:, -3:] lowerCamelCase : str = torch.tensor(_a ).to(_a ) assert torch_all_close(output_slice.flatten() , _a , atol=5e-3 ) @unittest.skipIf(torch_device == """mps""" , """Training is not supported in mps""" ) def UpperCamelCase__ ( self ): lowerCamelCase : List[Any] = self.prepare_init_args_and_inputs_for_common() lowerCamelCase : str = self.block_class(**_a ) model.to(_a ) model.train() lowerCamelCase : int = model(**_a ) if isinstance(_a , _a ): lowerCamelCase : str = output[0] lowerCamelCase : Dict = torch.device(_a ) lowerCamelCase : List[str] = randn_tensor(output.shape , device=_a ) lowerCamelCase : Tuple = torch.nn.functional.mse_loss(_a , _a ) loss.backward()
681
'''simple docstring''' def lowerCamelCase ( lowerCamelCase : int = 10**9): A_ : Optional[int] = 1 A_ : int = 2 A_ : List[Any] = 0 A_ : Optional[Any] = 0 A_ : str = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value A_ : Optional[Any] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f"""{solution() = }""")
665
0
'''simple docstring''' import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = {"""vocab_file""": """spiece.model"""} lowercase_ = { """vocab_file""": { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""", """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model""" ), } } lowercase_ = { """google/bigbird-roberta-base""": 4_096, """google/bigbird-roberta-large""": 4_096, """google/bigbird-base-trivia-itc""": 4_096, } class a_ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = VOCAB_FILES_NAMES UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase = ['''input_ids''', '''attention_mask'''] UpperCamelCase = [] def __init__( self , A , A="<unk>" , A="<s>" , A="</s>" , A="<pad>" , A="[SEP]" , A="[MASK]" , A="[CLS]" , A = None , **A , ) -> Any: _SCREAMING_SNAKE_CASE = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token _SCREAMING_SNAKE_CASE = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token _SCREAMING_SNAKE_CASE = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token _SCREAMING_SNAKE_CASE = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token _SCREAMING_SNAKE_CASE = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token _SCREAMING_SNAKE_CASE = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token # Mask token behave like a normal word, i.e. include the space before it _SCREAMING_SNAKE_CASE = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token _SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , pad_token=_a , sep_token=_a , mask_token=_a , cls_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) _SCREAMING_SNAKE_CASE = vocab_file _SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def snake_case_( self ) -> Dict: return self.sp_model.get_piece_size() def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Any: _SCREAMING_SNAKE_CASE = self.__dict__.copy() _SCREAMING_SNAKE_CASE = None return state def __setstate__( self , A ) -> List[str]: _SCREAMING_SNAKE_CASE = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def snake_case_( self , A ) -> Tuple: return self.sp_model.encode(_a , out_type=_a ) def snake_case_( self , A ) -> Any: return self.sp_model.piece_to_id(_a ) def snake_case_( self , A ) -> Dict: _SCREAMING_SNAKE_CASE = self.sp_model.IdToPiece(_a ) return token def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = """""" _SCREAMING_SNAKE_CASE = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = [] else: current_sub_tokens.append(_a ) _SCREAMING_SNAKE_CASE = False out_string += self.sp_model.decode(_a ) return out_string.strip() def snake_case_( self , A , A = False , A = None , A = True , **A , ) -> List[str]: _SCREAMING_SNAKE_CASE = kwargs.pop("""use_source_tokenizer""" , _a ) _SCREAMING_SNAKE_CASE = self.convert_ids_to_tokens(_a , skip_special_tokens=_a ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) _SCREAMING_SNAKE_CASE = [] sub_texts.append(_a ) else: current_sub_text.append(_a ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: _SCREAMING_SNAKE_CASE = re.sub(R""" (\[(MASK|SEP)\])""" , R"""\1""" , """ """.join(_a ) ) else: _SCREAMING_SNAKE_CASE = """""".join(_a ) _SCREAMING_SNAKE_CASE = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: _SCREAMING_SNAKE_CASE = self.clean_up_tokenization(_a ) return clean_text else: return text def snake_case_( self , A , A = None ) -> Tuple: if not os.path.isdir(_a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _SCREAMING_SNAKE_CASE = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , """wb""" ) as fi: _SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,) def snake_case_( self , A , A = None ) -> str: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE = [self.cls_token_id] _SCREAMING_SNAKE_CASE = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def snake_case_( self , A , A = None , A = False ) -> Optional[Any]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] def snake_case_( self , A , A = None ) -> Tuple: _SCREAMING_SNAKE_CASE = [self.sep_token_id] _SCREAMING_SNAKE_CASE = [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]
314
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def lowerCamelCase ( ): A_ : Optional[int] = ArgumentParser("""Accelerate CLI tool""" , usage="""accelerate <command> [<args>]""" , allow_abbrev=lowerCamelCase) A_ : Optional[int] = parser.add_subparsers(help="""accelerate command helpers""") # Register commands get_config_parser(subparsers=lowerCamelCase) env_command_parser(subparsers=lowerCamelCase) launch_command_parser(subparsers=lowerCamelCase) tpu_command_parser(subparsers=lowerCamelCase) test_command_parser(subparsers=lowerCamelCase) # Let's go A_ : Dict = parser.parse_args() if not hasattr(lowerCamelCase , """func"""): parser.print_help() exit(1) # Run args.func(lowerCamelCase) if __name__ == "__main__": main()
665
0
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _UpperCamelCase : """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=13 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=99 , lowerCAmelCase__=32 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=37 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_12 , lowerCAmelCase__=16 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , ) -> List[str]: '''simple docstring''' __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_input_mask __lowercase = use_token_type_ids __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = type_sequence_label_size __lowercase = initializer_range __lowercase = num_labels __lowercase = num_choices __lowercase = scope def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase = None if self.use_input_mask: __lowercase = random_attention_mask([self.batch_size, self.seq_length] ) __lowercase = None if self.use_token_type_ids: __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowercase = None __lowercase = None __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowercase = ids_tensor([self.batch_size] , self.num_choices ) __lowercase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' __lowercase = LlamaModel(config=_a ) model.to(_a ) model.eval() __lowercase = model(_a , attention_mask=_a ) __lowercase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> List[str]: '''simple docstring''' __lowercase = True __lowercase = LlamaModel(_a ) model.to(_a ) model.eval() __lowercase = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) __lowercase = model( _a , attention_mask=_a , encoder_hidden_states=_a , ) __lowercase = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> int: '''simple docstring''' __lowercase = LlamaForCausalLM(config=_a ) model.to(_a ) model.eval() __lowercase = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' __lowercase = True __lowercase = True __lowercase = LlamaForCausalLM(config=_a ) model.to(_a ) model.eval() # first forward pass __lowercase = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , use_cache=_a , ) __lowercase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __lowercase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __lowercase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __lowercase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowercase = torch.cat([input_mask, next_mask] , dim=-1 ) __lowercase = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , output_hidden_states=_a , )["""hidden_states"""][0] __lowercase = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , past_key_values=_a , output_hidden_states=_a , )["""hidden_states"""][0] # select random slice __lowercase = ids_tensor((1,) , output_from_past.shape[-1] ).item() __lowercase = output_from_no_past[:, -3:, random_slice_idx].detach() __lowercase = 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(_a , _a , atol=1E-3 ) ) def _SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' __lowercase = self.prepare_config_and_inputs() ( __lowercase ) = config_and_inputs __lowercase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _UpperCamelCase ( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,unittest.TestCase ): """simple docstring""" __a : Optional[int] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () __a : List[str] = (LlamaForCausalLM,) if is_torch_available() else () __a : Any = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) __a : Dict = False __a : List[Any] = False def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = LlamaModelTester(self ) __lowercase = ConfigTester(self , config_class=_a , hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowercase = type self.model_tester.create_and_check_model(*_a ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs_for_common() __lowercase = 3 __lowercase = input_dict["""input_ids"""] __lowercase = input_ids.ne(1 ).to(_a ) __lowercase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __lowercase = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() __lowercase = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs_for_common() __lowercase = 3 __lowercase = """single_label_classification""" __lowercase = input_dict["""input_ids"""] __lowercase = input_ids.ne(1 ).to(_a ) __lowercase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __lowercase = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() __lowercase = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs_for_common() __lowercase = 3 __lowercase = """multi_label_classification""" __lowercase = input_dict["""input_ids"""] __lowercase = input_ids.ne(1 ).to(_a ) __lowercase = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __lowercase = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() __lowercase = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''LLaMA buffers include complex numbers, which breaks this test''' ) def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs_for_common() __lowercase = ids_tensor([1, 10] , config.vocab_size ) __lowercase = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __lowercase = LlamaModel(_a ) original_model.to(_a ) original_model.eval() __lowercase = original_model(_a ).last_hidden_state __lowercase = original_model(_a ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __lowercase = {"""type""": scaling_type, """factor""": 10.0} __lowercase = LlamaModel(_a ) scaled_model.to(_a ) scaled_model.eval() __lowercase = scaled_model(_a ).last_hidden_state __lowercase = scaled_model(_a ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_a , _a , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(_a , _a , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_a , _a , atol=1E-5 ) ) @require_torch class _UpperCamelCase ( unittest.TestCase ): """simple docstring""" @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' __lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] __lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf''' , device_map='''auto''' ) __lowercase = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __lowercase = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __lowercase = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _a , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' __lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] __lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf''' , device_map='''auto''' ) __lowercase = model(torch.tensor(_a ) ) # Expected mean on dim = -1 __lowercase = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __lowercase = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _a , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' __lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] __lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' , device_map='''auto''' ) __lowercase = model(torch.tensor(_a ) ) # Expected mean on dim = -1 __lowercase = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __lowercase = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 ) @unittest.skip( '''Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test''' ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' __lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] __lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf''' , device_map='''auto''' ) __lowercase = model(torch.tensor(_a ) ) __lowercase = torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 ) # fmt: off __lowercase = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _a , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Model is curently gated''' ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' __lowercase = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" __lowercase = """Simply put, the theory of relativity states that """ __lowercase = LlamaTokenizer.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' ) __lowercase = tokenizer.encode(_a , return_tensors='''pt''' ) __lowercase = LlamaForCausalLM.from_pretrained( '''meta-llama/Llama-2-13b-chat-hf''' , device_map='''sequential''' , use_safetensors=_a ) # greedy generation outputs __lowercase = model.generate(_a , max_new_tokens=64 , top_p=_a , temperature=1 , do_sample=_a ) __lowercase = tokenizer.decode(generated_ids[0] , skip_special_tokens=_a ) self.assertEqual(_a , _a )
534
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __magic_name__ = { 'configuration_altclip': [ 'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig', ], 'processing_altclip': ['AltCLIPProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'AltCLIPPreTrainedModel', 'AltCLIPModel', 'AltCLIPTextModel', 'AltCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
0
import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor _lowercase : List[Any] =logging.getLogger(__name__) _lowercase : Optional[int] =50 # max width of layer names _lowercase : Tuple =70 # max width of quantizer names def lowerCAmelCase_ ( _lowercase : Any) -> Dict: """simple docstring""" a__ : Optional[int] = parser.add_argument_group("""quant_trainer arguments""") group.add_argument("""--wprec""" , type=_lowercase , default=8 , help="""weight precision""") group.add_argument("""--aprec""" , type=_lowercase , default=8 , help="""activation precision""") group.add_argument("""--quant-per-tensor""" , action="""store_true""" , help="""per tensor weight scaling""") group.add_argument("""--quant-disable""" , action="""store_true""" , help="""disable all quantizers""") group.add_argument("""--quant-disable-embeddings""" , action="""store_true""" , help="""disable all embeddings quantizers""") group.add_argument("""--quant-disable-keyword""" , type=_lowercase , nargs="""+""" , help="""disable quantizers by keyword""") group.add_argument("""--quant-disable-layer-module""" , type=_lowercase , help="""disable quantizers by keyword under layer.""") group.add_argument("""--quant-enable-layer-module""" , type=_lowercase , help="""enable quantizers by keyword under layer""") group.add_argument("""--calibrator""" , default="""max""" , help="""which quantization range calibrator to use""") group.add_argument("""--percentile""" , default=_lowercase , type=_lowercase , help="""percentile for PercentileCalibrator""") group.add_argument("""--fuse-qkv""" , action="""store_true""" , help="""use the same scale factor for qkv""") group.add_argument("""--clip-gelu""" , metavar="""N""" , type=_lowercase , help="""clip gelu output maximum value to N""") group.add_argument( """--recalibrate-weights""" , action="""store_true""" , help=( """recalibrate weight amaxes by taking the max of the weights.""" """ amaxes will be computed with the current quantization granularity (axis).""" ) , ) def lowerCAmelCase_ ( _lowercase : Tuple) -> Tuple: """simple docstring""" if args.calibrator == "max": a__ : Union[str, Any] = """max""" elif args.calibrator == "percentile": if args.percentile is None: raise ValueError("""Specify --percentile when using percentile calibrator""") a__ : Dict = """histogram""" elif args.calibrator == "mse": a__ : Union[str, Any] = """histogram""" else: raise ValueError(F'''Invalid calibrator {args.calibrator}''') a__ : str = QuantDescriptor(num_bits=args.aprec , calib_method=_lowercase) a__ : Tuple = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,))) quant_nn.QuantLinear.set_default_quant_desc_input(_lowercase) quant_nn.QuantLinear.set_default_quant_desc_weight(_lowercase) def lowerCAmelCase_ ( _lowercase : Optional[Any] , _lowercase : Dict , _lowercase : str=False , _lowercase : Any=False) -> List[Any]: """simple docstring""" logger.info("""Configuring Model for Quantization""") logger.info(F'''using quantization package {pytorch_quantization.__file__}''') if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(_lowercase , ["""embeddings"""] , which="""weight""" , _disabled=_lowercase) if args.quant_disable: set_quantizer_by_name(_lowercase , [""""""] , _disabled=_lowercase) if args.quant_disable_keyword: set_quantizer_by_name(_lowercase , args.quant_disable_keyword , _disabled=_lowercase) if args.quant_disable_layer_module: set_quantizer_by_name(_lowercase , [R"""layer.\d+.""" + args.quant_disable_layer_module] , _disabled=_lowercase) if args.quant_enable_layer_module: set_quantizer_by_name(_lowercase , [R"""layer.\d+.""" + args.quant_enable_layer_module] , _disabled=_lowercase) if args.recalibrate_weights: recalibrate_weights(_lowercase) if args.fuse_qkv: fuse_qkv(_lowercase , _lowercase) if args.clip_gelu: clip_gelu(_lowercase , args.clip_gelu) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(_lowercase) def lowerCAmelCase_ ( _lowercase : Dict) -> Any: """simple docstring""" logger.info("""Enabling Calibration""") for name, module in model.named_modules(): if name.endswith("""_quantizer"""): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(F'''{name:80}: {module}''') def lowerCAmelCase_ ( _lowercase : Dict , _lowercase : Union[str, Any]) -> Optional[int]: """simple docstring""" logger.info("""Loading calibrated amax""") for name, module in model.named_modules(): if name.endswith("""_quantizer"""): if module._calibrator is not None: if isinstance(module._calibrator , calib.MaxCalibrator): module.load_calib_amax() else: module.load_calib_amax("""percentile""" , percentile=args.percentile) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(_lowercase) def lowerCAmelCase_ ( _lowercase : List[str] , _lowercase : Dict) -> Union[str, Any]: """simple docstring""" def fusea(_lowercase : int , _lowercase : Dict , _lowercase : str): for mod in [qq, qk, qv]: if not hasattr(_lowercase , """_amax"""): print(""" WARNING: NO AMAX BUFFER""") return a__ : Dict = qq._amax.detach().item() a__ : int = qk._amax.detach().item() a__ : Union[str, Any] = qv._amax.detach().item() a__ : Any = max(_lowercase , _lowercase , _lowercase) qq._amax.fill_(_lowercase) qk._amax.fill_(_lowercase) qv._amax.fill_(_lowercase) logger.info(F''' q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}''') for name, mod in model.named_modules(): if name.endswith(""".attention.self"""): logger.info(F'''FUSE_QKV: {name:{name_width}}''') fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer) if args.quant_per_tensor: fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer) def lowerCAmelCase_ ( _lowercase : Optional[int] , _lowercase : Optional[Any]) -> Optional[Any]: """simple docstring""" for name, mod in model.named_modules(): if name.endswith(""".output.dense""") and not name.endswith("""attention.output.dense"""): a__ : Union[str, Any] = mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=_lowercase) a__ : Union[str, Any] = mod._input_quantizer._amax.data.detach().item() logger.info(F'''CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}''') def lowerCAmelCase_ ( _lowercase : Optional[Any]) -> Tuple: """simple docstring""" for name, mod in model.named_modules(): if hasattr(_lowercase , """_weight_quantizer""") and mod._weight_quantizer.axis is not None: a__ : List[str] = mod.weight.shape[0] a__ : Tuple = mod._weight_quantizer._amax.detach() a__ : int = torch.ones(_lowercase , dtype=amax.dtype , device=amax.device) * amax print(F'''expanding {name} {amax} -> {mod._weight_quantizer._amax}''') def lowerCAmelCase_ ( _lowercase : List[str]) -> Optional[int]: """simple docstring""" for name, mod in model.named_modules(): if hasattr(_lowercase , """_weight_quantizer"""): if not hasattr(mod.weight_quantizer , """_amax"""): print("""RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER""") continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) a__ : Dict = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis) a__ : int = set(range(len(mod.weight.size()))) - axis_set a__ : Any = pytorch_quantization.utils.reduce_amax(mod.weight , axis=_lowercase , keepdims=_lowercase).detach() logger.info(F'''RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}''') a__ : int = amax def lowerCAmelCase_ ( _lowercase : Any , _lowercase : Dict=25 , _lowercase : Union[str, Any]=180 , _lowercase : int=None) -> Optional[Any]: """simple docstring""" if ignore is None: a__ : List[Any] = [] elif not isinstance(_lowercase , _lowercase): a__ : Optional[Any] = [ignore] a__ : Optional[int] = 0 for name, mod in model.named_modules(): if not hasattr(_lowercase , """weight"""): continue a__ : str = max(_lowercase , len(_lowercase)) for name, mod in model.named_modules(): a__ : Any = getattr(_lowercase , """_input_quantizer""" , _lowercase) a__ : Optional[int] = getattr(_lowercase , """_weight_quantizer""" , _lowercase) if not hasattr(_lowercase , """weight"""): continue if type(_lowercase) in ignore: continue if [True for s in ignore if type(_lowercase) is str and s in name]: continue a__ : Optional[Any] = F'''Act:{input_q.extra_repr()}''' a__ : List[str] = F'''Wgt:{weight_q.extra_repr()}''' a__ : Tuple = F'''{name:{name_width}} {act_str} {wgt_str}''' if len(_lowercase) <= line_width: logger.info(_lowercase) else: logger.info(F'''{name:{name_width}} {act_str}''') logger.info(F'''{' ':{name_width}} {wgt_str}''') def lowerCAmelCase_ ( _lowercase : int) -> Any: """simple docstring""" a__ : Optional[Any] = 0 for name, mod in model.named_modules(): if isinstance(_lowercase , pytorch_quantization.nn.TensorQuantizer): print(F'''{name:80} {mod}''') count += 1 print(F'''{count} TensorQuantizers found in model''') def lowerCAmelCase_ ( _lowercase : str , _lowercase : str , _lowercase : int , _lowercase : Optional[int] , _lowercase : Optional[int]) -> List[Any]: """simple docstring""" a__ : Optional[Any] = getattr(_lowercase , _lowercase , _lowercase) if quantizer_mod is not None: assert hasattr(_lowercase , _lowercase) setattr(_lowercase , _lowercase , _lowercase) else: logger.warning(F'''{name} has no {quantizer}''') def lowerCAmelCase_ ( _lowercase : int , _lowercase : Optional[int] , _lowercase : List[Any]="both" , **_lowercase : Tuple) -> Dict: """simple docstring""" a__ : Dict = F'''Warning: changing {which} quantizers of {name:{qname_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' if which in ["input", "both"]: set_quantizer(_lowercase , _lowercase , """_input_quantizer""" , _lowercase , _lowercase) if which in ["weight", "both"]: set_quantizer(_lowercase , _lowercase , """_weight_quantizer""" , _lowercase , _lowercase) logger.info(_lowercase) def lowerCAmelCase_ ( _lowercase : Optional[int] , _lowercase : Tuple , **_lowercase : Tuple) -> Union[str, Any]: """simple docstring""" for name, mod in model.named_modules(): if hasattr(_lowercase , """_input_quantizer""") or hasattr(_lowercase , """_weight_quantizer"""): for n in names: if re.search(_lowercase , _lowercase): set_quantizers(_lowercase , _lowercase , **_lowercase) elif name.endswith("""_quantizer"""): for n in names: if re.search(_lowercase , _lowercase): a__ : Optional[Any] = F'''Warning: changing {name:{name_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' setattr(_lowercase , _lowercase , _lowercase) logger.info(_lowercase)
136
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __magic_name__ = {'configuration_yolos': ['YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'YolosConfig', 'YolosOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['YolosFeatureExtractor'] __magic_name__ = ['YolosImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST', 'YolosForObjectDetection', 'YolosModel', 'YolosPreTrainedModel', ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
0
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets UpperCAmelCase__ = '''\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n''' UpperCAmelCase__ = '''\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n''' UpperCAmelCase__ = r'''\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n''' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): '''simple docstring''' def lowerCAmelCase ( self : Optional[Any] ) -> int: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/hendrycks/math' , codebase_urls=['https://github.com/hendrycks/math'] , ) def lowerCAmelCase ( self : List[Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] ) -> int: __A= 0.0 for i, j in zip(_a , _a ): n_correct += 1.0 if math_equivalence.is_equiv(_a , _a ) else 0.0 __A= n_correct / len(_a ) return { "accuracy": accuracy, }
186
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ =logging.get_logger(__name__) lowercase__ ={ 'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json', } class a_ ( __SCREAMING_SNAKE_CASE ): lowerCamelCase__ : Dict = 'git_vision_model' def __init__( self , UpperCAmelCase=7_68 , UpperCAmelCase=30_72 , UpperCAmelCase=12 , UpperCAmelCase=12 , UpperCAmelCase=3 , UpperCAmelCase=2_24 , UpperCAmelCase=16 , UpperCAmelCase="quick_gelu" , UpperCAmelCase=1e-5 , UpperCAmelCase=0.0 , UpperCAmelCase=0.02 , **UpperCAmelCase , ): super().__init__(**_a ) a_ = hidden_size a_ = intermediate_size a_ = num_hidden_layers a_ = num_attention_heads a_ = num_channels a_ = patch_size a_ = image_size a_ = initializer_range a_ = attention_dropout a_ = layer_norm_eps a_ = hidden_act @classmethod def lowerCAmelCase__ ( cls , UpperCAmelCase , **UpperCAmelCase ): cls._set_token_in_kwargs(_a ) a_ = cls.get_config_dict(_a , **_a ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": a_ = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_a , **_a ) class a_ ( __SCREAMING_SNAKE_CASE ): lowerCamelCase__ : Optional[int] = 'git' def __init__( self , UpperCAmelCase=None , UpperCAmelCase=3_05_22 , UpperCAmelCase=7_68 , UpperCAmelCase=6 , UpperCAmelCase=12 , UpperCAmelCase=30_72 , UpperCAmelCase="gelu" , UpperCAmelCase=0.1 , UpperCAmelCase=0.1 , UpperCAmelCase=10_24 , UpperCAmelCase=0.02 , UpperCAmelCase=1e-12 , UpperCAmelCase=0 , UpperCAmelCase="absolute" , UpperCAmelCase=True , UpperCAmelCase=False , UpperCAmelCase=1_01 , UpperCAmelCase=1_02 , UpperCAmelCase=None , **UpperCAmelCase , ): super().__init__(bos_token_id=_a , eos_token_id=_a , pad_token_id=_a , **_a ) if vision_config is None: a_ = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) a_ = GitVisionConfig(**_a ) a_ = vocab_size a_ = hidden_size a_ = num_hidden_layers a_ = num_attention_heads a_ = hidden_act a_ = intermediate_size a_ = hidden_dropout_prob a_ = attention_probs_dropout_prob a_ = max_position_embeddings a_ = initializer_range a_ = layer_norm_eps a_ = position_embedding_type a_ = use_cache a_ = tie_word_embeddings a_ = num_image_with_embedding a_ = bos_token_id a_ = eos_token_id def lowerCAmelCase__ ( self ): a_ = copy.deepcopy(self.__dict__ ) a_ = self.vision_config.to_dict() a_ = self.__class__.model_type return output
263
'''simple docstring''' def lowerCamelCase ( lowerCamelCase : Tuple): A_ : str = [0] * len(lowerCamelCase) A_ : Union[str, Any] = [] A_ : Union[str, Any] = [] A_ : Tuple = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCamelCase)): if indegree[i] == 0: queue.append(lowerCamelCase) while queue: A_ : Any = queue.pop(0) cnt += 1 topo.append(lowerCamelCase) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(lowerCamelCase) if cnt != len(lowerCamelCase): print("""Cycle exists""") else: print(lowerCamelCase) # Adjacency List of Graph __magic_name__ = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
665
0
import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : Features ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ : Any =np.inf def set_batch_size(UpperCAmelCase_ : FeatureType ) -> None: nonlocal batch_size if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE_ : int =min(UpperCAmelCase_ , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE_ : List[str] =min(UpperCAmelCase_ , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and feature.dtype == "binary": SCREAMING_SNAKE_CASE_ : Tuple =min(UpperCAmelCase_ , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(UpperCAmelCase_ , UpperCAmelCase_ ) return None if batch_size is np.inf else batch_size class lowercase_ ( __SCREAMING_SNAKE_CASE ): def __init__( self , __A , __A = None , __A = None , __A = None , __A = False , __A = False , __A = None , **__A , ) -> Any: super().__init__( _a , split=_a , features=_a , cache_dir=_a , keep_in_memory=_a , streaming=_a , num_proc=_a , **_a , ) SCREAMING_SNAKE_CASE_ : Optional[Any] =path_or_paths if isinstance(_a , _a ) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE_ : Optional[int] =_PACKAGED_DATASETS_MODULES["""parquet"""][1] SCREAMING_SNAKE_CASE_ : str =Parquet( cache_dir=_a , data_files=_a , features=_a , hash=_a , **_a , ) def _snake_case ( self ) -> Optional[Any]: if self.streaming: SCREAMING_SNAKE_CASE_ : Union[str, Any] =self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE_ : Optional[int] =None SCREAMING_SNAKE_CASE_ : List[Any] =None SCREAMING_SNAKE_CASE_ : Union[str, Any] =None SCREAMING_SNAKE_CASE_ : List[Any] =None self.builder.download_and_prepare( download_config=_a , download_mode=_a , verification_mode=_a , base_path=_a , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =self.builder.as_dataset( split=self.split , verification_mode=_a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , __A , __A , __A = None , **__A , ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ : Tuple =dataset SCREAMING_SNAKE_CASE_ : Tuple =path_or_buf SCREAMING_SNAKE_CASE_ : Optional[Any] =batch_size or get_writer_batch_size(dataset.features ) SCREAMING_SNAKE_CASE_ : List[str] =parquet_writer_kwargs def _snake_case ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ : List[str] =self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with open(self.path_or_buf , '''wb+''' ) as buffer: SCREAMING_SNAKE_CASE_ : Dict =self._write(file_obj=_a , batch_size=_a , **self.parquet_writer_kwargs ) else: SCREAMING_SNAKE_CASE_ : List[Any] =self._write(file_obj=self.path_or_buf , batch_size=_a , **self.parquet_writer_kwargs ) return written def _snake_case ( self , __A , __A , **__A ) -> int: SCREAMING_SNAKE_CASE_ : List[Any] =0 SCREAMING_SNAKE_CASE_ : int =parquet_writer_kwargs.pop('''path_or_buf''' , _a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =self.dataset.features.arrow_schema SCREAMING_SNAKE_CASE_ : List[Any] =pq.ParquetWriter(_a , schema=_a , **_a ) for offset in logging.tqdm( range(0 , len(self.dataset ) , _a ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ): SCREAMING_SNAKE_CASE_ : Optional[Any] =query_table( table=self.dataset._data , key=slice(_a , offset + batch_size ) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(_a ) written += batch.nbytes writer.close() return written
443
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class __lowerCAmelCase : '''simple docstring''' def __init__( self : Optional[int] ,_a : List[Any] ,_a : Dict=13 ,_a : List[str]=7 ,_a : Dict=True ,_a : List[Any]=True ,_a : Dict=False ,_a : Optional[int]=True ,_a : List[Any]=99 ,_a : Any=32 ,_a : Optional[int]=5 ,_a : List[Any]=4 ,_a : int=37 ,_a : List[Any]="gelu" ,_a : List[str]=0.1 ,_a : Union[str, Any]=0.1 ,_a : Any=512 ,_a : int=16 ,_a : Optional[int]=2 ,_a : Any=0.02 ,_a : Any=3 ,_a : Any=4 ,_a : List[str]=None ,): '''simple docstring''' A_ : List[str] = parent A_ : Any = batch_size A_ : Tuple = seq_length A_ : List[str] = is_training A_ : Tuple = use_input_mask A_ : Dict = use_token_type_ids A_ : List[Any] = use_labels A_ : Union[str, Any] = vocab_size A_ : Any = hidden_size A_ : str = num_hidden_layers A_ : Optional[Any] = num_attention_heads A_ : str = intermediate_size A_ : Tuple = hidden_act A_ : Any = hidden_dropout_prob A_ : Any = attention_probs_dropout_prob A_ : List[str] = max_position_embeddings A_ : int = type_vocab_size A_ : Union[str, Any] = type_sequence_label_size A_ : Any = initializer_range A_ : List[Any] = num_labels A_ : Optional[Any] = num_choices A_ : List[Any] = scope def _a ( self : Optional[int] ): '''simple docstring''' A_ : str = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A_ : int = None if self.use_input_mask: A_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A_ : Dict = None if self.use_token_type_ids: A_ : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A_ : str = None A_ : Any = None A_ : str = None if self.use_labels: A_ : Dict = 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_ : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self : Optional[Any] ): '''simple docstring''' return LlamaConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=_a ,initializer_range=self.initializer_range ,) def _a ( self : Union[str, Any] ,_a : Optional[Any] ,_a : Optional[Any] ,_a : Any ,_a : Any ,_a : Optional[Any] ,_a : Optional[Any] ,_a : Tuple ): '''simple docstring''' A_ : Any = LlamaModel(config=_a ) model.to(_a ) model.eval() A_ : Optional[Any] = model(_a ,attention_mask=_a ) A_ : Optional[int] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self : Optional[int] ,_a : int ,_a : List[str] ,_a : Any ,_a : Any ,_a : Dict ,_a : List[str] ,_a : Optional[int] ,_a : Any ,_a : List[str] ,): '''simple docstring''' A_ : List[str] = True A_ : Union[str, Any] = LlamaModel(_a ) model.to(_a ) model.eval() A_ : Tuple = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,) A_ : List[Any] = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,) A_ : int = model(_a ,attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self : Any ,_a : Any ,_a : Optional[int] ,_a : List[Any] ,_a : List[Any] ,_a : Dict ,_a : Tuple ,_a : Optional[int] ,_a : List[Any] ,_a : Union[str, Any] ,): '''simple docstring''' A_ : List[Any] = LlamaForCausalLM(config=_a ) model.to(_a ) model.eval() A_ : Dict = model(_a ,attention_mask=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self : str ,_a : List[Any] ,_a : Dict ,_a : str ,_a : Tuple ,_a : Tuple ,_a : Tuple ,_a : Optional[Any] ,_a : Dict ,_a : Union[str, Any] ,): '''simple docstring''' A_ : Optional[Any] = True A_ : Any = True A_ : Tuple = LlamaForCausalLM(config=_a ) model.to(_a ) model.eval() # first forward pass A_ : Optional[int] = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,use_cache=_a ,) A_ : Tuple = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A_ : int = ids_tensor((self.batch_size, 3) ,config.vocab_size ) A_ : List[Any] = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and A_ : Tuple = torch.cat([input_ids, next_tokens] ,dim=-1 ) A_ : int = torch.cat([input_mask, next_mask] ,dim=-1 ) A_ : List[str] = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,output_hidden_states=_a ,)["""hidden_states"""][0] A_ : Any = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,past_key_values=_a ,output_hidden_states=_a ,)["""hidden_states"""][0] # select random slice A_ : List[str] = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A_ : str = output_from_no_past[:, -3:, random_slice_idx].detach() A_ : int = 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(_a ,_a ,atol=1e-3 ) ) def _a ( self : Optional[Any] ): '''simple docstring''' A_ : int = self.prepare_config_and_inputs() ( ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ) : Any = config_and_inputs A_ : int = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' a_ = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () a_ = (LlamaForCausalLM,) if is_torch_available() else () a_ = ( { """feature-extraction""": LlamaModel, """text-classification""": LlamaForSequenceClassification, """text-generation""": LlamaForCausalLM, """zero-shot""": LlamaForSequenceClassification, } if is_torch_available() else {} ) a_ = False a_ = False def _a ( self : List[Any] ): '''simple docstring''' A_ : Union[str, Any] = LlamaModelTester(self ) A_ : List[str] = ConfigTester(self ,config_class=_a ,hidden_size=37 ) def _a ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() def _a ( self : Optional[Any] ): '''simple docstring''' A_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self : Optional[Any] ): '''simple docstring''' A_ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A_ : Dict = type self.model_tester.create_and_check_model(*_a ) def _a ( self : List[Any] ): '''simple docstring''' A_ , A_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() A_ : List[str] = 3 A_ : Any = input_dict["""input_ids"""] A_ : Union[str, Any] = input_ids.ne(1 ).to(_a ) A_ : Union[str, Any] = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A_ : List[Any] = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() A_ : int = model(_a ,attention_mask=_a ,labels=_a ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self : Dict ): '''simple docstring''' A_ , A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() A_ : str = 3 A_ : Union[str, Any] = """single_label_classification""" A_ : Union[str, Any] = input_dict["""input_ids"""] A_ : List[Any] = input_ids.ne(1 ).to(_a ) A_ : Dict = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A_ : List[Any] = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() A_ : List[str] = model(_a ,attention_mask=_a ,labels=_a ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self : Optional[Any] ): '''simple docstring''' A_ , A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() A_ : Dict = 3 A_ : Dict = """multi_label_classification""" A_ : Any = input_dict["""input_ids"""] A_ : Optional[Any] = input_ids.ne(1 ).to(_a ) A_ : List[str] = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) A_ : Optional[int] = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() A_ : Any = model(_a ,attention_mask=_a ,labels=_a ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""LLaMA buffers include complex numbers, which breaks this test""" ) def _a ( self : Any ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _a ( self : Optional[Any] ,_a : List[Any] ): '''simple docstring''' A_ , A_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() A_ : Tuple = ids_tensor([1, 10] ,config.vocab_size ) A_ : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A_ : int = LlamaModel(_a ) original_model.to(_a ) original_model.eval() A_ : Tuple = original_model(_a ).last_hidden_state A_ : Union[str, Any] = original_model(_a ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A_ : Tuple = {"""type""": scaling_type, """factor""": 10.0} A_ : int = LlamaModel(_a ) scaled_model.to(_a ) scaled_model.eval() A_ : List[Any] = scaled_model(_a ).last_hidden_state A_ : Any = scaled_model(_a ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_a ,_a ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_a ,_a ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_a ,_a ,atol=1e-5 ) ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _a ( self : Tuple ): '''simple docstring''' A_ : Any = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : List[str] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf""" ,device_map="""auto""" ) A_ : str = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 A_ : Union[str, Any] = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A_ : str = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,_a ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _a ( self : str ): '''simple docstring''' A_ : Dict = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : Optional[int] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf""" ,device_map="""auto""" ) A_ : Tuple = model(torch.tensor(_a ) ) # Expected mean on dim = -1 A_ : str = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A_ : str = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,_a ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _a ( self : Union[str, Any] ): '''simple docstring''' A_ : Union[str, Any] = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : Optional[int] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ,device_map="""auto""" ) A_ : int = model(torch.tensor(_a ) ) # Expected mean on dim = -1 A_ : Union[str, Any] = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A_ : Optional[int] = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test""" ) @slow def _a ( self : Optional[Any] ): '''simple docstring''' A_ : Optional[int] = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : str = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf""" ,device_map="""auto""" ) A_ : Tuple = model(torch.tensor(_a ) ) A_ : Dict = torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # fmt: off A_ : List[str] = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,_a ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Model is curently gated""" ) @slow def _a ( self : Tuple ): '''simple docstring''' A_ : Union[str, Any] = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" A_ : List[str] = """Simply put, the theory of relativity states that """ A_ : Any = LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ) A_ : Union[str, Any] = tokenizer.encode(_a ,return_tensors="""pt""" ) A_ : List[str] = LlamaForCausalLM.from_pretrained( """meta-llama/Llama-2-13b-chat-hf""" ,device_map="""sequential""" ,use_safetensors=_a ) # greedy generation outputs A_ : str = model.generate(_a ,max_new_tokens=64 ,top_p=_a ,temperature=1 ,do_sample=_a ) A_ : Optional[Any] = tokenizer.decode(generated_ids[0] ,skip_special_tokens=_a ) self.assertEqual(_a ,_a )
665
0
from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBackboneConfig if is_timm_available(): import timm if is_torch_available(): from torch import Tensor class _lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE: Tuple = 'pixel_values' SCREAMING_SNAKE_CASE: Dict = False SCREAMING_SNAKE_CASE: int = TimmBackboneConfig def __init__( self , lowerCamelCase__ , **lowerCamelCase__ ): requires_backends(self , "timm" ) super().__init__(_a ) lowerCAmelCase_: List[str] = config if config.backbone is None: raise ValueError("backbone is not set in the config. Please set it to a timm model name." ) if config.backbone not in timm.list_models(): raise ValueError(F'''backbone {config.backbone} is not supported by timm.''' ) if hasattr(_a , "out_features" ) and config.out_features is not None: raise ValueError("out_features is not supported by TimmBackbone. Please use out_indices instead." ) lowerCAmelCase_: str = getattr(_a , "use_pretrained_backbone" , _a ) if pretrained is None: raise ValueError("use_pretrained_backbone is not set in the config. Please set it to True or False." ) # We just take the final layer by default. This matches the default for the transformers models. lowerCAmelCase_: Any = config.out_indices if getattr(_a , "out_indices" , _a ) is not None else (-1,) lowerCAmelCase_: Union[str, Any] = timm.create_model( config.backbone , pretrained=_a , features_only=config.features_only , in_chans=config.num_channels , out_indices=_a , **_a , ) # These are used to control the output of the model when called. If output_hidden_states is True, then # return_layers is modified to include all layers. lowerCAmelCase_: Dict = self._backbone.return_layers lowerCAmelCase_: Union[str, Any] = {layer["""module"""]: str(_a ) for i, layer in enumerate(self._backbone.feature_info.info )} super()._init_backbone(_a ) @classmethod def _a ( cls , lowerCamelCase__ , *lowerCamelCase__ , **lowerCamelCase__ ): requires_backends(cls , ["vision", "timm"] ) from ...models.timm_backbone import TimmBackboneConfig lowerCAmelCase_: List[str] = kwargs.pop("config" , TimmBackboneConfig() ) lowerCAmelCase_: Any = kwargs.pop("use_timm_backbone" , _a ) if not use_timm: raise ValueError("use_timm_backbone must be True for timm backbones" ) lowerCAmelCase_: Dict = kwargs.pop("num_channels" , config.num_channels ) lowerCAmelCase_: Any = kwargs.pop("features_only" , config.features_only ) lowerCAmelCase_: Tuple = kwargs.pop("use_pretrained_backbone" , config.use_pretrained_backbone ) lowerCAmelCase_: Union[str, Any] = kwargs.pop("out_indices" , config.out_indices ) lowerCAmelCase_: Dict = TimmBackboneConfig( backbone=_a , num_channels=_a , features_only=_a , use_pretrained_backbone=_a , out_indices=_a , ) return super()._from_config(_a , **_a ) def _a ( self , lowerCamelCase__ ): pass def _a ( self , lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None , **lowerCamelCase__ ): lowerCAmelCase_: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase_: Optional[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase_: Dict = output_attentions if output_attentions is not None else self.config.output_attentions if output_attentions: raise ValueError("Cannot output attentions for timm backbones at the moment" ) if output_hidden_states: # We modify the return layers to include all the stages of the backbone lowerCAmelCase_: Optional[int] = self._all_layers lowerCAmelCase_: Tuple = self._backbone(_a , **_a ) lowerCAmelCase_: Any = self._return_layers lowerCAmelCase_: Optional[Any] = tuple(hidden_states[i] for i in self.out_indices ) else: lowerCAmelCase_: Union[str, Any] = self._backbone(_a , **_a ) lowerCAmelCase_: List[Any] = None lowerCAmelCase_: List[str] = tuple(_a ) lowerCAmelCase_: int = tuple(_a ) if hidden_states is not None else None if not return_dict: lowerCAmelCase_: int = (feature_maps,) if output_hidden_states: lowerCAmelCase_: Dict = output + (hidden_states,) return output return BackboneOutput(feature_maps=_a , hidden_states=_a , attentions=_a )
613
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __magic_name__ = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' __magic_name__ = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' __magic_name__ = r'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def _a ( self : Optional[Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { """predictions""": datasets.Value("""string""" ), """references""": datasets.Value("""string""" ), } ) ,homepage="""https://github.com/hendrycks/math""" ,codebase_urls=["""https://github.com/hendrycks/math"""] ,) def _a ( self : List[Any] ,_a : Union[str, Any] ,_a : Optional[int] ): '''simple docstring''' A_ : Union[str, Any] = 0.0 for i, j in zip(_a ,_a ): n_correct += 1.0 if math_equivalence.is_equiv(_a ,_a ) else 0.0 A_ : List[str] = n_correct / len(_a ) return { "accuracy": accuracy, }
665
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : List[Any] = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""} UpperCAmelCase : Optional[Any] = { """vocab_file""": { """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json""", """allenai/longformer-large-4096""": ( """https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json""" ), """allenai/longformer-large-4096-finetuned-triviaqa""": ( """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json""" ), """allenai/longformer-base-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json""" ), """allenai/longformer-large-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json""" ), }, """merges_file""": { """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt""", """allenai/longformer-large-4096""": ( """https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt""" ), """allenai/longformer-large-4096-finetuned-triviaqa""": ( """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt""" ), """allenai/longformer-base-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt""" ), """allenai/longformer-large-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt""" ), }, } UpperCAmelCase : int = { """allenai/longformer-base-4096""": 4096, """allenai/longformer-large-4096""": 4096, """allenai/longformer-large-4096-finetuned-triviaqa""": 4096, """allenai/longformer-base-4096-extra.pos.embd.only""": 4096, """allenai/longformer-large-4096-extra.pos.embd.only""": 4096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _A ( ): """simple docstring""" a__ : Union[str, Any] =( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) a__ : Optional[Any] =bs[:] a__ : List[str] =0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE ) cs.append(2**8 + n ) n += 1 a__ : List[Any] =[chr(SCREAMING_SNAKE_CASE ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : int =set() a__ : int =word[0] for char in word[1:]: pairs.add((prev_char, char) ) a__ : List[str] =char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE): _lowercase : str = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : List[str] = ["""input_ids""", """attention_mask"""] def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__="replace" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__=False , **lowerCAmelCase__ , ) -> str: '''simple docstring''' a__ : Dict =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token a__ : Optional[int] =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token a__ : Optional[Any] =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token a__ : int =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token a__ : int =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token a__ : Optional[Any] =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it a__ : Any =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding="utf-8" ) as vocab_handle: a__ : str =json.load(_a ) a__ : Optional[int] ={v: k for k, v in self.encoder.items()} a__ : List[str] =errors # how to handle errors in decoding a__ : List[str] =bytes_to_unicode() a__ : str ={v: k for k, v in self.byte_encoder.items()} with open(_a , encoding="utf-8" ) as merges_handle: a__ : Any =merges_handle.read().split("\n" )[1:-1] a__ : str =[tuple(merge.split() ) for merge in bpe_merges] a__ : int =dict(zip(_a , range(len(_a ) ) ) ) a__ : List[Any] ={} a__ : Optional[int] =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions a__ : Optional[Any] =re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return len(self.encoder ) def _lowercase ( self ) -> Tuple: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' if token in self.cache: return self.cache[token] a__ : Optional[int] =tuple(_a ) a__ : Any =get_pairs(_a ) if not pairs: return token while True: a__ : Optional[Any] =min(_a , key=lambda lowerCAmelCase__ : self.bpe_ranks.get(_a , float("inf" ) ) ) if bigram not in self.bpe_ranks: break a__ : Dict =bigram a__ : int =[] a__ : Optional[Any] =0 while i < len(_a ): try: a__ : List[str] =word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) a__ : Tuple =j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 a__ : str =tuple(_a ) a__ : str =new_word if len(_a ) == 1: break else: a__ : int =get_pairs(_a ) a__ : Optional[int] =""" """.join(_a ) a__ : List[str] =word return word def _lowercase ( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' a__ : Any =[] for token in re.findall(self.pat , _a ): a__ : Any ="""""".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(" " ) ) return bpe_tokens def _lowercase ( self , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' return self.decoder.get(_a ) def _lowercase ( self , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' a__ : Optional[int] ="""""".join(_a ) a__ : Dict =bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[str]: '''simple docstring''' if not os.path.isdir(_a ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return a__ : int =os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) a__ : int =os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_a , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + "\n" ) a__ : int =0 with open(_a , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda lowerCAmelCase__ : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' " Please check that the tokenizer is not corrupted!" ) a__ : Dict =token_index writer.write(" ".join(_a ) + "\n" ) index += 1 return vocab_file, merge_file def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Dict: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a__ : int =[self.cls_token_id] a__ : int =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False ) -> str: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> str: '''simple docstring''' a__ : Union[str, Any] =[self.sep_token_id] a__ : Union[str, 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 + sep + token_ids_a + sep ) * [0] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=False , **lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' a__ : Any =kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): a__ : Optional[int] =""" """ + text return (text, kwargs)
563
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging __magic_name__ = logging.get_logger(__name__) # TODO: upload to AWS __magic_name__ = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = """retribert""" def __init__( self : int ,_a : Dict=30522 ,_a : List[Any]=768 ,_a : Optional[Any]=8 ,_a : str=12 ,_a : str=3072 ,_a : Tuple="gelu" ,_a : Optional[int]=0.1 ,_a : Dict=0.1 ,_a : List[Any]=512 ,_a : Union[str, Any]=2 ,_a : Tuple=0.02 ,_a : List[str]=1e-12 ,_a : Dict=True ,_a : Tuple=128 ,_a : Optional[int]=0 ,**_a : Tuple ,): '''simple docstring''' super().__init__(pad_token_id=_a ,**_a ) A_ : Dict = vocab_size A_ : int = hidden_size A_ : Union[str, Any] = num_hidden_layers A_ : Union[str, Any] = num_attention_heads A_ : Tuple = hidden_act A_ : int = intermediate_size A_ : Tuple = hidden_dropout_prob A_ : Optional[int] = attention_probs_dropout_prob A_ : int = max_position_embeddings A_ : Any = type_vocab_size A_ : Optional[int] = initializer_range A_ : Dict = layer_norm_eps A_ : str = share_encoders A_ : List[Any] = projection_dim
665
0
'''simple docstring''' def _UpperCamelCase ( lowerCAmelCase__: dict ) -> Any: SCREAMING_SNAKE_CASE_ = set() # To detect a back edge, keep track of vertices currently in the recursion stack SCREAMING_SNAKE_CASE_ = set() return any( node not in visited and depth_first_search(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) for node in graph ) def _UpperCamelCase ( lowerCAmelCase__: dict ,lowerCAmelCase__: int ,lowerCAmelCase__: set ,lowerCAmelCase__: set ) -> List[Any]: visited.add(lowerCAmelCase__ ) rec_stk.add(lowerCAmelCase__ ) for node in graph[vertex]: if node not in visited: if depth_first_search(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(lowerCAmelCase__ ) return False if __name__ == "__main__": from doctest import testmod testmod()
294
'''simple docstring''' import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'vocab_file': 'spiece.model'} __magic_name__ = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } __magic_name__ = { 'google/bigbird-roberta-base': 4_096, 'google/bigbird-roberta-large': 4_096, 'google/bigbird-base-trivia-itc': 4_096, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = ["""input_ids""", """attention_mask"""] a_ = [] def __init__( self : Optional[int] ,_a : int ,_a : Optional[Any]="<unk>" ,_a : int="<s>" ,_a : str="</s>" ,_a : Optional[Any]="<pad>" ,_a : Tuple="[SEP]" ,_a : Tuple="[MASK]" ,_a : Union[str, Any]="[CLS]" ,_a : Optional[Dict[str, Any]] = None ,**_a : Any ,): '''simple docstring''' A_ : Dict = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else bos_token A_ : Union[str, Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else eos_token A_ : Optional[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else unk_token A_ : Union[str, Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else pad_token A_ : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else cls_token A_ : Optional[int] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else sep_token # Mask token behave like a normal word, i.e. include the space before it A_ : List[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token A_ : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,pad_token=_a ,sep_token=_a ,mask_token=_a ,cls_token=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) A_ : Optional[int] = vocab_file A_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def _a ( self : Union[str, Any] ): '''simple docstring''' return self.sp_model.get_piece_size() def _a ( self : Optional[Any] ): '''simple docstring''' A_ : Tuple = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[Any] ): '''simple docstring''' A_ : Union[str, Any] = self.__dict__.copy() A_ : Union[str, Any] = None return state def __setstate__( self : List[Any] ,_a : Any ): '''simple docstring''' A_ : Tuple = d # for backward compatibility if not hasattr(self ,"""sp_model_kwargs""" ): A_ : Tuple = {} A_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _a ( self : Union[str, Any] ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def _a ( self : Optional[int] ,_a : str ): '''simple docstring''' return self.sp_model.piece_to_id(_a ) def _a ( self : int ,_a : Optional[int] ): '''simple docstring''' A_ : List[str] = self.sp_model.IdToPiece(_a ) return token def _a ( self : Dict ,_a : int ): '''simple docstring''' A_ : int = [] A_ : Any = """""" A_ : str = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token A_ : Dict = True A_ : Union[str, Any] = [] else: current_sub_tokens.append(_a ) A_ : str = False out_string += self.sp_model.decode(_a ) return out_string.strip() def _a ( self : int ,_a : List[int] ,_a : bool = False ,_a : bool = None ,_a : bool = True ,**_a : str ,): '''simple docstring''' A_ : Any = kwargs.pop("""use_source_tokenizer""" ,_a ) A_ : Union[str, Any] = self.convert_ids_to_tokens(_a ,skip_special_tokens=_a ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A_ : str = [] A_ : int = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) A_ : List[str] = [] sub_texts.append(_a ) else: current_sub_text.append(_a ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: A_ : Optional[int] = re.sub(r""" (\[(MASK|SEP)\])""" ,r"""\1""" ,""" """.join(_a ) ) else: A_ : Tuple = """""".join(_a ) A_ : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A_ : Optional[Any] = self.clean_up_tokenization(_a ) return clean_text else: return text def _a ( self : int ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A_ : int = os.path.join( _a ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,"""wb""" ) as fi: A_ : str = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,) def _a ( self : Optional[Any] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A_ : List[Any] = [self.cls_token_id] A_ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def _a ( self : Optional[int] ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] def _a ( self : Tuple ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' A_ : Tuple = [self.sep_token_id] A_ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
665
0
from __future__ import annotations from typing import TypedDict class SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowerCamelCase : str =42 lowerCamelCase : int =42 def snake_case_ (__A : str ) -> Tuple: if not isinstance(__A , __A ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__A ) )] def snake_case_ (__A : str ) -> str: if not isinstance(__A , __A ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) __lowerCAmelCase : Any = all_rotations(__A ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation __lowerCAmelCase : BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__A ), } return response def snake_case_ (__A : str , __A : int ) -> str: if not isinstance(__A , __A ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: __lowerCAmelCase : List[Any] = int(__A ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__A ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) __lowerCAmelCase : Any = [""""""] * len(__A ) for _ in range(len(__A ) ): for i in range(len(__A ) ): __lowerCAmelCase : int = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": __UpperCAmelCase = """Provide a string that I will generate its BWT transform: """ __UpperCAmelCase = input(entry_msg).strip() __UpperCAmelCase = bwt_transform(s) print( F'Burrows Wheeler transform for string \'{s}\' results ' F'in \'{result["bwt_string"]}\'' ) __UpperCAmelCase = reverse_bwt(result["""bwt_string"""], result["""idx_original_string"""]) print( F'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' F'we get original string \'{original_string}\'' )
651
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' a_ = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a_ = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def _a ( self : List[str] ,_a : int ,_a : Any ,_a : int ): '''simple docstring''' A_ : Dict = TextaTextGenerationPipeline(model=_a ,tokenizer=_a ) return generator, ["Something to write", "Something else"] def _a ( self : str ,_a : Union[str, Any] ,_a : int ): '''simple docstring''' A_ : Any = generator("""Something there""" ) self.assertEqual(_a ,[{"""generated_text""": ANY(_a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) ) A_ : List[Any] = generator(["""This is great !""", """Something else"""] ,num_return_sequences=2 ,do_sample=_a ) self.assertEqual( _a ,[ [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], ] ,) A_ : List[str] = generator( ["""This is great !""", """Something else"""] ,num_return_sequences=2 ,batch_size=2 ,do_sample=_a ) self.assertEqual( _a ,[ [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], ] ,) with self.assertRaises(_a ): generator(4 ) @require_torch def _a ( self : Union[str, Any] ): '''simple docstring''' A_ : int = pipeline("""text2text-generation""" ,model="""patrickvonplaten/t5-tiny-random""" ,framework="""pt""" ) # do_sample=False necessary for reproducibility A_ : Tuple = generator("""Something there""" ,do_sample=_a ) self.assertEqual(_a ,[{"""generated_text""": """"""}] ) A_ : Optional[int] = 3 A_ : Tuple = generator( """Something there""" ,num_return_sequences=_a ,num_beams=_a ,) A_ : Optional[Any] = [ {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """"""}, ] self.assertEqual(_a ,_a ) A_ : Optional[int] = generator("""This is a test""" ,do_sample=_a ,num_return_sequences=2 ,return_tensors=_a ) self.assertEqual( _a ,[ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ] ,) A_ : Dict = generator.model.config.eos_token_id A_ : Optional[int] = """<pad>""" A_ : List[Any] = generator( ["""This is a test""", """This is a second test"""] ,do_sample=_a ,num_return_sequences=2 ,batch_size=2 ,return_tensors=_a ,) self.assertEqual( _a ,[ [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], ] ,) @require_tf def _a ( self : List[Any] ): '''simple docstring''' A_ : Optional[int] = pipeline("""text2text-generation""" ,model="""patrickvonplaten/t5-tiny-random""" ,framework="""tf""" ) # do_sample=False necessary for reproducibility A_ : Dict = generator("""Something there""" ,do_sample=_a ) self.assertEqual(_a ,[{"""generated_text""": """"""}] )
665
0
from collections import defaultdict def _a ( lowerCamelCase, lowerCamelCase ): lowerCamelCase : List[Any] = first_str.lower().strip() lowerCamelCase : Union[str, Any] = second_str.lower().strip() # Remove whitespace lowerCamelCase : Union[str, Any] = first_str.replace(""" """, """""" ) lowerCamelCase : Union[str, Any] = second_str.replace(""" """, """""" ) # Strings of different lengths are not anagrams if len(lowerCamelCase ) != len(lowerCamelCase ): return False # Default values for count should be 0 lowerCamelCase : defaultdict[str, int] = defaultdict(lowerCamelCase ) # For each character in input strings, # increment count in the corresponding for i in range(len(lowerCamelCase ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() _lowerCamelCase =input("""Enter the first string """).strip() _lowerCamelCase =input("""Enter the second string """).strip() _lowerCamelCase =check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
681
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = """gpt_bigcode""" a_ = ["""past_key_values"""] a_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Optional[int] ,_a : Optional[int]=50257 ,_a : Dict=1024 ,_a : Union[str, Any]=768 ,_a : Union[str, Any]=12 ,_a : Union[str, Any]=12 ,_a : Tuple=None ,_a : int="gelu_pytorch_tanh" ,_a : Optional[Any]=0.1 ,_a : List[str]=0.1 ,_a : Union[str, Any]=0.1 ,_a : List[Any]=1e-5 ,_a : List[str]=0.02 ,_a : Any=True ,_a : Union[str, Any]=True ,_a : Tuple=50256 ,_a : Optional[int]=50256 ,_a : int=True ,_a : Optional[int]=True ,_a : Optional[int]=True ,**_a : List[str] ,): '''simple docstring''' A_ : Optional[Any] = vocab_size A_ : int = n_positions A_ : Union[str, Any] = n_embd A_ : int = n_layer A_ : Optional[int] = n_head A_ : Union[str, Any] = n_inner A_ : List[Any] = activation_function A_ : Dict = resid_pdrop A_ : int = embd_pdrop A_ : Optional[int] = attn_pdrop A_ : Union[str, Any] = layer_norm_epsilon A_ : int = initializer_range A_ : Union[str, Any] = scale_attn_weights A_ : List[str] = use_cache A_ : Tuple = attention_softmax_in_fpaa A_ : List[str] = scale_attention_softmax_in_fpaa A_ : Union[str, Any] = multi_query A_ : Any = bos_token_id A_ : Optional[int] = eos_token_id super().__init__(bos_token_id=_a ,eos_token_id=_a ,**_a )
665
0
'''simple docstring''' from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class a_ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = DistilBertTokenizer UpperCamelCase = DistilBertTokenizerFast UpperCamelCase = True @slow def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = DistilBertTokenizer.from_pretrained("""distilbert-base-uncased""" ) _SCREAMING_SNAKE_CASE = tokenizer.encode("""sequence builders""" , add_special_tokens=_a ) _SCREAMING_SNAKE_CASE = tokenizer.encode("""multi-sequence build""" , add_special_tokens=_a ) _SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(_a ) _SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
314
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} __magic_name__ = { 'vocab_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json' ), }, 'merges_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt' ), }, } __magic_name__ = { 'allenai/longformer-base-4096': 4_096, 'allenai/longformer-large-4096': 4_096, 'allenai/longformer-large-4096-finetuned-triviaqa': 4_096, 'allenai/longformer-base-4096-extra.pos.embd.only': 4_096, 'allenai/longformer-large-4096-extra.pos.embd.only': 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCamelCase ( ): A_ : Union[str, Any] = ( list(range(ord("""!""") , ord("""~""") + 1)) + list(range(ord("""¡""") , ord("""¬""") + 1)) + list(range(ord("""®""") , ord("""ÿ""") + 1)) ) A_ : Optional[Any] = bs[:] A_ : List[str] = 0 for b in range(2**8): if b not in bs: bs.append(lowerCamelCase) cs.append(2**8 + n) n += 1 A_ : List[Any] = [chr(lowerCamelCase) for n in cs] return dict(zip(lowerCamelCase , lowerCamelCase)) def lowerCamelCase ( lowerCamelCase : int): A_ : int = set() A_ : int = word[0] for char in word[1:]: pairs.add((prev_char, char)) A_ : List[str] = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = ["""input_ids""", """attention_mask"""] def __init__( self : int ,_a : Tuple ,_a : Union[str, Any] ,_a : Optional[Any]="replace" ,_a : Union[str, Any]="<s>" ,_a : Union[str, Any]="</s>" ,_a : int="</s>" ,_a : List[str]="<s>" ,_a : List[Any]="<unk>" ,_a : Any="<pad>" ,_a : Dict="<mask>" ,_a : Optional[int]=False ,**_a : List[Any] ,): '''simple docstring''' A_ : Dict = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else bos_token A_ : Optional[int] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else eos_token A_ : Optional[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else sep_token A_ : int = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else cls_token A_ : int = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else unk_token A_ : Optional[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it A_ : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token super().__init__( errors=_a ,bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,add_prefix_space=_a ,**_a ,) with open(_a ,encoding="""utf-8""" ) as vocab_handle: A_ : str = json.load(_a ) A_ : Optional[int] = {v: k for k, v in self.encoder.items()} A_ : List[str] = errors # how to handle errors in decoding A_ : List[str] = bytes_to_unicode() A_ : str = {v: k for k, v in self.byte_encoder.items()} with open(_a ,encoding="""utf-8""" ) as merges_handle: A_ : Any = merges_handle.read().split("""\n""" )[1:-1] A_ : str = [tuple(merge.split() ) for merge in bpe_merges] A_ : int = dict(zip(_a ,range(len(_a ) ) ) ) A_ : List[Any] = {} A_ : Optional[int] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions A_ : Optional[Any] = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property def _a ( self : Any ): '''simple docstring''' return len(self.encoder ) def _a ( self : str ): '''simple docstring''' return dict(self.encoder ,**self.added_tokens_encoder ) def _a ( self : int ,_a : int ): '''simple docstring''' if token in self.cache: return self.cache[token] A_ : Optional[int] = tuple(_a ) A_ : Any = get_pairs(_a ) if not pairs: return token while True: A_ : Optional[Any] = min(_a ,key=lambda _a : self.bpe_ranks.get(_a ,float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break A_ , A_ : Dict = bigram A_ : int = [] A_ : Optional[Any] = 0 while i < len(_a ): try: A_ : List[str] = word.index(_a ,_a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) A_ : Tuple = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 A_ : str = tuple(_a ) A_ : str = new_word if len(_a ) == 1: break else: A_ : int = get_pairs(_a ) A_ : Optional[int] = """ """.join(_a ) A_ : List[str] = word return word def _a ( self : Dict ,_a : Optional[int] ): '''simple docstring''' A_ : Any = [] for token in re.findall(self.pat ,_a ): A_ : Any = """""".join( self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(""" """ ) ) return bpe_tokens def _a ( self : Union[str, Any] ,_a : Optional[int] ): '''simple docstring''' return self.encoder.get(_a ,self.encoder.get(self.unk_token ) ) def _a ( self : int ,_a : Dict ): '''simple docstring''' return self.decoder.get(_a ) def _a ( self : Optional[int] ,_a : List[Any] ): '''simple docstring''' A_ : Optional[int] = """""".join(_a ) A_ : Dict = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" ,errors=self.errors ) return text def _a ( self : int ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A_ : int = os.path.join( _a ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) A_ : int = os.path.join( _a ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(_a ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=_a ,ensure_ascii=_a ) + """\n""" ) A_ : int = 0 with open(_a ,"""w""" ,encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,key=lambda _a : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' """ Please check that the tokenizer is not corrupted!""" ) A_ : Dict = token_index writer.write(""" """.join(_a ) + """\n""" ) index += 1 return vocab_file, merge_file def _a ( self : List[str] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A_ : int = [self.cls_token_id] A_ : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def _a ( self : Any ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' A_ : Union[str, Any] = [self.sep_token_id] A_ : Union[str, 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 + sep + token_ids_a + sep ) * [0] def _a ( self : str ,_a : Optional[int] ,_a : Union[str, Any]=False ,**_a : Dict ): '''simple docstring''' A_ : Any = kwargs.pop("""add_prefix_space""" ,self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): A_ : Optional[int] = """ """ + text return (text, kwargs)
665
0
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar __a : str = TypeVar("""T""") class _UpperCamelCase ( Generic[T] ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Any: '''simple docstring''' __lowercase = None __lowercase = len(_a ) __lowercase = [any_type for _ in range(self.N )] + arr __lowercase = fnc self.build() def _SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' for p in range(self.N - 1 , 0 , -1 ): __lowercase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' p += self.N __lowercase = v while p > 1: __lowercase = p // 2 __lowercase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: # noqa: E741 '''simple docstring''' __lowercase = l + self.N, r + self.N __lowercase = None while l <= r: if l % 2 == 1: __lowercase = self.st[l] if res is None else self.fn(_a , self.st[l] ) if r % 2 == 0: __lowercase = self.st[r] if res is None else self.fn(_a , self.st[r] ) __lowercase = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce __a : Optional[int] = [1, 1_0, -2, 9, -3, 8, 4, -7, 5, 6, 1_1, -1_2] __a : List[Any] = { 0: 7, 1: 2, 2: 6, 3: -1_4, 4: 5, 5: 4, 6: 7, 7: -1_0, 8: 9, 9: 1_0, 1_0: 1_2, 1_1: 1, } __a : List[str] = SegmentTree(test_array, min) __a : List[str] = SegmentTree(test_array, max) __a : List[Any] = SegmentTree(test_array, lambda a, b: a + b) def UpperCAmelCase ( ): """simple docstring""" for i in range(len(lowercase ) ): for j in range(lowercase , len(lowercase ) ): __lowercase = reduce(lowercase , test_array[i : j + 1] ) __lowercase = reduce(lowercase , test_array[i : j + 1] ) __lowercase = reduce(lambda lowercase , lowercase : a + b , test_array[i : j + 1] ) assert min_range == min_segment_tree.query(lowercase , lowercase ) assert max_range == max_segment_tree.query(lowercase , lowercase ) assert sum_range == sum_segment_tree.query(lowercase , lowercase ) test_all_segments() for index, value in test_updates.items(): __a : Optional[Any] = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
534
'''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_convbert import ConvBertTokenizer __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'vocab_file': 'vocab.txt'} __magic_name__ = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } __magic_name__ = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } __magic_name__ = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_INIT_CONFIGURATION a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = ConvBertTokenizer def __init__( self : str ,_a : Dict=None ,_a : List[Any]=None ,_a : Dict=True ,_a : List[str]="[UNK]" ,_a : Any="[SEP]" ,_a : str="[PAD]" ,_a : List[Any]="[CLS]" ,_a : List[str]="[MASK]" ,_a : Union[str, Any]=True ,_a : Any=None ,**_a : Optional[int] ,): '''simple docstring''' super().__init__( _a ,tokenizer_file=_a ,do_lower_case=_a ,unk_token=_a ,sep_token=_a ,pad_token=_a ,cls_token=_a ,mask_token=_a ,tokenize_chinese_chars=_a ,strip_accents=_a ,**_a ,) A_ : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" ,_a ) != do_lower_case or normalizer_state.get("""strip_accents""" ,_a ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" ,_a ) != tokenize_chinese_chars ): A_ : Dict = getattr(_a ,normalizer_state.pop("""type""" ) ) A_ : str = do_lower_case A_ : Any = strip_accents A_ : int = tokenize_chinese_chars A_ : Tuple = normalizer_class(**_a ) A_ : Any = do_lower_case def _a ( self : List[Any] ,_a : List[Any] ,_a : Any=None ): '''simple docstring''' A_ : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _a ( self : Dict ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' A_ : int = [self.sep_token_id] A_ : 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 _a ( self : int ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' A_ : List[Any] = self._tokenizer.model.save(_a ,name=_a ) return tuple(_a )
665
0
import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def lowerCAmelCase_ ( _lowercase : Union[str, Any]) -> Tuple: """simple docstring""" if hor == 128: a__ : List[Any] = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") a__ : List[Any] = (32, 128, 256) a__ : Tuple = ("""UpResnetBlock1D""", """UpResnetBlock1D""") elif hor == 32: a__ : str = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") a__ : Optional[Any] = (32, 64, 128, 256) a__ : Optional[int] = ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D""") a__ : Optional[int] = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''') a__ : Optional[Any] = model.state_dict() a__ : Optional[int] = { """down_block_types""": down_block_types, """block_out_channels""": block_out_channels, """up_block_types""": up_block_types, """layers_per_block""": 1, """use_timestep_embedding""": True, """out_block_type""": """OutConv1DBlock""", """norm_num_groups""": 8, """downsample_each_block""": False, """in_channels""": 14, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """flip_sin_to_cos""": False, """freq_shift""": 1, """sample_size""": 6_5536, """mid_block_type""": """MidResTemporalBlock1D""", """act_fn""": """mish""", } a__ : List[str] = UNetaDModel(**_lowercase) print(F'''length of state dict: {len(state_dict.keys())}''') print(F'''length of value function dict: {len(hf_value_function.state_dict().keys())}''') a__ : Dict = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys())) for k, v in mapping.items(): a__ : Any = state_dict.pop(_lowercase) hf_value_function.load_state_dict(_lowercase) torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''') with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , """w""") as f: json.dump(_lowercase , _lowercase) def lowerCAmelCase_ ( ) -> Tuple: """simple docstring""" a__ : Tuple = { """in_channels""": 14, """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""), """up_block_types""": (), """out_block_type""": """ValueFunction""", """mid_block_type""": """ValueFunctionMidBlock1D""", """block_out_channels""": (32, 64, 128, 256), """layers_per_block""": 1, """downsample_each_block""": True, """sample_size""": 6_5536, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """use_timestep_embedding""": True, """flip_sin_to_cos""": False, """freq_shift""": 1, """norm_num_groups""": 8, """act_fn""": """mish""", } a__ : Tuple = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""") a__ : List[str] = model a__ : Dict = UNetaDModel(**_lowercase) print(F'''length of state dict: {len(state_dict.keys())}''') print(F'''length of value function dict: {len(hf_value_function.state_dict().keys())}''') a__ : List[str] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys())) for k, v in mapping.items(): a__ : int = state_dict.pop(_lowercase) hf_value_function.load_state_dict(_lowercase) torch.save(hf_value_function.state_dict() , """hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin""") with open("""hub/hopper-medium-v2/value_function/config.json""" , """w""") as f: json.dump(_lowercase , _lowercase) if __name__ == "__main__": unet(32) # unet(128) value_function()
136
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all BART models at https://huggingface.co/models?filter=bart __magic_name__ = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, 'tokenizer_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json', }, } __magic_name__ = { 'facebook/bart-base': 1_024, 'facebook/bart-large': 1_024, 'facebook/bart-large-mnli': 1_024, 'facebook/bart-large-cnn': 1_024, 'facebook/bart-large-xsum': 1_024, 'yjernite/bart_eli5': 1_024, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = ["""input_ids""", """attention_mask"""] a_ = BartTokenizer def __init__( self : str ,_a : Any=None ,_a : Optional[int]=None ,_a : int=None ,_a : Optional[int]="replace" ,_a : Dict="<s>" ,_a : Optional[Any]="</s>" ,_a : Dict="</s>" ,_a : Tuple="<s>" ,_a : Optional[Any]="<unk>" ,_a : List[str]="<pad>" ,_a : int="<mask>" ,_a : str=False ,_a : List[str]=True ,**_a : Dict ,): '''simple docstring''' super().__init__( _a ,_a ,tokenizer_file=_a ,errors=_a ,bos_token=_a ,eos_token=_a ,sep_token=_a ,cls_token=_a ,unk_token=_a ,pad_token=_a ,mask_token=_a ,add_prefix_space=_a ,trim_offsets=_a ,**_a ,) A_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" ,_a ) != add_prefix_space: A_ : List[str] = getattr(_a ,pre_tok_state.pop("""type""" ) ) A_ : Optional[int] = add_prefix_space A_ : int = pre_tok_class(**_a ) A_ : str = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` A_ : str = """post_processor""" A_ : List[Any] = getattr(self.backend_tokenizer ,_a ,_a ) if tokenizer_component_instance: A_ : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: A_ : Tuple = tuple(state["""sep"""] ) if "cls" in state: A_ : Tuple = tuple(state["""cls"""] ) A_ : List[str] = False if state.get("""add_prefix_space""" ,_a ) != add_prefix_space: A_ : Dict = add_prefix_space A_ : Any = True if state.get("""trim_offsets""" ,_a ) != trim_offsets: A_ : Union[str, Any] = trim_offsets A_ : List[Any] = True if changes_to_apply: A_ : Optional[int] = getattr(_a ,state.pop("""type""" ) ) A_ : Tuple = component_class(**_a ) setattr(self.backend_tokenizer ,_a ,_a ) @property def _a ( self : List[str] ): '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _a ( self : Union[str, Any] ,_a : Any ): '''simple docstring''' A_ : int = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else value A_ : List[Any] = value def _a ( self : str ,*_a : str ,**_a : Optional[int] ): '''simple docstring''' A_ : Optional[Any] = kwargs.get("""is_split_into_words""" ,_a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*_a ,**_a ) def _a ( self : str ,*_a : List[Any] ,**_a : str ): '''simple docstring''' A_ : List[str] = kwargs.get("""is_split_into_words""" ,_a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' """to use it with pretokenized inputs.""" ) return super()._encode_plus(*_a ,**_a ) def _a ( self : Optional[int] ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' A_ : str = self._tokenizer.model.save(_a ,name=_a ) return tuple(_a ) def _a ( self : str ,_a : Optional[int] ,_a : int=None ): '''simple docstring''' A_ : Optional[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _a ( self : Optional[int] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' A_ : Dict = [self.sep_token_id] A_ : 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 + sep + token_ids_a + sep ) * [0]
665
0
'''simple docstring''' def UpperCAmelCase__( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" def merge(_SCREAMING_SNAKE_CASE : list,_SCREAMING_SNAKE_CASE : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(_SCREAMING_SNAKE_CASE ) <= 1: return collection __A= len(_SCREAMING_SNAKE_CASE ) // 2 return merge(merge_sort(collection[:mid] ),merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase__ = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase__ = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
186
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase ( lowerCamelCase : Optional[Any] , lowerCamelCase : Any , lowerCamelCase : Union[str, Any] , lowerCamelCase : Tuple , lowerCamelCase : str): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file A_ : int = TapasConfig.from_json_file(lowerCamelCase) # set absolute/relative position embeddings parameter A_ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": A_ : Optional[int] = TapasForQuestionAnswering(config=lowerCamelCase) elif task == "WTQ": # run_task_main.py hparams A_ : Tuple = 4 A_ : Optional[Any] = True # hparam_utils.py hparams A_ : Any = 0.66_4694 A_ : str = 0.20_7951 A_ : Any = 0.12_1194 A_ : str = True A_ : Dict = True A_ : int = False A_ : int = 0.035_2513 A_ : Tuple = TapasForQuestionAnswering(config=lowerCamelCase) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams A_ : int = 4 A_ : Union[str, Any] = False # hparam_utils.py hparams A_ : Dict = 36.4519 A_ : List[Any] = 0.90_3421 A_ : Any = 222.088 A_ : Optional[Any] = True A_ : Optional[int] = True A_ : Optional[Any] = True A_ : Optional[int] = 0.76_3141 A_ : Any = TapasForQuestionAnswering(config=lowerCamelCase) elif task == "TABFACT": A_ : Any = TapasForSequenceClassification(config=lowerCamelCase) elif task == "MLM": A_ : List[Any] = TapasForMaskedLM(config=lowerCamelCase) elif task == "INTERMEDIATE_PRETRAINING": A_ : Union[str, Any] = TapasModel(config=lowerCamelCase) else: raise ValueError(F'Task {task} not supported.') print(F'Building PyTorch model from configuration: {config}') # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCamelCase , lowerCamelCase , lowerCamelCase) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}') model.save_pretrained(lowerCamelCase) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}') A_ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512) tokenizer.save_pretrained(lowerCamelCase) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell) if __name__ == "__main__": __magic_name__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __magic_name__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
665
0
'''simple docstring''' import re from filelock import FileLock try: import nltk lowercase__ =True except (ImportError, ModuleNotFoundError): lowercase__ =False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def UpperCamelCase_ ( A__ ): re.sub("""<n>""" , """""" , A__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(A__ ) )
263
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = ["""vqvae"""] def __init__( self : Optional[Any] ,_a : AutoencoderKL ,_a : UNetaDConditionModel ,_a : Mel ,_a : Union[DDIMScheduler, DDPMScheduler] ,): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ,mel=_a ,vqvae=_a ) def _a ( self : str ): '''simple docstring''' return 50 if isinstance(self.scheduler ,_a ) else 1000 @torch.no_grad() def __call__( self : Optional[int] ,_a : int = 1 ,_a : str = None ,_a : np.ndarray = None ,_a : int = 0 ,_a : int = 0 ,_a : int = None ,_a : torch.Generator = None ,_a : float = 0 ,_a : float = 0 ,_a : torch.Generator = None ,_a : float = 0 ,_a : torch.Tensor = None ,_a : torch.Tensor = None ,_a : int=True ,): '''simple docstring''' A_ : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(_a ) A_ : Union[str, Any] = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: A_ : Tuple = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: A_ : int = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) ,generator=_a ,device=self.device ,) A_ : List[Any] = noise A_ : str = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(_a ,_a ) A_ : Any = self.mel.audio_slice_to_image(_a ) A_ : Union[str, Any] = np.frombuffer(input_image.tobytes() ,dtype="""uint8""" ).reshape( (input_image.height, input_image.width) ) A_ : Optional[Any] = (input_image / 255) * 2 - 1 A_ : Union[str, Any] = torch.tensor(input_image[np.newaxis, :, :] ,dtype=torch.float ).to(self.device ) if self.vqvae is not None: A_ : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(_a ,0 ) ).latent_dist.sample( generator=_a )[0] A_ : List[str] = self.vqvae.config.scaling_factor * input_images if start_step > 0: A_ : Any = self.scheduler.add_noise(_a ,_a ,self.scheduler.timesteps[start_step - 1] ) A_ : Tuple = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) A_ : Tuple = int(mask_start_secs * pixels_per_second ) A_ : str = int(mask_end_secs * pixels_per_second ) A_ : int = self.scheduler.add_noise(_a ,_a ,torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet ,_a ): A_ : Optional[Any] = self.unet(_a ,_a ,_a )["""sample"""] else: A_ : List[Any] = self.unet(_a ,_a )["""sample"""] if isinstance(self.scheduler ,_a ): A_ : Dict = self.scheduler.step( model_output=_a ,timestep=_a ,sample=_a ,eta=_a ,generator=_a ,)["""prev_sample"""] else: A_ : Any = self.scheduler.step( model_output=_a ,timestep=_a ,sample=_a ,generator=_a ,)["""prev_sample"""] if mask is not None: if mask_start > 0: A_ : Tuple = mask[:, step, :, :mask_start] if mask_end > 0: A_ : List[str] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance A_ : str = 1 / self.vqvae.config.scaling_factor * images A_ : Union[str, Any] = self.vqvae.decode(_a )["""sample"""] A_ : int = (images / 2 + 0.5).clamp(0 ,1 ) A_ : str = images.cpu().permute(0 ,2 ,3 ,1 ).numpy() A_ : Optional[int] = (images * 255).round().astype("""uint8""" ) A_ : List[Any] = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(_a ,mode="""RGB""" ).convert("""L""" ) for _ in images) ) A_ : Tuple = [self.mel.image_to_audio(_a ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(_a )[:, np.newaxis, :] ) ,**ImagePipelineOutput(_a ) ) @torch.no_grad() def _a ( self : Union[str, Any] ,_a : List[Image.Image] ,_a : int = 50 ): '''simple docstring''' assert isinstance(self.scheduler ,_a ) self.scheduler.set_timesteps(_a ) A_ : Optional[Any] = np.array( [np.frombuffer(image.tobytes() ,dtype="""uint8""" ).reshape((1, image.height, image.width) ) for image in images] ) A_ : List[str] = (sample / 255) * 2 - 1 A_ : Optional[int] = torch.Tensor(_a ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps ,(0,) ) ): A_ : List[str] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps A_ : Any = self.scheduler.alphas_cumprod[t] A_ : List[Any] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) A_ : str = 1 - alpha_prod_t A_ : List[str] = self.unet(_a ,_a )["""sample"""] A_ : str = (1 - alpha_prod_t_prev) ** 0.5 * model_output A_ : Union[str, Any] = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) A_ : Optional[int] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def _a ( _a : torch.Tensor ,_a : torch.Tensor ,_a : float ): '''simple docstring''' A_ : List[Any] = acos(torch.dot(torch.flatten(_a ) ,torch.flatten(_a ) ) / torch.norm(_a ) / torch.norm(_a ) ) return sin((1 - alpha) * theta ) * xa / sin(_a ) + sin(alpha * theta ) * xa / sin(_a )
665
0
from jiwer import compute_measures import datasets _lowercase = """\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n""" _lowercase = """\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n""" _lowercase = """\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> wer = datasets.load_metric(\"wer\")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase_ ( datasets.Metric ): def _snake_case ( self ) -> Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', ] , ) def _snake_case ( self , __A=None , __A=None , __A=False ) -> List[Any]: if concatenate_texts: return compute_measures(_a , _a )["wer"] else: SCREAMING_SNAKE_CASE_ : Tuple =0 SCREAMING_SNAKE_CASE_ : str =0 for prediction, reference in zip(_a , _a ): SCREAMING_SNAKE_CASE_ : Dict =compute_measures(_a , _a ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
443
'''simple docstring''' import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __magic_name__ = 16 __magic_name__ = 32 def lowerCamelCase ( lowerCamelCase : Accelerator , lowerCamelCase : int = 16): A_ : Any = AutoTokenizer.from_pretrained("""bert-base-cased""") A_ : str = load_dataset("""glue""" , """mrpc""") def tokenize_function(lowerCamelCase : Dict): # max_length=None => use the model max length (it's actually the default) A_ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCamelCase , max_length=lowerCamelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): A_ : Tuple = datasets.map( lowerCamelCase , batched=lowerCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A_ : List[str] = tokenized_datasets.rename_column("""label""" , """labels""") def collate_fn(lowerCamelCase : Tuple): # On TPU it's best to pad everything to the same length or training will be very slow. A_ : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": A_ : List[Any] = 16 elif accelerator.mixed_precision != "no": A_ : Any = 8 else: A_ : Tuple = None return tokenizer.pad( lowerCamelCase , padding="""longest""" , max_length=lowerCamelCase , pad_to_multiple_of=lowerCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. A_ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase , drop_last=lowerCamelCase) A_ : str = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase , drop_last=(accelerator.mixed_precision == """fp8""") , ) return train_dataloader, eval_dataloader def lowerCamelCase ( lowerCamelCase : Any , lowerCamelCase : Dict): # Initialize accelerator A_ : Tuple = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A_ : List[Any] = config["""lr"""] A_ : List[Any] = int(config["""num_epochs"""]) A_ : int = int(config["""seed"""]) A_ : Dict = int(config["""batch_size"""]) A_ : Union[str, Any] = evaluate.load("""glue""" , """mrpc""") # If the batch size is too big we use gradient accumulation A_ : int = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: A_ : Any = batch_size // MAX_GPU_BATCH_SIZE A_ : Union[str, Any] = MAX_GPU_BATCH_SIZE set_seed(lowerCamelCase) A_ , A_ : List[str] = get_dataloaders(lowerCamelCase , lowerCamelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A_ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=lowerCamelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). A_ : str = model.to(accelerator.device) # Instantiate optimizer A_ : str = AdamW(params=model.parameters() , lr=lowerCamelCase) # Instantiate scheduler A_ : Tuple = get_linear_schedule_with_warmup( optimizer=lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(lowerCamelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A_ , A_ , A_ , A_ , A_ : Union[str, Any] = accelerator.prepare( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase) # Now we train the model for epoch in range(lowerCamelCase): model.train() for step, batch in enumerate(lowerCamelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) A_ : Optional[int] = model(**lowerCamelCase) A_ : List[Any] = outputs.loss A_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(lowerCamelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCamelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): A_ : Union[str, Any] = model(**lowerCamelCase) A_ : Any = outputs.logits.argmax(dim=-1) A_ , A_ : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""])) metric.add_batch( predictions=lowerCamelCase , references=lowerCamelCase , ) A_ : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , lowerCamelCase) def lowerCamelCase ( ): A_ : Optional[int] = argparse.ArgumentParser(description="""Simple example of training script.""") parser.add_argument( """--mixed_precision""" , type=lowerCamelCase , default=lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""") A_ : Dict = parser.parse_args() A_ : Dict = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(lowerCamelCase , lowerCamelCase) if __name__ == "__main__": main()
665
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a : Optional[int] = { """configuration_conditional_detr""": [ """CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConditionalDetrConfig""", """ConditionalDetrOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Any = ["""ConditionalDetrFeatureExtractor"""] a : int = ["""ConditionalDetrImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : int = [ """CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConditionalDetrForObjectDetection""", """ConditionalDetrForSegmentation""", """ConditionalDetrModel""", """ConditionalDetrPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys a : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
613
'''simple docstring''' import functools def lowerCamelCase ( lowerCamelCase : list[int] , lowerCamelCase : list[int]): # Validation if not isinstance(lowerCamelCase , lowerCamelCase) or not all(isinstance(lowerCamelCase , lowerCamelCase) for day in days): raise ValueError("""The parameter days should be a list of integers""") if len(lowerCamelCase) != 3 or not all(isinstance(lowerCamelCase , lowerCamelCase) for cost in costs): raise ValueError("""The parameter costs should be a list of three integers""") if len(lowerCamelCase) == 0: return 0 if min(lowerCamelCase) <= 0: raise ValueError("""All days elements should be greater than 0""") if max(lowerCamelCase) >= 366: raise ValueError("""All days elements should be less than 366""") A_ : Tuple = set(lowerCamelCase) @functools.cache def dynamic_programming(lowerCamelCase : int) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1) return min( costs[0] + dynamic_programming(index + 1) , costs[1] + dynamic_programming(index + 7) , costs[2] + dynamic_programming(index + 30) , ) return dynamic_programming(1) if __name__ == "__main__": import doctest doctest.testmod()
665
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
563
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowerCamelCase ( lowerCamelCase : NDArray[floataa] , lowerCamelCase : NDArray[floataa] , lowerCamelCase : list[int] , lowerCamelCase : int , ): A_ , A_ : int = coefficient_matrix.shape A_ , A_ : Union[str, Any] = constant_matrix.shape if rowsa != colsa: A_ : Any = F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(lowerCamelCase) if colsa != 1: A_ : Tuple = F'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(lowerCamelCase) if rowsa != rowsa: A_ : Dict = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(lowerCamelCase) if len(lowerCamelCase) != rowsa: A_ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'matrix but received {len(lowerCamelCase)} and {rowsa}' ) raise ValueError(lowerCamelCase) if iterations <= 0: raise ValueError("""Iterations must be at least 1""") A_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1) A_ , A_ : int = table.shape strictly_diagonally_dominant(lowerCamelCase) # Iterates the whole matrix for given number of times for _ in range(lowerCamelCase): A_ : List[Any] = [] for row in range(lowerCamelCase): A_ : int = 0 for col in range(lowerCamelCase): if col == row: A_ : List[str] = table[row][col] elif col == cols - 1: A_ : str = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] A_ : Union[str, Any] = (temp + val) / denom new_val.append(lowerCamelCase) A_ : Tuple = new_val return [float(lowerCamelCase) for i in new_val] def lowerCamelCase ( lowerCamelCase : NDArray[floataa]): A_ , A_ : Dict = table.shape A_ : Union[str, Any] = True for i in range(0 , lowerCamelCase): A_ : str = 0 for j in range(0 , cols - 1): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""") return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
665
0
'''simple docstring''' from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers SCREAMING_SNAKE_CASE : Dict = [ "python", "tqdm", "regex", "requests", "packaging", "filelock", "numpy", "tokenizers", "huggingface-hub", "safetensors", "accelerate", "pyyaml", ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py") def _UpperCamelCase ( lowerCAmelCase__: Optional[int] ,lowerCAmelCase__: Tuple=None ) -> Union[str, Any]: require_version(deps[pkg] ,lowerCAmelCase__ )
294
'''simple docstring''' def lowerCamelCase ( lowerCamelCase : str , lowerCamelCase : str): A_ : Any = len(lowerCamelCase) A_ : Optional[Any] = len(lowerCamelCase) A_ : Optional[int] = [[False for _ in range(m + 1)] for _ in range(n + 1)] A_ : Union[str, Any] = True for i in range(lowerCamelCase): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: A_ : Optional[int] = True if a[i].islower(): A_ : List[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
665
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[int] =KandinskyInpaintPipeline lowerCamelCase : Optional[Any] =["prompt", "image_embeds", "negative_image_embeds", "image", "mask_image"] lowerCamelCase : List[Any] =[ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", "mask_image", ] lowerCamelCase : str =[ "generator", "height", "width", "latents", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCamelCase : Optional[Any] =False @property def SCREAMING_SNAKE_CASE ( self : int ) -> str: """simple docstring""" return 32 @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: """simple docstring""" return 32 @property def SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: """simple docstring""" return self.time_input_dim @property def SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: """simple docstring""" return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: """simple docstring""" return 1_00 @property def SCREAMING_SNAKE_CASE ( self : int ) -> int: """simple docstring""" __lowerCAmelCase : List[str] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase : Optional[int] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=10_05 , ) __lowerCAmelCase : List[Any] = MultilingualCLIP(_a ) __lowerCAmelCase : Any = text_encoder.eval() return text_encoder @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase : Optional[int] = { """in_channels""": 9, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } __lowerCAmelCase : Union[str, Any] = UNetaDConditionModel(**_a ) return model @property def SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase : Dict = VQModel(**self.dummy_movq_kwargs ) return model def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Any = self.dummy_text_encoder __lowerCAmelCase : Tuple = self.dummy_tokenizer __lowerCAmelCase : List[Any] = self.dummy_unet __lowerCAmelCase : Any = self.dummy_movq __lowerCAmelCase : Any = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule="""linear""" , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=_a , set_alpha_to_one=_a , steps_offset=1 , prediction_type="""epsilon""" , thresholding=_a , ) __lowerCAmelCase : List[Any] = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : str=0 ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Any = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_a ) ).to(_a ) __lowerCAmelCase : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_a ) # create init_image __lowerCAmelCase : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_a ) ).to(_a ) __lowerCAmelCase : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCAmelCase : str = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((2_56, 2_56) ) # create mask __lowerCAmelCase : Any = np.ones((64, 64) , dtype=np.floataa ) __lowerCAmelCase : List[str] = 0 if str(_a ).startswith("""mps""" ): __lowerCAmelCase : Union[str, Any] = torch.manual_seed(_a ) else: __lowerCAmelCase : int = torch.Generator(device=_a ).manual_seed(_a ) __lowerCAmelCase : List[str] = { """prompt""": """horse""", """image""": init_image, """mask_image""": mask, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 2, """guidance_scale""": 4.0, """output_type""": """np""", } return inputs def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Any = """cpu""" __lowerCAmelCase : Optional[int] = self.get_dummy_components() __lowerCAmelCase : Tuple = self.pipeline_class(**_a ) __lowerCAmelCase : int = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __lowerCAmelCase : Optional[Any] = pipe(**self.get_dummy_inputs(_a ) ) __lowerCAmelCase : int = output.images __lowerCAmelCase : Optional[int] = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] __lowerCAmelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCAmelCase : Optional[int] = image_from_tuple[0, -3:, -3:, -1] print(f'''image.shape {image.shape}''' ) assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : Tuple = np.array( [0.832_6919, 0.7379_0467, 0.2091_8581, 0.930_9612, 0.551_1791, 0.4371_3328, 0.551_3321, 0.4992_2934, 0.5949_7786] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: """simple docstring""" __lowerCAmelCase : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy""" ) __lowerCAmelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) __lowerCAmelCase : Optional[Any] = np.ones((7_68, 7_68) , dtype=np.floataa ) __lowerCAmelCase : Any = 0 __lowerCAmelCase : Tuple = """a hat""" __lowerCAmelCase : str = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_a ) __lowerCAmelCase : Dict = KandinskyInpaintPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-inpaint""" , torch_dtype=torch.floataa ) __lowerCAmelCase : Optional[Any] = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) __lowerCAmelCase : List[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) __lowerCAmelCase : str = pipe_prior( _a , generator=_a , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() __lowerCAmelCase : str = pipeline( _a , image=_a , mask_image=_a , image_embeds=_a , negative_image_embeds=_a , generator=_a , num_inference_steps=1_00 , height=7_68 , width=7_68 , output_type="""np""" , ) __lowerCAmelCase : Optional[int] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(_a , _a )
651
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class __lowerCAmelCase : '''simple docstring''' a_ = 42 a_ = 42 class __lowerCAmelCase : '''simple docstring''' def __init__( self : Union[str, Any] ,_a : int ): '''simple docstring''' A_ : list[list[Edge]] = [[] for _ in range(_a )] A_ : List[Any] = size def __getitem__( self : int ,_a : int ): '''simple docstring''' return iter(self._graph[vertex] ) @property def _a ( self : str ): '''simple docstring''' return self._size def _a ( self : str ,_a : int ,_a : int ,_a : int ): '''simple docstring''' if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(_a ,_a ) ) def _a ( self : Dict ,_a : int ,_a : int ): '''simple docstring''' A_ : Tuple = deque([start_vertex] ) A_ : list[int | None] = [None] * self.size A_ : Union[str, Any] = 0 while queue: A_ : List[Any] = queue.popleft() A_ : Tuple = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: A_ : Union[str, Any] = current_distance + edge.weight A_ : Optional[Any] = distances[edge.destination_vertex] if ( isinstance(_a ,_a ) and new_distance >= dest_vertex_distance ): continue A_ : Tuple = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
665
0
from typing import TYPE_CHECKING from ..utils import _LazyModule _lowerCamelCase ={ """config""": [ """EXTERNAL_DATA_FORMAT_SIZE_LIMIT""", """OnnxConfig""", """OnnxConfigWithPast""", """OnnxSeq2SeqConfigWithPast""", """PatchingSpec""", ], """convert""": ["""export""", """validate_model_outputs"""], """features""": ["""FeaturesManager"""], """utils""": ["""ParameterFormat""", """compute_serialized_parameters_size"""], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
681
'''simple docstring''' def lowerCamelCase ( lowerCamelCase : int = 10**9): A_ : Optional[int] = 1 A_ : int = 2 A_ : List[Any] = 0 A_ : Optional[Any] = 0 A_ : str = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value A_ : Optional[Any] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f"""{solution() = }""")
665
0
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = {"""vocab_file""": """vocab.txt"""} lowercase_ = { """vocab_file""": { """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""", }, } lowercase_ = { """openbmb/cpm-ant-10b""": 1_024, } def lowerCamelCase ( __lowerCamelCase : Any ) ->List[Any]: _SCREAMING_SNAKE_CASE = collections.OrderedDict() with open(__lowerCamelCase , """r""" , encoding="""utf-8""" ) as reader: _SCREAMING_SNAKE_CASE = reader.readlines() for index, token in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = token.rstrip("""\n""" ) _SCREAMING_SNAKE_CASE = index return vocab class a_ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , A , A="<unk>" , A=200 ) -> Optional[int]: _SCREAMING_SNAKE_CASE = vocab _SCREAMING_SNAKE_CASE = unk_token _SCREAMING_SNAKE_CASE = max_input_chars_per_word def snake_case_( self , A ) -> int: _SCREAMING_SNAKE_CASE = list(_a ) if len(_a ) > self.max_input_chars_per_word: return [self.unk_token] _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = [] while start < len(_a ): _SCREAMING_SNAKE_CASE = len(_a ) _SCREAMING_SNAKE_CASE = None while start < end: _SCREAMING_SNAKE_CASE = """""".join(chars[start:end] ) if substr in self.vocab: _SCREAMING_SNAKE_CASE = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(_a ) _SCREAMING_SNAKE_CASE = end return sub_tokens class a_ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = VOCAB_FILES_NAMES UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase = ['''input_ids''', '''attention_mask'''] UpperCamelCase = False def __init__( self , A , A="<d>" , A="</d>" , A="<s>" , A="</s>" , A="<pad>" , A="<unk>" , A="</n>" , A="</_>" , A="left" , **A , ) -> Optional[int]: requires_backends(self , ["""jieba"""] ) super().__init__( bod_token=_a , eod_token=_a , bos_token=_a , eos_token=_a , pad_token=_a , unk_token=_a , line_token=_a , space_token=_a , padding_side=_a , **_a , ) _SCREAMING_SNAKE_CASE = bod_token _SCREAMING_SNAKE_CASE = eod_token _SCREAMING_SNAKE_CASE = load_vocab(_a ) _SCREAMING_SNAKE_CASE = self.encoder[space_token] _SCREAMING_SNAKE_CASE = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] _SCREAMING_SNAKE_CASE = collections.OrderedDict(sorted(self.encoder.items() , key=lambda A : x[1] ) ) _SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} _SCREAMING_SNAKE_CASE = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def snake_case_( self ) -> List[Any]: return self.encoder[self.bod_token] @property def snake_case_( self ) -> List[Any]: return self.encoder[self.eod_token] @property def snake_case_( self ) -> int: return self.encoder["\n"] @property def snake_case_( self ) -> int: return len(self.encoder ) def snake_case_( self ) -> Optional[Any]: return dict(self.encoder , **self.added_tokens_encoder ) def snake_case_( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = [] for x in jieba.cut(_a , cut_all=_a ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(_a ) ) return output_tokens def snake_case_( self , A , **A ) -> Tuple: _SCREAMING_SNAKE_CASE = [i for i in token_ids if i >= 0] _SCREAMING_SNAKE_CASE = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(_a , **_a ) def snake_case_( self , A ) -> List[str]: return token in self.encoder def snake_case_( self , A ) -> Optional[Any]: return "".join(_a ) def snake_case_( self , A ) -> Any: return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def snake_case_( self , A ) -> int: return self.decoder.get(_a , self.unk_token ) def snake_case_( self , A , A = None ) -> List[str]: if os.path.isdir(_a ): _SCREAMING_SNAKE_CASE = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) else: _SCREAMING_SNAKE_CASE = (filename_prefix + """-""" if filename_prefix else """""") + save_directory _SCREAMING_SNAKE_CASE = 0 if " " in self.encoder: _SCREAMING_SNAKE_CASE = self.encoder[""" """] del self.encoder[" "] if "\n" in self.encoder: _SCREAMING_SNAKE_CASE = self.encoder["""\n"""] del self.encoder["\n"] _SCREAMING_SNAKE_CASE = collections.OrderedDict(sorted(self.encoder.items() , key=lambda A : x[1] ) ) with open(_a , """w""" , encoding="""utf-8""" ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( f'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.' """ Please check that the vocabulary is not corrupted!""" ) _SCREAMING_SNAKE_CASE = token_index writer.write(token + """\n""" ) index += 1 return (vocab_file,) def snake_case_( self , A , A = None ) -> Optional[int]: if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def snake_case_( self , A , A = None , A = False ) -> Optional[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is not None: return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) return [1] + ([0] * len(_a ))
314
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def lowerCamelCase ( ): A_ : Optional[int] = ArgumentParser("""Accelerate CLI tool""" , usage="""accelerate <command> [<args>]""" , allow_abbrev=lowerCamelCase) A_ : Optional[int] = parser.add_subparsers(help="""accelerate command helpers""") # Register commands get_config_parser(subparsers=lowerCamelCase) env_command_parser(subparsers=lowerCamelCase) launch_command_parser(subparsers=lowerCamelCase) tpu_command_parser(subparsers=lowerCamelCase) test_command_parser(subparsers=lowerCamelCase) # Let's go A_ : Dict = parser.parse_args() if not hasattr(lowerCamelCase , """func"""): parser.print_help() exit(1) # Run args.func(lowerCamelCase) if __name__ == "__main__": main()
665
0
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" __lowercase = TapasConfig.from_json_file(lowercase ) # set absolute/relative position embeddings parameter __lowercase = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": __lowercase = TapasForQuestionAnswering(config=lowercase ) elif task == "WTQ": # run_task_main.py hparams __lowercase = 4 __lowercase = True # hparam_utils.py hparams __lowercase = 0.664694 __lowercase = 0.207951 __lowercase = 0.121194 __lowercase = True __lowercase = True __lowercase = False __lowercase = 0.0352513 __lowercase = TapasForQuestionAnswering(config=lowercase ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams __lowercase = 4 __lowercase = False # hparam_utils.py hparams __lowercase = 36.4519 __lowercase = 0.903421 __lowercase = 222.088 __lowercase = True __lowercase = True __lowercase = True __lowercase = 0.763141 __lowercase = TapasForQuestionAnswering(config=lowercase ) elif task == "TABFACT": __lowercase = TapasForSequenceClassification(config=lowercase ) elif task == "MLM": __lowercase = TapasForMaskedLM(config=lowercase ) elif task == "INTERMEDIATE_PRETRAINING": __lowercase = TapasModel(config=lowercase ) else: raise ValueError(F"Task {task} not supported." ) print(F"Building PyTorch model from configuration: {config}" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowercase , lowercase , lowercase ) # Save pytorch-model (weights and configuration) print(F"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(lowercase ) # Save tokenizer files print(F"Save tokenizer files to {pytorch_dump_path}" ) __lowercase = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowercase ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __a : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--task""", default="""SQA""", type=str, help="""Model task for which to convert a checkpoint. Defaults to SQA.""" ) parser.add_argument( """--reset_position_index_per_cell""", default=False, action="""store_true""", help="""Whether to use relative position embeddings or not. Defaults to True.""", ) parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--tapas_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained TAPAS model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __a : Dict = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
534
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __magic_name__ = { 'configuration_altclip': [ 'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig', ], 'processing_altclip': ['AltCLIPProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'AltCLIPPreTrainedModel', 'AltCLIPModel', 'AltCLIPTextModel', 'AltCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
0
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 snake_case__ : """simple docstring""" def __init__( self , __lowercase , __lowercase=1_3 , __lowercase=7 , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=9_9 , __lowercase=6_4 , __lowercase=3_2 , __lowercase=5 , __lowercase=4 , __lowercase=3_7 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=5_1_2 , __lowercase=1_6 , __lowercase=2 , __lowercase=0.0_2 , __lowercase=3 , __lowercase=4 , __lowercase=None , ) -> Optional[int]: """simple docstring""" a__ : Dict = parent a__ : Optional[Any] = batch_size a__ : Dict = seq_length a__ : List[str] = is_training a__ : Optional[int] = use_input_mask a__ : Dict = use_token_type_ids a__ : Optional[Any] = use_labels a__ : Dict = vocab_size a__ : List[Any] = hidden_size a__ : Union[str, Any] = embedding_size a__ : List[Any] = num_hidden_layers a__ : List[Any] = num_attention_heads a__ : Union[str, Any] = intermediate_size a__ : Union[str, Any] = hidden_act a__ : int = hidden_dropout_prob a__ : Union[str, Any] = attention_probs_dropout_prob a__ : Tuple = max_position_embeddings a__ : List[str] = type_vocab_size a__ : List[Any] = type_sequence_label_size a__ : List[str] = initializer_range a__ : Any = num_labels a__ : Dict = num_choices a__ : Union[str, Any] = scope def SCREAMING_SNAKE_CASE__( self ) -> Any: """simple docstring""" a__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Optional[int] = None if self.use_input_mask: a__ : str = random_attention_mask([self.batch_size, self.seq_length] ) a__ : List[str] = None if self.use_token_type_ids: a__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : Any = None a__ : List[Any] = None a__ : int = None if self.use_labels: a__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : Optional[Any] = 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 SCREAMING_SNAKE_CASE__( 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=_a , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Optional[Any]: """simple docstring""" a__ : str = MegatronBertModel(config=_a ) model.to(_a ) model.eval() a__ : List[str] = model(_a , attention_mask=_a , token_type_ids=_a ) a__ : List[Any] = model(_a , token_type_ids=_a ) a__ : Union[str, Any] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> str: """simple docstring""" a__ : Optional[Any] = MegatronBertForMaskedLM(config=_a ) model.to(_a ) model.eval() a__ : List[str] = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Tuple: """simple docstring""" a__ : Optional[Any] = MegatronBertForCausalLM(config=_a ) model.to(_a ) model.eval() a__ : Dict = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Optional[Any]: """simple docstring""" a__ : List[Any] = MegatronBertForNextSentencePrediction(config=_a ) model.to(_a ) model.eval() a__ : Tuple = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: """simple docstring""" a__ : List[Any] = MegatronBertForPreTraining(config=_a ) model.to(_a ) model.eval() a__ : List[str] = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , next_sentence_label=_a , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> List[str]: """simple docstring""" a__ : Optional[Any] = MegatronBertForQuestionAnswering(config=_a ) model.to(_a ) model.eval() a__ : str = model( _a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Optional[int]: """simple docstring""" a__ : int = self.num_labels a__ : List[Any] = MegatronBertForSequenceClassification(_a ) model.to(_a ) model.eval() a__ : str = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Tuple: """simple docstring""" a__ : Any = self.num_labels a__ : List[Any] = MegatronBertForTokenClassification(config=_a ) model.to(_a ) model.eval() a__ : Optional[int] = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: """simple docstring""" a__ : Optional[int] = self.num_choices a__ : Optional[Any] = MegatronBertForMultipleChoice(config=_a ) model.to(_a ) model.eval() a__ : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Optional[Any] = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__( self ) -> Tuple: """simple docstring""" a__ : Dict = self.prepare_config_and_inputs() ( a__ ) : List[Any] = config_and_inputs a__ : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class snake_case__ (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __lowerCAmelCase :Dict = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) __lowerCAmelCase :List[Any] = ( { "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 {} ) __lowerCAmelCase :int = True # test_resize_embeddings = False __lowerCAmelCase :Tuple = False def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase=False ) -> int: """simple docstring""" a__ : str = super()._prepare_for_class(_a , _a , return_labels=_a ) if return_labels: if model_class in get_values(_a ): a__ : List[str] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_a ) a__ : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) return inputs_dict def SCREAMING_SNAKE_CASE__( self ) -> Optional[int]: """simple docstring""" a__ : str = MegatronBertModelTester(self ) a__ : Union[str, Any] = ConfigTester(self , config_class=_a , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE__( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__( self ) -> int: """simple docstring""" a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*_a ) def SCREAMING_SNAKE_CASE__( self ) -> str: """simple docstring""" a__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*_a ) def SCREAMING_SNAKE_CASE__( self ) -> Optional[Any]: """simple docstring""" a__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*_a ) def SCREAMING_SNAKE_CASE__( self ) -> str: """simple docstring""" a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*_a ) def SCREAMING_SNAKE_CASE__( self ) -> Optional[Any]: """simple docstring""" a__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*_a ) def SCREAMING_SNAKE_CASE__( self ) -> Union[str, Any]: """simple docstring""" a__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*_a ) def SCREAMING_SNAKE_CASE__( self ) -> str: """simple docstring""" a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*_a ) def SCREAMING_SNAKE_CASE__( self ) -> int: """simple docstring""" a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*_a ) def lowerCAmelCase_ ( _lowercase : Tuple) -> List[Any]: """simple docstring""" return torch.tensor( _lowercase , dtype=torch.long , device=_lowercase , ) _lowercase : int =1E-4 @require_torch @require_sentencepiece @require_tokenizers class snake_case__ (unittest.TestCase ): """simple docstring""" @slow @unittest.skip("""Model is not available.""" ) def SCREAMING_SNAKE_CASE__( self ) -> Dict: """simple docstring""" a__ : Dict = """nvidia/megatron-bert-uncased-345m""" if "MYDIR" in os.environ: a__ : int = os.path.join(os.environ["""MYDIR"""] , _a ) a__ : List[str] = MegatronBertModel.from_pretrained(_a ) model.to(_a ) model.half() a__ : Any = _long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]] ) with torch.no_grad(): a__ : Optional[Any] = model(_a )[0] a__ : List[Any] = torch.Size((1, 9, 1_0_2_4) ) self.assertEqual(output.shape , _a ) a__ : Dict = [-0.6_0_4_0, -0.2_5_1_7, -0.1_0_2_5, 0.3_4_2_0, -0.6_7_5_8, -0.0_0_1_7, -0.1_0_8_9, -0.1_9_9_0, 0.5_7_2_8] for ii in range(3 ): for jj in range(3 ): a__ : List[Any] = output[0, ii, jj] a__ : Optional[Any] = expected[3 * ii + jj] a__ : Any = """ii={} jj={} a={} b={}""".format(_a , _a , _a , _a ) self.assertTrue(math.isclose(_a , _a , rel_tol=_a , abs_tol=_a ) , msg=_a )
136
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __magic_name__ = {'configuration_yolos': ['YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'YolosConfig', 'YolosOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['YolosFeatureExtractor'] __magic_name__ = ['YolosImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST', 'YolosForObjectDetection', 'YolosModel', 'YolosPreTrainedModel', ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { '''microsoft/wavlm-base''': '''https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json''', # See all WavLM models at https://huggingface.co/models?filter=wavlm } class a__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' A : Any = '''wavlm''' def __init__( self : List[Any] , lowerCAmelCase_ : Dict=32 , lowerCAmelCase_ : List[Any]=768 , lowerCAmelCase_ : Tuple=12 , lowerCAmelCase_ : Union[str, Any]=12 , lowerCAmelCase_ : Dict=3_072 , lowerCAmelCase_ : int="gelu" , lowerCAmelCase_ : Tuple=0.1 , lowerCAmelCase_ : Optional[Any]=0.1 , lowerCAmelCase_ : int=0.1 , lowerCAmelCase_ : Optional[int]=0.0 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : Union[str, Any]=0.1 , lowerCAmelCase_ : Tuple=0.02 , lowerCAmelCase_ : Union[str, Any]=1E-5 , lowerCAmelCase_ : Any="group" , lowerCAmelCase_ : Optional[int]="gelu" , lowerCAmelCase_ : Dict=(512, 512, 512, 512, 512, 512, 512) , lowerCAmelCase_ : str=(5, 2, 2, 2, 2, 2, 2) , lowerCAmelCase_ : List[str]=(10, 3, 3, 3, 3, 2, 2) , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : Union[str, Any]=128 , lowerCAmelCase_ : List[str]=16 , lowerCAmelCase_ : List[str]=320 , lowerCAmelCase_ : Tuple=800 , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[int]=0.05 , lowerCAmelCase_ : Union[str, Any]=10 , lowerCAmelCase_ : Tuple=2 , lowerCAmelCase_ : List[Any]=0.0 , lowerCAmelCase_ : int=10 , lowerCAmelCase_ : Optional[int]=320 , lowerCAmelCase_ : int=2 , lowerCAmelCase_ : Optional[int]=0.1 , lowerCAmelCase_ : Dict=100 , lowerCAmelCase_ : List[Any]=256 , lowerCAmelCase_ : List[str]=256 , lowerCAmelCase_ : List[str]=0.1 , lowerCAmelCase_ : Any="mean" , lowerCAmelCase_ : Tuple=False , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : int=256 , lowerCAmelCase_ : Union[str, Any]=(512, 512, 512, 512, 1_500) , lowerCAmelCase_ : Optional[Any]=(5, 3, 3, 1, 1) , lowerCAmelCase_ : Union[str, Any]=(1, 2, 3, 1, 1) , lowerCAmelCase_ : str=512 , lowerCAmelCase_ : int=80 , lowerCAmelCase_ : str=0 , lowerCAmelCase_ : Optional[Any]=1 , lowerCAmelCase_ : Any=2 , lowerCAmelCase_ : int=False , lowerCAmelCase_ : Optional[int]=3 , lowerCAmelCase_ : Union[str, Any]=2 , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : Tuple=None , **lowerCAmelCase_ : Any , ) -> Optional[int]: super().__init__(**_a , pad_token_id=_a , bos_token_id=_a , eos_token_id=_a ) __A= hidden_size __A= feat_extract_norm __A= feat_extract_activation __A= list(_a ) __A= list(_a ) __A= list(_a ) __A= conv_bias __A= num_buckets __A= max_bucket_distance __A= num_conv_pos_embeddings __A= num_conv_pos_embedding_groups __A= len(self.conv_dim ) __A= num_hidden_layers __A= intermediate_size __A= hidden_act __A= num_attention_heads __A= hidden_dropout __A= attention_dropout __A= activation_dropout __A= feat_proj_dropout __A= final_dropout __A= layerdrop __A= layer_norm_eps __A= initializer_range __A= num_ctc_classes __A= vocab_size __A= do_stable_layer_norm __A= use_weighted_layer_sum __A= classifier_proj_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)`, 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= apply_spec_augment __A= mask_time_prob __A= mask_time_length __A= mask_time_min_masks __A= mask_feature_prob __A= mask_feature_length # parameters for pretraining with codevector quantized representations __A= num_codevectors_per_group __A= num_codevector_groups __A= contrastive_logits_temperature __A= num_negatives __A= codevector_dim __A= proj_codevector_dim __A= diversity_loss_weight # ctc loss __A= ctc_loss_reduction __A= ctc_zero_infinity # adapter __A= add_adapter __A= adapter_kernel_size __A= adapter_stride __A= num_adapter_layers __A= output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __A= classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __A= list(_a ) __A= list(_a ) __A= list(_a ) __A= xvector_output_dim @property def lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: return functools.reduce(operator.mul , self.conv_stride , 1 )
186
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
665
0
'''simple docstring''' from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : def __init__( self , UpperCAmelCase , UpperCAmelCase=3 , UpperCAmelCase=32 , UpperCAmelCase=3 , UpperCAmelCase=10 , UpperCAmelCase=[10, 20, 30, 40] , UpperCAmelCase=[1, 1, 2, 1] , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase="relu" , UpperCAmelCase=3 , UpperCAmelCase=None , ): a_ = parent a_ = batch_size a_ = image_size a_ = num_channels a_ = embeddings_size a_ = hidden_sizes a_ = depths a_ = is_training a_ = use_labels a_ = hidden_act a_ = num_labels a_ = scope a_ = len(_a ) def lowerCAmelCase__ ( self ): a_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a_ = None if self.use_labels: a_ = ids_tensor([self.batch_size] , self.num_labels ) a_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase__ ( self ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def lowerCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): a_ = TFRegNetModel(config=_a ) a_ = model(_a , training=_a ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): a_ = self.num_labels a_ = TFRegNetForImageClassification(_a ) a_ = model(_a , labels=_a , training=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__ ( self ): a_ = self.prepare_config_and_inputs() a_ = config_and_inputs a_ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class a_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): lowerCamelCase__ : Optional[Any] = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowerCamelCase__ : Dict = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowerCamelCase__ : List[str] = False lowerCamelCase__ : str = False lowerCamelCase__ : int = False lowerCamelCase__ : int = False lowerCamelCase__ : int = False def lowerCAmelCase__ ( self ): a_ = TFRegNetModelTester(self ) a_ = ConfigTester(self , config_class=_a , has_text_modality=_a ) def lowerCAmelCase__ ( self ): return @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def lowerCAmelCase__ ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def lowerCAmelCase__ ( self ): super().test_keras_fit() @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def lowerCAmelCase__ ( self ): pass def lowerCAmelCase__ ( self ): a_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a_ = model_class(_a ) a_ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a_ = [*signature.parameters.keys()] a_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def lowerCAmelCase__ ( self ): a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def lowerCAmelCase__ ( self ): def check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): a_ = model_class(_a ) a_ = model(**self._prepare_for_class(_a , _a ) , training=_a ) a_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a_ = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) a_ = self.model_tester.prepare_config_and_inputs_for_common() a_ = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: a_ = layer_type a_ = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a_ = True check_hidden_states_output(_a , _a , _a ) def lowerCAmelCase__ ( self ): a_ = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase={} ): a_ = model(_a , return_dict=_a , **_a ) a_ = model(_a , return_dict=_a , **_a ).to_tuple() def recursive_check(UpperCAmelCase , UpperCAmelCase ): if isinstance(_a , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_a , _a ): recursive_check(_a , _a ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(_a , _a ) ) , msg=( """Tuple and dict output are not equal. Difference:""" f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(_a , _a ) for model_class in self.all_model_classes: a_ = model_class(_a ) a_ = self._prepare_for_class(_a , _a ) a_ = self._prepare_for_class(_a , _a ) check_equivalence(_a , _a , _a ) a_ = self._prepare_for_class(_a , _a , return_labels=_a ) a_ = self._prepare_for_class(_a , _a , return_labels=_a ) check_equivalence(_a , _a , _a ) a_ = self._prepare_for_class(_a , _a ) a_ = self._prepare_for_class(_a , _a ) check_equivalence(_a , _a , _a , {"""output_hidden_states""": True} ) a_ = self._prepare_for_class(_a , _a , return_labels=_a ) a_ = self._prepare_for_class(_a , _a , return_labels=_a ) check_equivalence(_a , _a , _a , {"""output_hidden_states""": True} ) def lowerCAmelCase__ ( self ): a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def lowerCAmelCase__ ( self ): for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ = TFRegNetModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def UpperCamelCase_ ( ): a_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class a_ ( unittest.TestCase ): @cached_property def lowerCAmelCase__ ( self ): return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCAmelCase__ ( self ): a_ = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) a_ = self.default_image_processor a_ = prepare_img() a_ = image_processor(images=_a , return_tensors="""tf""" ) # forward pass a_ = model(**_a , training=_a ) # verify the logits a_ = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , _a ) a_ = tf.constant([-0.41_80, -1.50_51, -3.48_36] ) tf.debugging.assert_near(outputs.logits[0, :3] , _a , atol=1e-4 )
263
'''simple docstring''' def lowerCamelCase ( lowerCamelCase : Tuple): A_ : str = [0] * len(lowerCamelCase) A_ : Union[str, Any] = [] A_ : Union[str, Any] = [] A_ : Tuple = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCamelCase)): if indegree[i] == 0: queue.append(lowerCamelCase) while queue: A_ : Any = queue.pop(0) cnt += 1 topo.append(lowerCamelCase) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(lowerCamelCase) if cnt != len(lowerCamelCase): print("""Cycle exists""") else: print(lowerCamelCase) # Adjacency List of Graph __magic_name__ = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
665
0
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class lowercase_ : def __init__( self , __A , __A=13 , __A=10 , __A=3 , __A=2 , __A=2 , __A=True , __A=True , __A=32 , __A=5 , __A=4 , __A=37 , __A="gelu" , __A=0.1 , __A=0.1 , __A=10 , __A=0.02 , __A="divided_space_time" , __A=None , ) -> str: SCREAMING_SNAKE_CASE_ : Dict =parent SCREAMING_SNAKE_CASE_ : Dict =batch_size SCREAMING_SNAKE_CASE_ : str =image_size SCREAMING_SNAKE_CASE_ : Dict =num_channels SCREAMING_SNAKE_CASE_ : int =patch_size SCREAMING_SNAKE_CASE_ : Any =num_frames SCREAMING_SNAKE_CASE_ : Any =is_training SCREAMING_SNAKE_CASE_ : Tuple =use_labels SCREAMING_SNAKE_CASE_ : List[Any] =hidden_size SCREAMING_SNAKE_CASE_ : List[Any] =num_hidden_layers SCREAMING_SNAKE_CASE_ : Any =num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] =intermediate_size SCREAMING_SNAKE_CASE_ : List[str] =hidden_act SCREAMING_SNAKE_CASE_ : Union[str, Any] =hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[int] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Any =attention_type SCREAMING_SNAKE_CASE_ : Optional[Any] =initializer_range SCREAMING_SNAKE_CASE_ : str =scope SCREAMING_SNAKE_CASE_ : List[str] =num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE_ : Any =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE_ : Dict =(num_frames) * self.num_patches_per_frame + 1 def _snake_case ( self ) -> str: SCREAMING_SNAKE_CASE_ : int =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : List[Any] =None if self.use_labels: SCREAMING_SNAKE_CASE_ : Tuple =ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE_ : Tuple =self.get_config() return config, pixel_values, labels def _snake_case ( self ) -> str: SCREAMING_SNAKE_CASE_ : int =TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) SCREAMING_SNAKE_CASE_ : int =self.num_labels return config def _snake_case ( self , __A , __A , __A ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ : List[str] =TimesformerModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE_ : str =model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self , __A , __A , __A ) -> Tuple: SCREAMING_SNAKE_CASE_ : Tuple =TimesformerForVideoClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE_ : str =model(_a ) # verify the logits shape SCREAMING_SNAKE_CASE_ : Tuple =torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , _a ) def _snake_case ( self ) -> Dict: SCREAMING_SNAKE_CASE_ : Tuple =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ : Tuple =config_and_inputs SCREAMING_SNAKE_CASE_ : Any ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): __lowerCamelCase = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () __lowerCamelCase = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def _snake_case ( self ) -> Dict: SCREAMING_SNAKE_CASE_ : Tuple =TimesformerModelTester(self ) SCREAMING_SNAKE_CASE_ : List[str] =ConfigTester( self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def _snake_case ( self , __A , __A , __A=False ) -> Optional[int]: SCREAMING_SNAKE_CASE_ : List[Any] =copy.deepcopy(_a ) if return_labels: if model_class in get_values(_a ): SCREAMING_SNAKE_CASE_ : Optional[Any] =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) return inputs_dict def _snake_case ( self ) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def _snake_case ( self ) -> Tuple: pass def _snake_case ( self ) -> List[Any]: SCREAMING_SNAKE_CASE_ : Tuple =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : List[str] =model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE_ : str =model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def _snake_case ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ : str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Dict =model_class(_a ) SCREAMING_SNAKE_CASE_ : Dict =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : str =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : str =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def _snake_case ( self ) -> List[str]: SCREAMING_SNAKE_CASE_ : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _snake_case ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*_a ) @slow def _snake_case ( self ) -> Dict: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Dict =TimesformerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def _snake_case ( self ) -> List[str]: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE_ : Dict =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[str] =True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Tuple =self.model_tester.seq_length SCREAMING_SNAKE_CASE_ : List[Any] =self.model_tester.num_frames SCREAMING_SNAKE_CASE_ : Optional[Any] =True SCREAMING_SNAKE_CASE_ : str =False SCREAMING_SNAKE_CASE_ : Any =True SCREAMING_SNAKE_CASE_ : List[Any] =model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[Any] =model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE_ : int =outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE_ : Dict =True SCREAMING_SNAKE_CASE_ : Optional[Any] =model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] =model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE_ : List[str] =outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) SCREAMING_SNAKE_CASE_ : int =len(_a ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE_ : Optional[int] =True SCREAMING_SNAKE_CASE_ : Any =True SCREAMING_SNAKE_CASE_ : Union[str, Any] =model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[str] =model(**self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + 1 , len(_a ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] =outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def _snake_case ( self ) -> List[Any]: def check_hidden_states_output(__A , __A , __A ): SCREAMING_SNAKE_CASE_ : Optional[int] =model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Union[str, Any] =model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE_ : str =outputs.hidden_states SCREAMING_SNAKE_CASE_ : Dict =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(_a ) , _a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[Any] =True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Optional[int] =True check_hidden_states_output(_a , _a , _a ) def SCREAMING_SNAKE_CASE_ ( ) -> Dict: SCREAMING_SNAKE_CASE_ : List[Any] =hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' ) SCREAMING_SNAKE_CASE_ : int =np.load(UpperCAmelCase_ ) return list(UpperCAmelCase_ ) @require_torch @require_vision class lowercase_ ( unittest.TestCase ): @cached_property def _snake_case ( self ) -> Union[str, Any]: return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def _snake_case ( self ) -> List[Any]: SCREAMING_SNAKE_CASE_ : Any =TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( _a ) SCREAMING_SNAKE_CASE_ : Optional[Any] =self.default_image_processor SCREAMING_SNAKE_CASE_ : Dict =prepare_video() SCREAMING_SNAKE_CASE_ : Dict =image_processor(video[:8] , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] =model(**_a ) # verify the logits SCREAMING_SNAKE_CASE_ : Optional[Any] =torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , _a ) SCREAMING_SNAKE_CASE_ : Dict =torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
443
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class __lowerCAmelCase : '''simple docstring''' def __init__( self : Optional[int] ,_a : List[Any] ,_a : Dict=13 ,_a : List[str]=7 ,_a : Dict=True ,_a : List[Any]=True ,_a : Dict=False ,_a : Optional[int]=True ,_a : List[Any]=99 ,_a : Any=32 ,_a : Optional[int]=5 ,_a : List[Any]=4 ,_a : int=37 ,_a : List[Any]="gelu" ,_a : List[str]=0.1 ,_a : Union[str, Any]=0.1 ,_a : Any=512 ,_a : int=16 ,_a : Optional[int]=2 ,_a : Any=0.02 ,_a : Any=3 ,_a : Any=4 ,_a : List[str]=None ,): '''simple docstring''' A_ : List[str] = parent A_ : Any = batch_size A_ : Tuple = seq_length A_ : List[str] = is_training A_ : Tuple = use_input_mask A_ : Dict = use_token_type_ids A_ : List[Any] = use_labels A_ : Union[str, Any] = vocab_size A_ : Any = hidden_size A_ : str = num_hidden_layers A_ : Optional[Any] = num_attention_heads A_ : str = intermediate_size A_ : Tuple = hidden_act A_ : Any = hidden_dropout_prob A_ : Any = attention_probs_dropout_prob A_ : List[str] = max_position_embeddings A_ : int = type_vocab_size A_ : Union[str, Any] = type_sequence_label_size A_ : Any = initializer_range A_ : List[Any] = num_labels A_ : Optional[Any] = num_choices A_ : List[Any] = scope def _a ( self : Optional[int] ): '''simple docstring''' A_ : str = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A_ : int = None if self.use_input_mask: A_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A_ : Dict = None if self.use_token_type_ids: A_ : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A_ : str = None A_ : Any = None A_ : str = None if self.use_labels: A_ : Dict = 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_ : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self : Optional[Any] ): '''simple docstring''' return LlamaConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=_a ,initializer_range=self.initializer_range ,) def _a ( self : Union[str, Any] ,_a : Optional[Any] ,_a : Optional[Any] ,_a : Any ,_a : Any ,_a : Optional[Any] ,_a : Optional[Any] ,_a : Tuple ): '''simple docstring''' A_ : Any = LlamaModel(config=_a ) model.to(_a ) model.eval() A_ : Optional[Any] = model(_a ,attention_mask=_a ) A_ : Optional[int] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self : Optional[int] ,_a : int ,_a : List[str] ,_a : Any ,_a : Any ,_a : Dict ,_a : List[str] ,_a : Optional[int] ,_a : Any ,_a : List[str] ,): '''simple docstring''' A_ : List[str] = True A_ : Union[str, Any] = LlamaModel(_a ) model.to(_a ) model.eval() A_ : Tuple = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,) A_ : List[Any] = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,) A_ : int = model(_a ,attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self : Any ,_a : Any ,_a : Optional[int] ,_a : List[Any] ,_a : List[Any] ,_a : Dict ,_a : Tuple ,_a : Optional[int] ,_a : List[Any] ,_a : Union[str, Any] ,): '''simple docstring''' A_ : List[Any] = LlamaForCausalLM(config=_a ) model.to(_a ) model.eval() A_ : Dict = model(_a ,attention_mask=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self : str ,_a : List[Any] ,_a : Dict ,_a : str ,_a : Tuple ,_a : Tuple ,_a : Tuple ,_a : Optional[Any] ,_a : Dict ,_a : Union[str, Any] ,): '''simple docstring''' A_ : Optional[Any] = True A_ : Any = True A_ : Tuple = LlamaForCausalLM(config=_a ) model.to(_a ) model.eval() # first forward pass A_ : Optional[int] = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,use_cache=_a ,) A_ : Tuple = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A_ : int = ids_tensor((self.batch_size, 3) ,config.vocab_size ) A_ : List[Any] = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and A_ : Tuple = torch.cat([input_ids, next_tokens] ,dim=-1 ) A_ : int = torch.cat([input_mask, next_mask] ,dim=-1 ) A_ : List[str] = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,output_hidden_states=_a ,)["""hidden_states"""][0] A_ : Any = model( _a ,attention_mask=_a ,encoder_hidden_states=_a ,encoder_attention_mask=_a ,past_key_values=_a ,output_hidden_states=_a ,)["""hidden_states"""][0] # select random slice A_ : List[str] = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A_ : str = output_from_no_past[:, -3:, random_slice_idx].detach() A_ : int = 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(_a ,_a ,atol=1e-3 ) ) def _a ( self : Optional[Any] ): '''simple docstring''' A_ : int = self.prepare_config_and_inputs() ( ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ) : Any = config_and_inputs A_ : int = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' a_ = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () a_ = (LlamaForCausalLM,) if is_torch_available() else () a_ = ( { """feature-extraction""": LlamaModel, """text-classification""": LlamaForSequenceClassification, """text-generation""": LlamaForCausalLM, """zero-shot""": LlamaForSequenceClassification, } if is_torch_available() else {} ) a_ = False a_ = False def _a ( self : List[Any] ): '''simple docstring''' A_ : Union[str, Any] = LlamaModelTester(self ) A_ : List[str] = ConfigTester(self ,config_class=_a ,hidden_size=37 ) def _a ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() def _a ( self : Optional[Any] ): '''simple docstring''' A_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self : Optional[Any] ): '''simple docstring''' A_ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A_ : Dict = type self.model_tester.create_and_check_model(*_a ) def _a ( self : List[Any] ): '''simple docstring''' A_ , A_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() A_ : List[str] = 3 A_ : Any = input_dict["""input_ids"""] A_ : Union[str, Any] = input_ids.ne(1 ).to(_a ) A_ : Union[str, Any] = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A_ : List[Any] = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() A_ : int = model(_a ,attention_mask=_a ,labels=_a ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self : Dict ): '''simple docstring''' A_ , A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() A_ : str = 3 A_ : Union[str, Any] = """single_label_classification""" A_ : Union[str, Any] = input_dict["""input_ids"""] A_ : List[Any] = input_ids.ne(1 ).to(_a ) A_ : Dict = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) A_ : List[Any] = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() A_ : List[str] = model(_a ,attention_mask=_a ,labels=_a ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self : Optional[Any] ): '''simple docstring''' A_ , A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() A_ : Dict = 3 A_ : Dict = """multi_label_classification""" A_ : Any = input_dict["""input_ids"""] A_ : Optional[Any] = input_ids.ne(1 ).to(_a ) A_ : List[str] = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) A_ : Optional[int] = LlamaForSequenceClassification(_a ) model.to(_a ) model.eval() A_ : Any = model(_a ,attention_mask=_a ,labels=_a ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""LLaMA buffers include complex numbers, which breaks this test""" ) def _a ( self : Any ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _a ( self : Optional[Any] ,_a : List[Any] ): '''simple docstring''' A_ , A_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() A_ : Tuple = ids_tensor([1, 10] ,config.vocab_size ) A_ : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A_ : int = LlamaModel(_a ) original_model.to(_a ) original_model.eval() A_ : Tuple = original_model(_a ).last_hidden_state A_ : Union[str, Any] = original_model(_a ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A_ : Tuple = {"""type""": scaling_type, """factor""": 10.0} A_ : int = LlamaModel(_a ) scaled_model.to(_a ) scaled_model.eval() A_ : List[Any] = scaled_model(_a ).last_hidden_state A_ : Any = scaled_model(_a ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_a ,_a ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_a ,_a ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_a ,_a ,atol=1e-5 ) ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _a ( self : Tuple ): '''simple docstring''' A_ : Any = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : List[str] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf""" ,device_map="""auto""" ) A_ : str = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 A_ : Union[str, Any] = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A_ : str = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,_a ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _a ( self : str ): '''simple docstring''' A_ : Dict = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : Optional[int] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf""" ,device_map="""auto""" ) A_ : Tuple = model(torch.tensor(_a ) ) # Expected mean on dim = -1 A_ : str = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A_ : str = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,_a ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _a ( self : Union[str, Any] ): '''simple docstring''' A_ : Union[str, Any] = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : Optional[int] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ,device_map="""auto""" ) A_ : int = model(torch.tensor(_a ) ) # Expected mean on dim = -1 A_ : Union[str, Any] = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A_ : Optional[int] = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test""" ) @slow def _a ( self : Optional[Any] ): '''simple docstring''' A_ : Optional[int] = [1, 306, 4658, 278, 6593, 310, 2834, 338] A_ : str = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf""" ,device_map="""auto""" ) A_ : Tuple = model(torch.tensor(_a ) ) A_ : Dict = torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,_a ,atol=1e-2 ,rtol=1e-2 ) # fmt: off A_ : List[str] = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,_a ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Model is curently gated""" ) @slow def _a ( self : Tuple ): '''simple docstring''' A_ : Union[str, Any] = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" A_ : List[str] = """Simply put, the theory of relativity states that """ A_ : Any = LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ) A_ : Union[str, Any] = tokenizer.encode(_a ,return_tensors="""pt""" ) A_ : List[str] = LlamaForCausalLM.from_pretrained( """meta-llama/Llama-2-13b-chat-hf""" ,device_map="""sequential""" ,use_safetensors=_a ) # greedy generation outputs A_ : str = model.generate(_a ,max_new_tokens=64 ,top_p=_a ,temperature=1 ,do_sample=_a ) A_ : Optional[Any] = tokenizer.decode(generated_ids[0] ,skip_special_tokens=_a ) self.assertEqual(_a ,_a )
665
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class _lowercase ( unittest.TestCase ): '''simple docstring''' def __init__( self , lowerCamelCase__ , lowerCamelCase__=7 , lowerCamelCase__=3 , lowerCamelCase__=30 , lowerCamelCase__=400 , lowerCamelCase__=True , lowerCamelCase__=None , lowerCamelCase__=True , lowerCamelCase__=[0.5, 0.5, 0.5] , lowerCamelCase__=[0.5, 0.5, 0.5] , lowerCamelCase__=True , lowerCamelCase__=1 / 255 , lowerCamelCase__=True , ): lowerCAmelCase_: Any = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1_333} lowerCAmelCase_: Optional[int] = parent lowerCAmelCase_: str = batch_size lowerCAmelCase_: Optional[Any] = num_channels lowerCAmelCase_: Optional[int] = min_resolution lowerCAmelCase_: List[str] = max_resolution lowerCAmelCase_: Union[str, Any] = do_resize lowerCAmelCase_: Tuple = size lowerCAmelCase_: Any = do_normalize lowerCAmelCase_: int = image_mean lowerCAmelCase_: Optional[int] = image_std lowerCAmelCase_: int = do_rescale lowerCAmelCase_: Optional[Any] = rescale_factor lowerCAmelCase_: Optional[Any] = do_pad def _a ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _a ( self , lowerCamelCase__ , lowerCamelCase__=False ): if not batched: lowerCAmelCase_: Optional[Any] = image_inputs[0] if isinstance(_a , Image.Image ): lowerCAmelCase_: List[Any] = image.size else: lowerCAmelCase_: Dict = image.shape[1], image.shape[2] if w < h: lowerCAmelCase_: List[Any] = int(self.size["shortest_edge"] * h / w ) lowerCAmelCase_: str = self.size["""shortest_edge"""] elif w > h: lowerCAmelCase_: Optional[int] = self.size["""shortest_edge"""] lowerCAmelCase_: Optional[Any] = int(self.size["shortest_edge"] * w / h ) else: lowerCAmelCase_: str = self.size["""shortest_edge"""] lowerCAmelCase_: Union[str, Any] = self.size["""shortest_edge"""] else: lowerCAmelCase_: Any = [] for image in image_inputs: lowerCAmelCase_: Dict = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCAmelCase_: List[str] = max(_a , key=lambda lowerCamelCase__ : item[0] )[0] lowerCAmelCase_: Tuple = max(_a , key=lambda lowerCamelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _lowercase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE: List[str] = ConditionalDetrImageProcessor if is_vision_available() else None def _a ( self ): lowerCAmelCase_: Dict = ConditionalDetrImageProcessingTester(self ) @property def _a ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _a ( self ): lowerCAmelCase_: Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , "image_mean" ) ) self.assertTrue(hasattr(_a , "image_std" ) ) self.assertTrue(hasattr(_a , "do_normalize" ) ) self.assertTrue(hasattr(_a , "do_resize" ) ) self.assertTrue(hasattr(_a , "size" ) ) def _a ( self ): lowerCAmelCase_: int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1_333} ) self.assertEqual(image_processor.do_pad , _a ) lowerCAmelCase_: List[str] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_a ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , _a ) def _a ( self ): pass def _a ( self ): lowerCAmelCase_: Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase_: List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input lowerCAmelCase_: Any = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase_: List[Any] = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase_: str = self.image_processor_tester.get_expected_values(_a , batched=_a ) lowerCAmelCase_: Tuple = image_processing(_a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self ): lowerCAmelCase_: int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase_: Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input lowerCAmelCase_: Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase_: Any = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase_: Any = image_processing(_a , return_tensors="pt" ).pixel_values lowerCAmelCase_: List[Any] = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self ): lowerCAmelCase_: str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase_: int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input lowerCAmelCase_: Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase_: str = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase_: Dict = image_processing(_a , return_tensors="pt" ).pixel_values lowerCAmelCase_: Union[str, Any] = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _a ( self ): lowerCAmelCase_: List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: lowerCAmelCase_: str = json.loads(f.read() ) lowerCAmelCase_: Any = {"""image_id""": 39_769, """annotations""": target} # encode them lowerCAmelCase_: Optional[Any] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) lowerCAmelCase_: Any = image_processing(images=_a , annotations=_a , return_tensors="pt" ) # verify pixel values lowerCAmelCase_: Optional[int] = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , _a ) lowerCAmelCase_: Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _a , atol=1E-4 ) ) # verify area lowerCAmelCase_: Optional[int] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _a ) ) # verify boxes lowerCAmelCase_: Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _a ) lowerCAmelCase_: Dict = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _a , atol=1E-3 ) ) # verify image_id lowerCAmelCase_: List[str] = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _a ) ) # verify is_crowd lowerCAmelCase_: Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _a ) ) # verify class_labels lowerCAmelCase_: Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _a ) ) # verify orig_size lowerCAmelCase_: int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _a ) ) # verify size lowerCAmelCase_: Union[str, Any] = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _a ) ) @slow def _a ( self ): lowerCAmelCase_: Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: lowerCAmelCase_: int = json.loads(f.read() ) lowerCAmelCase_: str = {"""file_name""": """000000039769.png""", """image_id""": 39_769, """segments_info""": target} lowerCAmelCase_: str = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them lowerCAmelCase_: str = ConditionalDetrImageProcessor(format="coco_panoptic" ) lowerCAmelCase_: str = image_processing(images=_a , annotations=_a , masks_path=_a , return_tensors="pt" ) # verify pixel values lowerCAmelCase_: Any = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , _a ) lowerCAmelCase_: List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _a , atol=1E-4 ) ) # verify area lowerCAmelCase_: Optional[Any] = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _a ) ) # verify boxes lowerCAmelCase_: Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _a ) lowerCAmelCase_: Dict = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _a , atol=1E-3 ) ) # verify image_id lowerCAmelCase_: Optional[Any] = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _a ) ) # verify is_crowd lowerCAmelCase_: Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _a ) ) # verify class_labels lowerCAmelCase_: List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _a ) ) # verify masks lowerCAmelCase_: Dict = 822_873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , _a ) # verify orig_size lowerCAmelCase_: List[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _a ) ) # verify size lowerCAmelCase_: int = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _a ) )
613
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __magic_name__ = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' __magic_name__ = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' __magic_name__ = r'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def _a ( self : Optional[Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { """predictions""": datasets.Value("""string""" ), """references""": datasets.Value("""string""" ), } ) ,homepage="""https://github.com/hendrycks/math""" ,codebase_urls=["""https://github.com/hendrycks/math"""] ,) def _a ( self : List[Any] ,_a : Union[str, Any] ,_a : Optional[int] ): '''simple docstring''' A_ : Union[str, Any] = 0.0 for i, j in zip(_a ,_a ): n_correct += 1.0 if math_equivalence.is_equiv(_a ,_a ) else 0.0 A_ : List[str] = n_correct / len(_a ) return { "accuracy": accuracy, }
665
0
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): UpperCAmelCase : Optional[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : str = 128022 UpperCAmelCase : int = 128028 @require_sentencepiece class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase): _lowercase : Tuple = MaMaaaTokenizer _lowercase : int = False _lowercase : Optional[Any] = False _lowercase : int = True def _lowercase ( self ) -> Dict: '''simple docstring''' super().setUp() a__ : Optional[int] =["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] a__ : Dict =dict(zip(_a , range(len(_a ) ) ) ) a__ : List[Any] =Path(self.tmpdirname ) save_json(_a , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(_a , save_dir / VOCAB_FILES_NAMES["spm_file"] ) a__ : Any =MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **_a ) def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' return ( "This is a test", "This is a test", ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] ="""</s>""" a__ : int =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Optional[Any] =self.get_tokenizer() a__ : str =list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "</s>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "<s>" ) self.assertEqual(len(_a ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip("Skip this test while all models are still to be uploaded." ) def _lowercase ( self ) -> Tuple: '''simple docstring''' pass def _lowercase ( self ) -> str: '''simple docstring''' a__ : Any =self.get_tokenizer() a__ : Dict =tokenizer.tokenize("This is a test" ) self.assertListEqual(_a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [2, 3, 4, 5, 6] , ) a__ : Dict =tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(_a , ["▁This", "▁is", "▁a", "▁t", "est"] ) a__ : Union[str, Any] =tokenizer.convert_tokens_to_string(_a ) self.assertEqual(_a , "This is a test" ) @slow def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] ={"""input_ids""": [[1_2_8_0_2_2, 1_1_0_1_0_8, 3_9_7, 1_1, 3_8_2_7_2, 2_2_4_7, 1_2_4_8_1_1, 2_8_5, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 3_9_5_3_4, 4_4_2_8, 3_9_7, 1_0_1_9, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 4_1_3_3_7, 1_6_7_8_6, 2_4_1, 7, 2_0_2_1_4, 1_7, 1_2_5_6_9_0, 1_0_3_9_8, 7, 4_4_3_7_8, 5_8_0_6_9, 6_8_3_4_2, 7_7_9_8, 7_3_4_3, 1_1, 2_9_9, 3_3_3_1_0, 4, 1_5_8, 3_7_3_5_0, 9_4_0_7_7, 4_5_6_9, 2_9_9, 3_3_3_1_0, 9_0, 4, 5_2_8_4_0, 2_9_0, 4, 3_1_2_7_0, 1_1_2, 2_9_9, 6_8_2, 4, 5_2_8_4_0, 3_9_9_5_3, 1_4_0_7_9, 1_9_3, 5_2_5_1_9, 9_0_8_9_4, 1_7_8_9_4, 1_2_0_6_9_7, 1_1, 4_0_4_4_5, 5_5_1, 1_7, 1_0_1_9, 5_2_5_1_9, 9_0_8_9_4, 1_7_7_5_6, 9_6_3, 1_1, 4_0_4_4_5, 4_8_0, 1_7, 9_7_9_2, 1_1_2_0, 5_1_7_3, 1_3_9_3, 6_2_4_0, 1_6_7_8_6, 2_4_1, 1_2_0_9_9_6, 2_8, 1_2_4_5, 1_3_9_3, 1_1_8_2_4_0, 1_1_1_2_3, 1_0_1_9, 9_3_6_1_2, 2_6_9_1, 1_0_6_1_8, 9_8_0_5_8, 1_2_0_4_0_9, 1_9_2_8, 2_7_9, 4, 4_0_6_8_3, 3_6_7, 1_7_8, 2_0_7, 1_0_1_9, 1_0_3, 1_0_3_1_2_1, 5_0_6, 6_5_2_9_6, 5, 2], [1_2_8_0_2_2, 2_1_2_1_7, 3_6_7, 1_1_7, 1_2_5_4_5_0, 1_2_8, 7_1_9, 7, 7_3_0_8, 4_0, 9_3_6_1_2, 1_2_6_6_9, 1_1_1_6, 1_6_7_0_4, 7_1, 1_7_7_8_5, 3_6_9_9, 1_5_5_9_2, 3_5, 1_4_4, 9_5_8_4, 2_4_1, 1_1_9_4_3, 7_1_3, 9_5_0, 7_9_9, 2_2_4_7, 8_8_4_2_7, 1_5_0, 1_4_9, 1_1_8_8_1_3, 1_2_0_7_0_6, 1_0_1_9, 1_0_6_9_0_6, 8_1_5_1_8, 2_8, 1_2_2_4, 2_2_7_9_9, 3_9_7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1_2_8_0_2_2, 1_6_5_8, 1_2_3_3_1_1, 5_1_5_5, 5_5_7_8, 4_7_2_2, 2_7_9, 1_4_9_4_7, 2_3_6_6, 1_1_2_0, 1_1_9_7, 1_4, 1_3_4_8, 9_2_3_2, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name="facebook/m2m100_418M" , revision="c168bae485c864188cf9aa0e4108b0b6934dc91e" , ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase): _lowercase : str = """facebook/m2m100_418M""" _lowercase : Optional[Any] = [ """In my opinion, there are two levels of response from the French government.""", """NSA Affair Emphasizes Complete Lack of Debate on Intelligence""", ] _lowercase : Tuple = [ """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""", """L'affaire NSA souligne l'absence totale de débat sur le renseignement""", ] # fmt: off _lowercase : List[Any] = [EN_CODE, 593, 1949, 11_5781, 4, 7_1586, 4234, 6_0633, 12_6233, 432, 12_3808, 1_5592, 1197, 11_7132, 12_0618, 5, 2] @classmethod def _lowercase ( cls ) -> List[Any]: '''simple docstring''' a__ : MaMaaaTokenizer =MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en" , tgt_lang="fr" ) a__ : Optional[Any] =1 return cls def _lowercase ( self ) -> Optional[int]: '''simple docstring''' self.assertEqual(self.tokenizer.get_lang_id("ar" ) , 1_2_8_0_0_6 ) self.assertEqual(self.tokenizer.get_lang_id("en" ) , 1_2_8_0_2_2 ) self.assertEqual(self.tokenizer.get_lang_id("ro" ) , 1_2_8_0_7_6 ) self.assertEqual(self.tokenizer.get_lang_id("mr" ) , 1_2_8_0_6_3 ) def _lowercase ( self ) -> int: '''simple docstring''' a__ : Any =self.tokenizer.get_vocab() self.assertEqual(len(_a ) , self.tokenizer.vocab_size ) self.assertEqual(vocab["<unk>"] , 3 ) self.assertIn(self.tokenizer.get_lang_token("en" ) , _a ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : str ="""en""" a__ : Optional[Any] =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _a ) def _lowercase ( self ) -> Tuple: '''simple docstring''' self.assertIn(_a , self.tokenizer.all_special_ids ) # fmt: off a__ : Tuple =[FR_CODE, 5_3_6_4, 8_2, 8_6_4_2, 4, 2_9_4, 4_7, 8, 1_4_0_2_8, 1_3_6, 3_2_8_6, 9_7_0_6, 6, 9_0_7_9_7, 6, 1_4_4_0_1_2, 1_6_2, 8_8_1_2_8, 3_0_0_6_1, 5, 2] # fmt: on a__ : Any =self.tokenizer.decode(_a , skip_special_tokens=_a ) a__ : str =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_a ) self.assertEqual(_a , _a ) self.assertNotIn(self.tokenizer.eos_token , _a ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Union[str, Any] =tempfile.mkdtemp() a__ : List[Any] =self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(_a ) a__ : Union[str, Any] =MaMaaaTokenizer.from_pretrained(_a ) self.assertDictEqual(new_tok.lang_token_to_id , _a ) @require_torch def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : List[Any] ="""en""" a__ : Union[str, Any] ="""fr""" a__ : int =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_a , return_tensors="pt" ) a__ : List[str] =shift_tokens_right( batch["labels"] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: a__ : Dict =batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def _lowercase ( self ) -> int: '''simple docstring''' a__ : List[Any] ="""mr""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) a__ : str ="""zh""" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def _lowercase ( self ) -> int: '''simple docstring''' a__ : Optional[int] ="""mr""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) a__ : Optional[int] ="""zh""" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] =self.tokenizer._build_translation_inputs("A test" , return_tensors="pt" , src_lang="en" , tgt_lang="ar" ) self.assertEqual( nested_simplify(_a ) , { # en_XX, A, test, EOS "input_ids": [[1_2_8_0_2_2, 5_8, 4_1_8_3, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 1_2_8_0_0_6, } , )
563
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging __magic_name__ = logging.get_logger(__name__) # TODO: upload to AWS __magic_name__ = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = """retribert""" def __init__( self : int ,_a : Dict=30522 ,_a : List[Any]=768 ,_a : Optional[Any]=8 ,_a : str=12 ,_a : str=3072 ,_a : Tuple="gelu" ,_a : Optional[int]=0.1 ,_a : Dict=0.1 ,_a : List[Any]=512 ,_a : Union[str, Any]=2 ,_a : Tuple=0.02 ,_a : List[str]=1e-12 ,_a : Dict=True ,_a : Tuple=128 ,_a : Optional[int]=0 ,**_a : Tuple ,): '''simple docstring''' super().__init__(pad_token_id=_a ,**_a ) A_ : Dict = vocab_size A_ : int = hidden_size A_ : Union[str, Any] = num_hidden_layers A_ : Union[str, Any] = num_attention_heads A_ : Tuple = hidden_act A_ : int = intermediate_size A_ : Tuple = hidden_dropout_prob A_ : Optional[int] = attention_probs_dropout_prob A_ : int = max_position_embeddings A_ : Any = type_vocab_size A_ : Optional[int] = initializer_range A_ : Dict = layer_norm_eps A_ : str = share_encoders A_ : List[Any] = projection_dim
665
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Optional[Any] = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json" ), } class snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" _a = """audio-spectrogram-transformer""" def __init__( self, _lowercase=768, _lowercase=12, _lowercase=12, _lowercase=3072, _lowercase="gelu", _lowercase=0.0, _lowercase=0.0, _lowercase=0.02, _lowercase=1E-12, _lowercase=16, _lowercase=True, _lowercase=10, _lowercase=10, _lowercase=1024, _lowercase=128, **_lowercase, ) -> Any: super().__init__(**_a ) SCREAMING_SNAKE_CASE_ = hidden_size SCREAMING_SNAKE_CASE_ = num_hidden_layers SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = intermediate_size SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = hidden_dropout_prob SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = patch_size SCREAMING_SNAKE_CASE_ = qkv_bias SCREAMING_SNAKE_CASE_ = frequency_stride SCREAMING_SNAKE_CASE_ = time_stride SCREAMING_SNAKE_CASE_ = max_length SCREAMING_SNAKE_CASE_ = num_mel_bins
294
'''simple docstring''' import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'vocab_file': 'spiece.model'} __magic_name__ = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } __magic_name__ = { 'google/bigbird-roberta-base': 4_096, 'google/bigbird-roberta-large': 4_096, 'google/bigbird-base-trivia-itc': 4_096, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = ["""input_ids""", """attention_mask"""] a_ = [] def __init__( self : Optional[int] ,_a : int ,_a : Optional[Any]="<unk>" ,_a : int="<s>" ,_a : str="</s>" ,_a : Optional[Any]="<pad>" ,_a : Tuple="[SEP]" ,_a : Tuple="[MASK]" ,_a : Union[str, Any]="[CLS]" ,_a : Optional[Dict[str, Any]] = None ,**_a : Any ,): '''simple docstring''' A_ : Dict = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else bos_token A_ : Union[str, Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else eos_token A_ : Optional[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else unk_token A_ : Union[str, Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else pad_token A_ : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else cls_token A_ : Optional[int] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else sep_token # Mask token behave like a normal word, i.e. include the space before it A_ : List[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token A_ : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a ,eos_token=_a ,unk_token=_a ,pad_token=_a ,sep_token=_a ,mask_token=_a ,cls_token=_a ,sp_model_kwargs=self.sp_model_kwargs ,**_a ,) A_ : Optional[int] = vocab_file A_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def _a ( self : Union[str, Any] ): '''simple docstring''' return self.sp_model.get_piece_size() def _a ( self : Optional[Any] ): '''simple docstring''' A_ : Tuple = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[Any] ): '''simple docstring''' A_ : Union[str, Any] = self.__dict__.copy() A_ : Union[str, Any] = None return state def __setstate__( self : List[Any] ,_a : Any ): '''simple docstring''' A_ : Tuple = d # for backward compatibility if not hasattr(self ,"""sp_model_kwargs""" ): A_ : Tuple = {} A_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _a ( self : Union[str, Any] ,_a : str ): '''simple docstring''' return self.sp_model.encode(_a ,out_type=_a ) def _a ( self : Optional[int] ,_a : str ): '''simple docstring''' return self.sp_model.piece_to_id(_a ) def _a ( self : int ,_a : Optional[int] ): '''simple docstring''' A_ : List[str] = self.sp_model.IdToPiece(_a ) return token def _a ( self : Dict ,_a : int ): '''simple docstring''' A_ : int = [] A_ : Any = """""" A_ : str = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token A_ : Dict = True A_ : Union[str, Any] = [] else: current_sub_tokens.append(_a ) A_ : str = False out_string += self.sp_model.decode(_a ) return out_string.strip() def _a ( self : int ,_a : List[int] ,_a : bool = False ,_a : bool = None ,_a : bool = True ,**_a : str ,): '''simple docstring''' A_ : Any = kwargs.pop("""use_source_tokenizer""" ,_a ) A_ : Union[str, Any] = self.convert_ids_to_tokens(_a ,skip_special_tokens=_a ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A_ : str = [] A_ : int = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) A_ : List[str] = [] sub_texts.append(_a ) else: current_sub_text.append(_a ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: A_ : Optional[int] = re.sub(r""" (\[(MASK|SEP)\])""" ,r"""\1""" ,""" """.join(_a ) ) else: A_ : Tuple = """""".join(_a ) A_ : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A_ : Optional[Any] = self.clean_up_tokenization(_a ) return clean_text else: return text def _a ( self : int ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A_ : int = os.path.join( _a ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_a ) elif not os.path.isfile(self.vocab_file ): with open(_a ,"""wb""" ) as fi: A_ : str = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,) def _a ( self : Optional[Any] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A_ : List[Any] = [self.cls_token_id] A_ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def _a ( self : Optional[int] ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] def _a ( self : Tuple ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' A_ : Tuple = [self.sep_token_id] A_ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
665
0
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} # See all BART models at https://huggingface.co/models?filter=bart __UpperCAmelCase = { """vocab_file""": { """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/vocab.json""", """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/vocab.json""", """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json""", """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json""", """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json""", """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json""", }, """merges_file""": { """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/merges.txt""", """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/merges.txt""", """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt""", """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt""", """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt""", """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt""", }, """tokenizer_file""": { """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json""", """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json""", """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json""", """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json""", """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json""", """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json""", }, } __UpperCAmelCase = { """facebook/bart-base""": 1_024, """facebook/bart-large""": 1_024, """facebook/bart-large-mnli""": 1_024, """facebook/bart-large-cnn""": 1_024, """facebook/bart-large-xsum""": 1_024, """yjernite/bart_eli5""": 1_024, } class SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowerCamelCase : List[Any] =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Any =["input_ids", "attention_mask"] lowerCamelCase : Tuple =BartTokenizer def __init__( self : str , lowerCAmelCase : Any=None , lowerCAmelCase : Optional[int]=None , lowerCAmelCase : int=None , lowerCAmelCase : Optional[int]="replace" , lowerCAmelCase : Dict="<s>" , lowerCAmelCase : Optional[Any]="</s>" , lowerCAmelCase : Dict="</s>" , lowerCAmelCase : Tuple="<s>" , lowerCAmelCase : Optional[Any]="<unk>" , lowerCAmelCase : List[str]="<pad>" , lowerCAmelCase : int="<mask>" , lowerCAmelCase : str=False , lowerCAmelCase : List[str]=True , **lowerCAmelCase : Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__( _a , _a , tokenizer_file=_a , errors=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , trim_offsets=_a , **_a , ) __lowerCAmelCase : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , _a ) != add_prefix_space: __lowerCAmelCase : List[str] = getattr(_a , pre_tok_state.pop("""type""" ) ) __lowerCAmelCase : Optional[int] = add_prefix_space __lowerCAmelCase : int = pre_tok_class(**_a ) __lowerCAmelCase : str = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` __lowerCAmelCase : str = """post_processor""" __lowerCAmelCase : List[Any] = getattr(self.backend_tokenizer , _a , _a ) if tokenizer_component_instance: __lowerCAmelCase : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __lowerCAmelCase : Tuple = tuple(state["""sep"""] ) if "cls" in state: __lowerCAmelCase : Tuple = tuple(state["""cls"""] ) __lowerCAmelCase : List[str] = False if state.get("""add_prefix_space""" , _a ) != add_prefix_space: __lowerCAmelCase : Dict = add_prefix_space __lowerCAmelCase : Any = True if state.get("""trim_offsets""" , _a ) != trim_offsets: __lowerCAmelCase : Union[str, Any] = trim_offsets __lowerCAmelCase : List[Any] = True if changes_to_apply: __lowerCAmelCase : Optional[int] = getattr(_a , state.pop("""type""" ) ) __lowerCAmelCase : Tuple = component_class(**_a ) setattr(self.backend_tokenizer , _a , _a ) @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase : Any ) -> Tuple: """simple docstring""" __lowerCAmelCase : int = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else value __lowerCAmelCase : List[Any] = value def SCREAMING_SNAKE_CASE ( self : str , *lowerCAmelCase : str , **lowerCAmelCase : Optional[int] ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Optional[Any] = kwargs.get("""is_split_into_words""" , _a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*_a , **_a ) def SCREAMING_SNAKE_CASE ( self : str , *lowerCAmelCase : List[Any] , **lowerCAmelCase : str ) -> List[Any]: """simple docstring""" __lowerCAmelCase : List[str] = kwargs.get("""is_split_into_words""" , _a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._encode_plus(*_a , **_a ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None ) -> int: """simple docstring""" __lowerCAmelCase : str = self._tokenizer.model.save(_a , name=_a ) return tuple(_a ) def SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase : Optional[int] , lowerCAmelCase : int=None ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> Any: """simple docstring""" __lowerCAmelCase : Dict = [self.sep_token_id] __lowerCAmelCase : 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 + sep + token_ids_a + sep ) * [0]
651
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' a_ = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a_ = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def _a ( self : List[str] ,_a : int ,_a : Any ,_a : int ): '''simple docstring''' A_ : Dict = TextaTextGenerationPipeline(model=_a ,tokenizer=_a ) return generator, ["Something to write", "Something else"] def _a ( self : str ,_a : Union[str, Any] ,_a : int ): '''simple docstring''' A_ : Any = generator("""Something there""" ) self.assertEqual(_a ,[{"""generated_text""": ANY(_a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) ) A_ : List[Any] = generator(["""This is great !""", """Something else"""] ,num_return_sequences=2 ,do_sample=_a ) self.assertEqual( _a ,[ [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], ] ,) A_ : List[str] = generator( ["""This is great !""", """Something else"""] ,num_return_sequences=2 ,batch_size=2 ,do_sample=_a ) self.assertEqual( _a ,[ [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], [{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}], ] ,) with self.assertRaises(_a ): generator(4 ) @require_torch def _a ( self : Union[str, Any] ): '''simple docstring''' A_ : int = pipeline("""text2text-generation""" ,model="""patrickvonplaten/t5-tiny-random""" ,framework="""pt""" ) # do_sample=False necessary for reproducibility A_ : Tuple = generator("""Something there""" ,do_sample=_a ) self.assertEqual(_a ,[{"""generated_text""": """"""}] ) A_ : Optional[int] = 3 A_ : Tuple = generator( """Something there""" ,num_return_sequences=_a ,num_beams=_a ,) A_ : Optional[Any] = [ {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """"""}, ] self.assertEqual(_a ,_a ) A_ : Optional[int] = generator("""This is a test""" ,do_sample=_a ,num_return_sequences=2 ,return_tensors=_a ) self.assertEqual( _a ,[ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ] ,) A_ : Dict = generator.model.config.eos_token_id A_ : Optional[int] = """<pad>""" A_ : List[Any] = generator( ["""This is a test""", """This is a second test"""] ,do_sample=_a ,num_return_sequences=2 ,batch_size=2 ,return_tensors=_a ,) self.assertEqual( _a ,[ [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], ] ,) @require_tf def _a ( self : List[Any] ): '''simple docstring''' A_ : Optional[int] = pipeline("""text2text-generation""" ,model="""patrickvonplaten/t5-tiny-random""" ,framework="""tf""" ) # do_sample=False necessary for reproducibility A_ : Dict = generator("""Something there""" ,do_sample=_a ) self.assertEqual(_a ,[{"""generated_text""": """"""}] )
665
0
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Optional[Any] = 42 @flax_register_to_config class A__ ( nn.Module , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Union[str, Any] = 32 _UpperCAmelCase : Optional[int] = 4 _UpperCAmelCase : Any = 4 _UpperCAmelCase : Dict = ( """CrossAttnDownBlock2D""", """CrossAttnDownBlock2D""", """CrossAttnDownBlock2D""", """DownBlock2D""", ) _UpperCAmelCase : Any = ("""UpBlock2D""", """CrossAttnUpBlock2D""", """CrossAttnUpBlock2D""", """CrossAttnUpBlock2D""") _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Tuple = (320, 640, 1280, 1280) _UpperCAmelCase : str = 2 _UpperCAmelCase : List[Any] = 8 _UpperCAmelCase : Dict = None _UpperCAmelCase : int = 1280 _UpperCAmelCase : Union[str, Any] = 0.0 _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[int] = jnp.floataa _UpperCAmelCase : int = True _UpperCAmelCase : Union[str, Any] = 0 _UpperCAmelCase : str = False def UpperCamelCase__ ( self , __magic_name__ ): lowerCamelCase : Union[str, Any] = (1, self.in_channels, self.sample_size, self.sample_size) lowerCamelCase : Optional[Any] = jnp.zeros(_a , dtype=jnp.floataa ) lowerCamelCase : Union[str, Any] = jnp.ones((1,) , dtype=jnp.intaa ) lowerCamelCase : str = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowerCamelCase : Optional[Any] = jax.random.split(_a ) lowerCamelCase : Optional[Any] = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(_a , _a , _a , _a )["params"] def UpperCamelCase__ ( self ): lowerCamelCase : Dict = self.block_out_channels lowerCamelCase : str = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.""" ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. lowerCamelCase : Optional[Any] = self.num_attention_heads or self.attention_head_dim # input lowerCamelCase : int = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowerCamelCase : Any = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowerCamelCase : List[str] = FlaxTimestepEmbedding(_a , dtype=self.dtype ) lowerCamelCase : Optional[int] = self.only_cross_attention if isinstance(_a , _a ): lowerCamelCase : str = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_a , _a ): lowerCamelCase : List[Any] = (num_attention_heads,) * len(self.down_block_types ) # down lowerCamelCase : Optional[Any] = [] lowerCamelCase : Dict = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): lowerCamelCase : Tuple = output_channel lowerCamelCase : List[Any] = block_out_channels[i] lowerCamelCase : Optional[int] = i == len(_a ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowerCamelCase : Tuple = FlaxCrossAttnDownBlockaD( in_channels=_a , out_channels=_a , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: lowerCamelCase : str = FlaxDownBlockaD( in_channels=_a , out_channels=_a , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_a ) lowerCamelCase : Union[str, Any] = down_blocks # mid lowerCamelCase : Optional[Any] = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up lowerCamelCase : Dict = [] lowerCamelCase : List[str] = list(reversed(_a ) ) lowerCamelCase : Any = list(reversed(_a ) ) lowerCamelCase : Union[str, Any] = list(reversed(_a ) ) lowerCamelCase : Any = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): lowerCamelCase : Dict = output_channel lowerCamelCase : Optional[int] = reversed_block_out_channels[i] lowerCamelCase : Optional[int] = reversed_block_out_channels[min(i + 1 , len(_a ) - 1 )] lowerCamelCase : Dict = i == len(_a ) - 1 if up_block_type == "CrossAttnUpBlock2D": lowerCamelCase : Any = FlaxCrossAttnUpBlockaD( in_channels=_a , out_channels=_a , prev_output_channel=_a , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: lowerCamelCase : Dict = FlaxUpBlockaD( in_channels=_a , out_channels=_a , prev_output_channel=_a , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(_a ) lowerCamelCase : int = output_channel lowerCamelCase : Dict = up_blocks # out lowerCamelCase : int = nn.GroupNorm(num_groups=3_2 , epsilon=1e-5 ) lowerCamelCase : str = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , __magic_name__=None , __magic_name__ = True , __magic_name__ = False , ): if not isinstance(_a , jnp.ndarray ): lowerCamelCase : Any = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_a , jnp.ndarray ) and len(timesteps.shape ) == 0: lowerCamelCase : int = timesteps.astype(dtype=jnp.floataa ) lowerCamelCase : List[str] = jnp.expand_dims(_a , 0 ) lowerCamelCase : int = self.time_proj(_a ) lowerCamelCase : Union[str, Any] = self.time_embedding(_a ) # 2. pre-process lowerCamelCase : str = jnp.transpose(_a , (0, 2, 3, 1) ) lowerCamelCase : List[str] = self.conv_in(_a ) # 3. down lowerCamelCase : Tuple = (sample,) for down_block in self.down_blocks: if isinstance(_a , _a ): lowerCamelCase : Union[str, Any] = down_block(_a , _a , _a , deterministic=not train ) else: lowerCamelCase : str = down_block(_a , _a , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: lowerCamelCase : List[Any] = () for down_block_res_sample, down_block_additional_residual in zip( _a , _a ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) lowerCamelCase : Union[str, Any] = new_down_block_res_samples # 4. mid lowerCamelCase : List[Any] = self.mid_block(_a , _a , _a , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: lowerCamelCase : Union[str, Any] = down_block_res_samples[-(self.layers_per_block + 1) :] lowerCamelCase : Any = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(_a , _a ): lowerCamelCase : List[str] = up_block( _a , temb=_a , encoder_hidden_states=_a , res_hidden_states_tuple=_a , deterministic=not train , ) else: lowerCamelCase : Optional[int] = up_block(_a , temb=_a , res_hidden_states_tuple=_a , deterministic=not train ) # 6. post-process lowerCamelCase : Optional[Any] = self.conv_norm_out(_a ) lowerCamelCase : Tuple = nn.silu(_a ) lowerCamelCase : Optional[Any] = self.conv_out(_a ) lowerCamelCase : List[str] = jnp.transpose(_a , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=_a )
681
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = """gpt_bigcode""" a_ = ["""past_key_values"""] a_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Optional[int] ,_a : Optional[int]=50257 ,_a : Dict=1024 ,_a : Union[str, Any]=768 ,_a : Union[str, Any]=12 ,_a : Union[str, Any]=12 ,_a : Tuple=None ,_a : int="gelu_pytorch_tanh" ,_a : Optional[Any]=0.1 ,_a : List[str]=0.1 ,_a : Union[str, Any]=0.1 ,_a : List[Any]=1e-5 ,_a : List[str]=0.02 ,_a : Any=True ,_a : Union[str, Any]=True ,_a : Tuple=50256 ,_a : Optional[int]=50256 ,_a : int=True ,_a : Optional[int]=True ,_a : Optional[int]=True ,**_a : List[str] ,): '''simple docstring''' A_ : Optional[Any] = vocab_size A_ : int = n_positions A_ : Union[str, Any] = n_embd A_ : int = n_layer A_ : Optional[int] = n_head A_ : Union[str, Any] = n_inner A_ : List[Any] = activation_function A_ : Dict = resid_pdrop A_ : int = embd_pdrop A_ : Optional[int] = attn_pdrop A_ : Union[str, Any] = layer_norm_epsilon A_ : int = initializer_range A_ : Union[str, Any] = scale_attn_weights A_ : List[str] = use_cache A_ : Tuple = attention_softmax_in_fpaa A_ : List[str] = scale_attention_softmax_in_fpaa A_ : Union[str, Any] = multi_query A_ : Any = bos_token_id A_ : Optional[int] = eos_token_id super().__init__(bos_token_id=_a ,eos_token_id=_a ,**_a )
665
0
'''simple docstring''' from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class a_ : '''simple docstring''' pass
314
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} __magic_name__ = { 'vocab_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json' ), }, 'merges_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt' ), }, } __magic_name__ = { 'allenai/longformer-base-4096': 4_096, 'allenai/longformer-large-4096': 4_096, 'allenai/longformer-large-4096-finetuned-triviaqa': 4_096, 'allenai/longformer-base-4096-extra.pos.embd.only': 4_096, 'allenai/longformer-large-4096-extra.pos.embd.only': 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCamelCase ( ): A_ : Union[str, Any] = ( list(range(ord("""!""") , ord("""~""") + 1)) + list(range(ord("""¡""") , ord("""¬""") + 1)) + list(range(ord("""®""") , ord("""ÿ""") + 1)) ) A_ : Optional[Any] = bs[:] A_ : List[str] = 0 for b in range(2**8): if b not in bs: bs.append(lowerCamelCase) cs.append(2**8 + n) n += 1 A_ : List[Any] = [chr(lowerCamelCase) for n in cs] return dict(zip(lowerCamelCase , lowerCamelCase)) def lowerCamelCase ( lowerCamelCase : int): A_ : int = set() A_ : int = word[0] for char in word[1:]: pairs.add((prev_char, char)) A_ : List[str] = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = ["""input_ids""", """attention_mask"""] def __init__( self : int ,_a : Tuple ,_a : Union[str, Any] ,_a : Optional[Any]="replace" ,_a : Union[str, Any]="<s>" ,_a : Union[str, Any]="</s>" ,_a : int="</s>" ,_a : List[str]="<s>" ,_a : List[Any]="<unk>" ,_a : Any="<pad>" ,_a : Dict="<mask>" ,_a : Optional[int]=False ,**_a : List[Any] ,): '''simple docstring''' A_ : Dict = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else bos_token A_ : Optional[int] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else eos_token A_ : Optional[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else sep_token A_ : int = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else cls_token A_ : int = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else unk_token A_ : Optional[Any] = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it A_ : Any = AddedToken(_a ,lstrip=_a ,rstrip=_a ) if isinstance(_a ,_a ) else mask_token super().__init__( errors=_a ,bos_token=_a ,eos_token=_a ,unk_token=_a ,sep_token=_a ,cls_token=_a ,pad_token=_a ,mask_token=_a ,add_prefix_space=_a ,**_a ,) with open(_a ,encoding="""utf-8""" ) as vocab_handle: A_ : str = json.load(_a ) A_ : Optional[int] = {v: k for k, v in self.encoder.items()} A_ : List[str] = errors # how to handle errors in decoding A_ : List[str] = bytes_to_unicode() A_ : str = {v: k for k, v in self.byte_encoder.items()} with open(_a ,encoding="""utf-8""" ) as merges_handle: A_ : Any = merges_handle.read().split("""\n""" )[1:-1] A_ : str = [tuple(merge.split() ) for merge in bpe_merges] A_ : int = dict(zip(_a ,range(len(_a ) ) ) ) A_ : List[Any] = {} A_ : Optional[int] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions A_ : Optional[Any] = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property def _a ( self : Any ): '''simple docstring''' return len(self.encoder ) def _a ( self : str ): '''simple docstring''' return dict(self.encoder ,**self.added_tokens_encoder ) def _a ( self : int ,_a : int ): '''simple docstring''' if token in self.cache: return self.cache[token] A_ : Optional[int] = tuple(_a ) A_ : Any = get_pairs(_a ) if not pairs: return token while True: A_ : Optional[Any] = min(_a ,key=lambda _a : self.bpe_ranks.get(_a ,float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break A_ , A_ : Dict = bigram A_ : int = [] A_ : Optional[Any] = 0 while i < len(_a ): try: A_ : List[str] = word.index(_a ,_a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) A_ : Tuple = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 A_ : str = tuple(_a ) A_ : str = new_word if len(_a ) == 1: break else: A_ : int = get_pairs(_a ) A_ : Optional[int] = """ """.join(_a ) A_ : List[str] = word return word def _a ( self : Dict ,_a : Optional[int] ): '''simple docstring''' A_ : Any = [] for token in re.findall(self.pat ,_a ): A_ : Any = """""".join( self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(""" """ ) ) return bpe_tokens def _a ( self : Union[str, Any] ,_a : Optional[int] ): '''simple docstring''' return self.encoder.get(_a ,self.encoder.get(self.unk_token ) ) def _a ( self : int ,_a : Dict ): '''simple docstring''' return self.decoder.get(_a ) def _a ( self : Optional[int] ,_a : List[Any] ): '''simple docstring''' A_ : Optional[int] = """""".join(_a ) A_ : Dict = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" ,errors=self.errors ) return text def _a ( self : int ,_a : str ,_a : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A_ : int = os.path.join( _a ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) A_ : int = os.path.join( _a ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(_a ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=_a ,ensure_ascii=_a ) + """\n""" ) A_ : int = 0 with open(_a ,"""w""" ,encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,key=lambda _a : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' """ Please check that the tokenizer is not corrupted!""" ) A_ : Dict = token_index writer.write(""" """.join(_a ) + """\n""" ) index += 1 return vocab_file, merge_file def _a ( self : List[str] ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A_ : int = [self.cls_token_id] A_ : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self : int ,_a : List[int] ,_a : Optional[List[int]] = None ,_a : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a ,token_ids_a=_a ,already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def _a ( self : Any ,_a : List[int] ,_a : Optional[List[int]] = None ): '''simple docstring''' A_ : Union[str, Any] = [self.sep_token_id] A_ : Union[str, 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 + sep + token_ids_a + sep ) * [0] def _a ( self : str ,_a : Optional[int] ,_a : Union[str, Any]=False ,**_a : Dict ): '''simple docstring''' A_ : Any = kwargs.pop("""add_prefix_space""" ,self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): A_ : Optional[int] = """ """ + text return (text, kwargs)
665
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig", ], "processing_x_clip": ["XCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( _UpperCamelCase ): def __init__( self : Union[str, Any] , A__ : VQModel , A__ : UNetaDModel , A__ : DDIMScheduler ) -> List[Any]: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : str , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : float = 0.0 , A__ : int = 50 , A__ : Optional[str] = "pil" , A__ : bool = True , **A__ : Optional[Any] , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' snake_case_ : Optional[int] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=A__ , ) snake_case_ : List[Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ : Any = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(A__ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature snake_case_ : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ : List[Any] = {} if accepts_eta: snake_case_ : int = eta for t in self.progress_bar(self.scheduler.timesteps ): snake_case_ : Union[str, Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual snake_case_ : Dict = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case_ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VAE snake_case_ : int = self.vqvae.decode(A__ ).sample snake_case_ : Dict = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ : Optional[int] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
666
1
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: list[str] | None = None , lowerCAmelCase_: dict[str, float] | None = None , lowerCAmelCase_: bool = False , ): snake_case_ : List[str] = cipher_alphabet or [chr(lowerCAmelCase_ ) for i in range(9_7 , 1_2_3 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) snake_case_ : List[str] = { "a": 0.0_8_4_9_7, "b": 0.0_1_4_9_2, "c": 0.0_2_2_0_2, "d": 0.0_4_2_5_3, "e": 0.1_1_1_6_2, "f": 0.0_2_2_2_8, "g": 0.0_2_0_1_5, "h": 0.0_6_0_9_4, "i": 0.0_7_5_4_6, "j": 0.0_0_1_5_3, "k": 0.0_1_2_9_2, "l": 0.0_4_0_2_5, "m": 0.0_2_4_0_6, "n": 0.0_6_7_4_9, "o": 0.0_7_5_0_7, "p": 0.0_1_9_2_9, "q": 0.0_0_0_9_5, "r": 0.0_7_5_8_7, "s": 0.0_6_3_2_7, "t": 0.0_9_3_5_6, "u": 0.0_2_7_5_8, "v": 0.0_0_9_7_8, "w": 0.0_2_5_6_0, "x": 0.0_0_1_5_0, "y": 0.0_1_9_9_4, "z": 0.0_0_0_7_7, } else: # Custom frequencies dictionary snake_case_ : str = frequencies_dict if not case_sensitive: snake_case_ : Union[str, Any] = ciphertext.lower() # Chi squared statistic values snake_case_ : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(lowerCAmelCase_ ) ): snake_case_ : Tuple = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet snake_case_ : str = (alphabet_letters.index(letter.lower() ) - shift) % len( lowerCAmelCase_ ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter snake_case_ : List[Any] = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: snake_case_ : Optional[Any] = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message snake_case_ : Optional[Any] = decrypted_with_shift.lower().count(lowerCAmelCase_ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies snake_case_ : Union[str, Any] = frequencies[letter] * occurrences # Complete the chi squared statistic formula snake_case_ : List[str] = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message snake_case_ : Any = decrypted_with_shift.count(lowerCAmelCase_ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies snake_case_ : Tuple = frequencies[letter] * occurrences # Complete the chi squared statistic formula snake_case_ : Dict = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary snake_case_ : Tuple = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(lowerCAmelCase_: int ) -> tuple[float, str]: return chi_squared_statistic_values[key] snake_case_ : int = min( lowerCAmelCase_ , key=lowerCAmelCase_ , ) # Get all the data from the most likely cipher (key, decoded message) ( ( snake_case_ ) ,( snake_case_ ) , ) : str = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
666
from decimal import Decimal, getcontext from math import ceil, factorial def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) snake_case_ : List[str] = precision snake_case_ : Union[str, Any] = ceil(precision / 1_4 ) snake_case_ : List[str] = 4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt() snake_case_ : str = 1 snake_case_ : List[str] = 1_3_5_9_1_4_0_9 snake_case_ : str = Decimal(lowerCAmelCase_ ) for k in range(1 , lowerCAmelCase_ ): snake_case_ : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(lowerCAmelCase_ ) ** 3) linear_term += 5_4_5_1_4_0_1_3_4 exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": UpperCAmelCase = 5_0 print(F"The first {n} digits of pi is: {pi(n)}")
666
1
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class snake_case__ ( _UpperCamelCase ): def __init__( self : Optional[Any] , A__ : CLIPSegForImageSegmentation , A__ : CLIPSegProcessor , A__ : AutoencoderKL , A__ : CLIPTextModel , A__ : CLIPTokenizer , A__ : UNetaDConditionModel , A__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , A__ : StableDiffusionSafetyChecker , A__ : CLIPImageProcessor , ) -> Optional[int]: '''simple docstring''' super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: snake_case_ : Union[str, Any] = ( f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , A__ , standard_warn=A__ ) snake_case_ : int = dict(scheduler.config ) snake_case_ : str = 1 snake_case_ : int = FrozenDict(A__ ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: snake_case_ : Optional[Any] = ( f"The configuration file of this scheduler: {scheduler} has not set the configuration" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , A__ , standard_warn=A__ ) snake_case_ : Dict = dict(scheduler.config ) snake_case_ : Any = True snake_case_ : str = FrozenDict(A__ ) if safety_checker is None: logger.warning( f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=A__ , segmentation_processor=A__ , vae=A__ , text_encoder=A__ , tokenizer=A__ , unet=A__ , scheduler=A__ , safety_checker=A__ , feature_extractor=A__ , ) def UpperCAmelCase__ ( self : Tuple , A__ : Optional[Union[str, int]] = "auto" ) -> Optional[int]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory snake_case_ : int = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(A__ ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' self.enable_attention_slicing(A__ ) def UpperCAmelCase__ ( self : Tuple ) -> Any: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) snake_case_ : Optional[Any] = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: '''simple docstring''' if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(A__ , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : str , A__ : Union[str, List[str]] , A__ : Union[torch.FloatTensor, PIL.Image.Image] , A__ : str , A__ : int = 5_12 , A__ : int = 5_12 , A__ : int = 50 , A__ : float = 7.5 , A__ : Optional[Union[str, List[str]]] = None , A__ : Optional[int] = 1 , A__ : float = 0.0 , A__ : Optional[torch.Generator] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , A__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , A__ : int = 1 , **A__ : List[Any] , ) -> str: '''simple docstring''' snake_case_ : Tuple = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) snake_case_ : Optional[int] = self.segmentation_model(**A__ ) snake_case_ : Any = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() snake_case_ : Optional[Any] = self.numpy_to_pil(A__ )[0].resize(image.size ) # Run inpainting pipeline with the generated mask snake_case_ : int = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=A__ , image=A__ , mask_image=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , )
666
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int = 1_0_0_0 ): snake_case_ ,snake_case_ : List[str] = 1, 1 snake_case_ : List[str] = 2 while True: snake_case_ : Tuple = 0 snake_case_ : Union[str, Any] = fa + fa snake_case_ ,snake_case_ : str = fa, f index += 1 for _ in str(lowerCAmelCase_ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
666
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self : List[Any] , A__ : int , A__ : Any=7 , A__ : Dict=3 , A__ : str=18 , A__ : List[str]=30 , A__ : Tuple=4_00 , A__ : int=True , A__ : Dict=None , A__ : List[str]=True , ) -> Any: '''simple docstring''' snake_case_ : Any = size if size is not None else {"height": 18, "width": 18} snake_case_ : Optional[Any] = parent snake_case_ : Tuple = batch_size snake_case_ : Union[str, Any] = num_channels snake_case_ : Any = image_size snake_case_ : Tuple = min_resolution snake_case_ : Optional[int] = max_resolution snake_case_ : Optional[Any] = do_resize snake_case_ : Optional[int] = size snake_case_ : str = apply_ocr def UpperCAmelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case__ ( _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Any = LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCAmelCase__ ( self : List[str] ) -> str: '''simple docstring''' snake_case_ : Any = LayoutLMvaImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : int ) -> Optional[int]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Any ) -> Tuple: '''simple docstring''' snake_case_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , "do_resize" ) ) self.assertTrue(hasattr(A__ , "size" ) ) self.assertTrue(hasattr(A__ , "apply_ocr" ) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) snake_case_ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def UpperCAmelCase__ ( self : str ) -> List[Any]: '''simple docstring''' pass def UpperCAmelCase__ ( self : int ) -> List[str]: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : Any = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , A__ ) self.assertIsInstance(encoding.boxes , A__ ) # Test batched snake_case_ : Optional[int] = image_processing(A__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase__ ( self : Tuple ) -> Dict: '''simple docstring''' snake_case_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , numpify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , np.ndarray ) # Test not batched input snake_case_ : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched snake_case_ : Optional[int] = image_processing(A__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , torchify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , torch.Tensor ) # Test not batched input snake_case_ : Any = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched snake_case_ : Any = image_processing(A__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase__ ( self : str ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = LayoutLMvaImageProcessor() from datasets import load_dataset snake_case_ : Union[str, Any] = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) snake_case_ : Optional[int] = Image.open(ds[0]["file"] ).convert("RGB" ) snake_case_ : Tuple = image_processing(A__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 snake_case_ : Optional[Any] = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 snake_case_ : Tuple = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , A__ ) self.assertListEqual(encoding.boxes , A__ ) # with apply_OCR = False snake_case_ : Dict = LayoutLMvaImageProcessor(apply_ocr=A__ ) snake_case_ : int = image_processing(A__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
666
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int | float] , lowerCAmelCase_: int , lowerCAmelCase_: int ): if len(lowerCAmelCase_ ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(lowerCAmelCase_ ) or left < -len(lowerCAmelCase_ ) or right >= len(lowerCAmelCase_ ) or right < -len(lowerCAmelCase_ ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] snake_case_ : List[Any] = (left + right) >> 1 # the middle snake_case_ : Dict = find_max(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # find max in range[left, mid] snake_case_ : int = find_max(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
666
1
UpperCAmelCase = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
666
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase = { "vocab_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/vocab.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/vocab.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/vocab.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json" ), }, "merges_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/merges.txt", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/merges.txt", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/merges.txt", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt" ), }, "tokenizer_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/tokenizer.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/tokenizer.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json", "roberta-base-openai-detector": ( "https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json" ), "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json" ), }, } UpperCAmelCase = { "roberta-base": 5_1_2, "roberta-large": 5_1_2, "roberta-large-mnli": 5_1_2, "distilroberta-base": 5_1_2, "roberta-base-openai-detector": 5_1_2, "roberta-large-openai-detector": 5_1_2, } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : int = ["input_ids", "attention_mask"] _SCREAMING_SNAKE_CASE : List[str] = RobertaTokenizer def __init__( self : Optional[int] , A__ : List[Any]=None , A__ : Optional[int]=None , A__ : List[str]=None , A__ : Dict="replace" , A__ : List[str]="<s>" , A__ : Optional[Any]="</s>" , A__ : List[str]="</s>" , A__ : List[Any]="<s>" , A__ : int="<unk>" , A__ : int="<pad>" , A__ : List[Any]="<mask>" , A__ : Any=False , A__ : Optional[int]=True , **A__ : Union[str, Any] , ) -> int: '''simple docstring''' super().__init__( A__ , A__ , tokenizer_file=A__ , errors=A__ , bos_token=A__ , eos_token=A__ , sep_token=A__ , cls_token=A__ , unk_token=A__ , pad_token=A__ , mask_token=A__ , add_prefix_space=A__ , trim_offsets=A__ , **A__ , ) snake_case_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , A__ ) != add_prefix_space: snake_case_ : List[Any] = getattr(A__ , pre_tok_state.pop("type" ) ) snake_case_ : Any = add_prefix_space snake_case_ : List[Any] = pre_tok_class(**A__ ) snake_case_ : Optional[int] = add_prefix_space snake_case_ : List[str] = "post_processor" snake_case_ : Tuple = getattr(self.backend_tokenizer , A__ , A__ ) if tokenizer_component_instance: snake_case_ : List[str] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: snake_case_ : str = tuple(state["sep"] ) if "cls" in state: snake_case_ : Tuple = tuple(state["cls"] ) snake_case_ : Tuple = False if state.get("add_prefix_space" , A__ ) != add_prefix_space: snake_case_ : Optional[Any] = add_prefix_space snake_case_ : str = True if state.get("trim_offsets" , A__ ) != trim_offsets: snake_case_ : Optional[int] = trim_offsets snake_case_ : List[Any] = True if changes_to_apply: snake_case_ : int = getattr(A__ , state.pop("type" ) ) snake_case_ : List[Any] = component_class(**A__ ) setattr(self.backend_tokenizer , A__ , A__ ) @property def UpperCAmelCase__ ( self : Optional[Any] ) -> str: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def UpperCAmelCase__ ( self : Tuple , A__ : Dict ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else value snake_case_ : Any = value def UpperCAmelCase__ ( self : int , *A__ : Optional[Any] , **A__ : int ) -> BatchEncoding: '''simple docstring''' snake_case_ : Optional[Any] = kwargs.get("is_split_into_words" , A__ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*A__ , **A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , *A__ : Any , **A__ : List[Any] ) -> BatchEncoding: '''simple docstring''' snake_case_ : Optional[int] = kwargs.get("is_split_into_words" , A__ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' snake_case_ : Optional[Any] = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ ) def UpperCAmelCase__ ( self : int , A__ : List[str] , A__ : Union[str, Any]=None ) -> Any: '''simple docstring''' snake_case_ : List[str] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCAmelCase__ ( self : Dict , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' snake_case_ : str = [self.sep_token_id] snake_case_ : 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 + sep + token_ids_a + sep ) * [0]
666
1
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase = logging.get_logger(__name__) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = ["pixel_values"] def __init__( self : Dict , A__ : bool = True , A__ : int = 32 , A__ : Union[str, Any]=PILImageResampling.BILINEAR , A__ : bool = True , **A__ : Any , ) -> None: '''simple docstring''' snake_case_ : List[Any] = do_resize snake_case_ : Tuple = do_rescale snake_case_ : Optional[Any] = size_divisor snake_case_ : List[Any] = resample super().__init__(**A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , A__ : np.ndarray , A__ : int , A__ : List[Any] , A__ : Optional[ChannelDimension] = None , **A__ : List[Any] ) -> np.ndarray: '''simple docstring''' snake_case_ ,snake_case_ : Union[str, Any] = get_image_size(A__ ) # Rounds the height and width down to the closest multiple of size_divisor snake_case_ : Optional[int] = height // size_divisor * size_divisor snake_case_ : Dict = width // size_divisor * size_divisor snake_case_ : Union[str, Any] = resize(A__ , (new_h, new_w) , resample=A__ , data_format=A__ , **A__ ) return image def UpperCAmelCase__ ( self : str , A__ : np.ndarray , A__ : float , A__ : Optional[ChannelDimension] = None , **A__ : Union[str, Any] ) -> np.ndarray: '''simple docstring''' return rescale(image=A__ , scale=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , A__ : Optional[bool] = None , A__ : Optional[int] = None , A__ : Tuple=None , A__ : Optional[bool] = None , A__ : Optional[Union[TensorType, str]] = None , A__ : ChannelDimension = ChannelDimension.FIRST , **A__ : Optional[int] , ) -> BatchFeature: '''simple docstring''' snake_case_ : str = do_resize if do_resize is not None else self.do_resize snake_case_ : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale snake_case_ : List[str] = size_divisor if size_divisor is not None else self.size_divisor snake_case_ : Any = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("size_divisor is required for resizing" ) snake_case_ : List[Any] = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError("Invalid image(s)" ) # All transformations expect numpy arrays. snake_case_ : List[str] = [to_numpy_array(A__ ) for img in images] if do_resize: snake_case_ : List[str] = [self.resize(A__ , size_divisor=A__ , resample=A__ ) for image in images] if do_rescale: snake_case_ : str = [self.rescale(A__ , scale=1 / 2_55 ) for image in images] snake_case_ : Tuple = [to_channel_dimension_format(A__ , A__ ) for image in images] snake_case_ : Dict = {"pixel_values": images} return BatchFeature(data=A__ , tensor_type=A__ )
666
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = TFXLMRobertaModel.from_pretrained("jplu/tf-xlm-roberta-base" ) snake_case_ : Any = { "input_ids": tf.convert_to_tensor([[0, 26_46, 1_02_69, 83, 9_99_42, 2]] , dtype=tf.intaa ), # "My dog is cute" "attention_mask": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } snake_case_ : List[str] = model(A__ )["last_hidden_state"] snake_case_ : str = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , A__ ) # compare the actual values for a slice. snake_case_ : List[str] = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
666
1
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: str ): snake_case_ : str = len(lowerCAmelCase_ ) snake_case_ : Optional[int] = len(lowerCAmelCase_ ) snake_case_ : Any = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] snake_case_ : Union[str, Any] = True for i in range(lowerCAmelCase_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: snake_case_ : Optional[Any] = True if a[i].islower(): snake_case_ : Optional[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
666
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging UpperCAmelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = ["pixel_values"] def __init__( self : Union[str, Any] , A__ : bool = True , A__ : Dict[str, int] = None , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : bool = True , A__ : Dict[str, int] = None , A__ : bool = True , A__ : Union[int, float] = 1 / 2_55 , A__ : bool = True , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : bool = True , **A__ : Optional[int] , ) -> None: '''simple docstring''' super().__init__(**A__ ) snake_case_ : str = size if size is not None else {"shortest_edge": 2_24} snake_case_ : Union[str, Any] = get_size_dict(A__ , default_to_square=A__ ) snake_case_ : List[Any] = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} snake_case_ : Dict = get_size_dict(A__ , default_to_square=A__ , param_name="crop_size" ) snake_case_ : str = do_resize snake_case_ : str = size snake_case_ : Optional[Any] = resample snake_case_ : Any = do_center_crop snake_case_ : Any = crop_size snake_case_ : str = do_rescale snake_case_ : Optional[Any] = rescale_factor snake_case_ : int = do_normalize snake_case_ : Optional[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN snake_case_ : List[str] = image_std if image_std is not None else OPENAI_CLIP_STD snake_case_ : int = do_convert_rgb def UpperCAmelCase__ ( self : Optional[int] , A__ : np.ndarray , A__ : Dict[str, int] , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[str] , ) -> np.ndarray: '''simple docstring''' snake_case_ : str = get_size_dict(A__ , default_to_square=A__ ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) snake_case_ : str = get_resize_output_image_size(A__ , size=size["shortest_edge"] , default_to_square=A__ ) return resize(A__ , size=A__ , resample=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : np.ndarray , A__ : Dict[str, int] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[Any] , ) -> np.ndarray: '''simple docstring''' snake_case_ : Optional[int] = get_size_dict(A__ ) if "height" not in size or "width" not in size: raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(A__ , size=(size["height"], size["width"]) , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Optional[Any] , A__ : np.ndarray , A__ : Union[int, float] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[str] , ) -> str: '''simple docstring''' return rescale(A__ , scale=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Any , A__ : np.ndarray , A__ : Union[float, List[float]] , A__ : Union[float, List[float]] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Any , ) -> np.ndarray: '''simple docstring''' return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : List[Any] , A__ : ImageInput , A__ : bool = None , A__ : Dict[str, int] = None , A__ : PILImageResampling = None , A__ : bool = None , A__ : int = None , A__ : bool = None , A__ : float = None , A__ : bool = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : bool = None , A__ : Optional[Union[str, TensorType]] = None , A__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **A__ : Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' snake_case_ : List[Any] = do_resize if do_resize is not None else self.do_resize snake_case_ : Union[str, Any] = size if size is not None else self.size snake_case_ : Any = get_size_dict(A__ , param_name="size" , default_to_square=A__ ) snake_case_ : Optional[int] = resample if resample is not None else self.resample snake_case_ : int = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ : List[str] = crop_size if crop_size is not None else self.crop_size snake_case_ : Tuple = get_size_dict(A__ , param_name="crop_size" , default_to_square=A__ ) snake_case_ : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale snake_case_ : str = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ : List[Any] = do_normalize if do_normalize is not None else self.do_normalize snake_case_ : Any = image_mean if image_mean is not None else self.image_mean snake_case_ : List[str] = image_std if image_std is not None else self.image_std snake_case_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case_ : List[Any] = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: snake_case_ : Dict = [convert_to_rgb(A__ ) for image in images] # All transformations expect numpy arrays. snake_case_ : Dict = [to_numpy_array(A__ ) for image in images] if do_resize: snake_case_ : Dict = [self.resize(image=A__ , size=A__ , resample=A__ ) for image in images] if do_center_crop: snake_case_ : Tuple = [self.center_crop(image=A__ , size=A__ ) for image in images] if do_rescale: snake_case_ : str = [self.rescale(image=A__ , scale=A__ ) for image in images] if do_normalize: snake_case_ : int = [self.normalize(image=A__ , mean=A__ , std=A__ ) for image in images] snake_case_ : List[Any] = [to_channel_dimension_format(A__ , A__ ) for image in images] snake_case_ : Tuple = {"pixel_values": images} return BatchFeature(data=A__ , tensor_type=A__ )
666
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Union[str, Any] ): snake_case_ : Any = SwinConfig( embed_dim=1_9_2 , depths=(2, 2, 1_8, 2) , num_heads=(6, 1_2, 2_4, 4_8) , window_size=1_2 , out_features=["stage2", "stage3", "stage4"] , ) snake_case_ : Tuple = DetaConfig( backbone_config=lowerCAmelCase_ , num_queries=9_0_0 , encoder_ffn_dim=2_0_4_8 , decoder_ffn_dim=2_0_4_8 , num_feature_levels=5 , assign_first_stage=lowerCAmelCase_ , with_box_refine=lowerCAmelCase_ , two_stage=lowerCAmelCase_ , ) # set labels snake_case_ : int = "huggingface/label-files" if "o365" in model_name: snake_case_ : List[Any] = 3_6_6 snake_case_ : int = "object365-id2label.json" else: snake_case_ : Optional[Any] = 9_1 snake_case_ : Any = "coco-detection-id2label.json" snake_case_ : str = num_labels snake_case_ : Union[str, Any] = json.load(open(cached_download(hf_hub_url(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) ) , "r" ) ) snake_case_ : int = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} snake_case_ : str = idalabel snake_case_ : Any = {v: k for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Dict = [] # stem # fmt: off rename_keys.append(("backbone.0.body.patch_embed.proj.weight", "model.backbone.model.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("backbone.0.body.patch_embed.proj.bias", "model.backbone.model.embeddings.patch_embeddings.projection.bias") ) rename_keys.append(("backbone.0.body.patch_embed.norm.weight", "model.backbone.model.embeddings.norm.weight") ) rename_keys.append(("backbone.0.body.patch_embed.norm.bias", "model.backbone.model.embeddings.norm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm1.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm1.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm2.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm2.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias") ) if i < 3: rename_keys.append((f"backbone.0.body.layers.{i}.downsample.reduction.weight", f"model.backbone.model.encoder.layers.{i}.downsample.reduction.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.downsample.norm.weight", f"model.backbone.model.encoder.layers.{i}.downsample.norm.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.downsample.norm.bias", f"model.backbone.model.encoder.layers.{i}.downsample.norm.bias") ) rename_keys.append(("backbone.0.body.norm1.weight", "model.backbone.model.hidden_states_norms.stage2.weight") ) rename_keys.append(("backbone.0.body.norm1.bias", "model.backbone.model.hidden_states_norms.stage2.bias") ) rename_keys.append(("backbone.0.body.norm2.weight", "model.backbone.model.hidden_states_norms.stage3.weight") ) rename_keys.append(("backbone.0.body.norm2.bias", "model.backbone.model.hidden_states_norms.stage3.bias") ) rename_keys.append(("backbone.0.body.norm3.weight", "model.backbone.model.hidden_states_norms.stage4.weight") ) rename_keys.append(("backbone.0.body.norm3.bias", "model.backbone.model.hidden_states_norms.stage4.bias") ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight", f"model.encoder.layers.{i}.self_attn.sampling_offsets.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias", f"model.encoder.layers.{i}.self_attn.sampling_offsets.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.weight", f"model.encoder.layers.{i}.self_attn.attention_weights.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.bias", f"model.encoder.layers.{i}.self_attn.attention_weights.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.weight", f"model.encoder.layers.{i}.self_attn.value_proj.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.bias", f"model.encoder.layers.{i}.self_attn.value_proj.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.weight", f"model.encoder.layers.{i}.self_attn.output_proj.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.bias", f"model.encoder.layers.{i}.self_attn.output_proj.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm1.weight", f"model.encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm1.bias", f"model.encoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"model.encoder.layers.{i}.fc1.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"model.encoder.layers.{i}.fc1.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"model.encoder.layers.{i}.fc2.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"model.encoder.layers.{i}.fc2.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.weight", f"model.encoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"model.encoder.layers.{i}.final_layer_norm.bias") ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.weight", f"model.decoder.layers.{i}.encoder_attn.attention_weights.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.bias", f"model.decoder.layers.{i}.encoder_attn.attention_weights.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.weight", f"model.decoder.layers.{i}.encoder_attn.value_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.bias", f"model.decoder.layers.{i}.encoder_attn.value_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.weight", f"model.decoder.layers.{i}.encoder_attn.output_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.bias", f"model.decoder.layers.{i}.encoder_attn.output_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm1.weight", f"model.decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm1.bias", f"model.decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"model.decoder.layers.{i}.self_attn.out_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"model.decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm2.weight", f"model.decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm2.bias", f"model.decoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"model.decoder.layers.{i}.fc1.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"model.decoder.layers.{i}.fc1.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"model.decoder.layers.{i}.fc2.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"model.decoder.layers.{i}.fc2.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.weight", f"model.decoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"model.decoder.layers.{i}.final_layer_norm.bias") ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: List[str] ): snake_case_ : Dict = dct.pop(lowerCAmelCase_ ) snake_case_ : Dict = val def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: List[Any] ): snake_case_ : int = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): snake_case_ : str = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) snake_case_ : Optional[Any] = state_dict.pop(f"backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight" ) snake_case_ : str = state_dict.pop(f"backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case_ : str = in_proj_weight[:dim, :] snake_case_ : List[str] = in_proj_bias[: dim] snake_case_ : Optional[int] = in_proj_weight[ dim : dim * 2, : ] snake_case_ : Any = in_proj_bias[ dim : dim * 2 ] snake_case_ : Optional[Any] = in_proj_weight[ -dim :, : ] snake_case_ : Optional[Any] = in_proj_bias[-dim :] # fmt: on def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Dict , lowerCAmelCase_: Union[str, Any] ): # transformer decoder self-attention layers snake_case_ : str = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention snake_case_ : List[Any] = state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) snake_case_ : str = state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict snake_case_ : Optional[Any] = in_proj_weight[:hidden_size, :] snake_case_ : Optional[Any] = in_proj_bias[:hidden_size] snake_case_ : Optional[Any] = in_proj_weight[ hidden_size : hidden_size * 2, : ] snake_case_ : Union[str, Any] = in_proj_bias[hidden_size : hidden_size * 2] snake_case_ : Any = in_proj_weight[-hidden_size:, :] snake_case_ : Optional[Any] = in_proj_bias[-hidden_size:] def SCREAMING_SNAKE_CASE_ ( ): snake_case_ : Optional[int] = "http://images.cocodataset.org/val2017/000000039769.jpg" snake_case_ : Tuple = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: int , lowerCAmelCase_: Optional[Any] ): snake_case_ : Any = get_deta_config(lowerCAmelCase_ ) # load original state dict if model_name == "deta-swin-large": snake_case_ : int = hf_hub_download(repo_id="nielsr/deta-checkpoints" , filename="adet_swin_ft.pth" ) elif model_name == "deta-swin-large-o365": snake_case_ : Dict = hf_hub_download(repo_id="jozhang97/deta-swin-l-o365" , filename="deta_swin_pt_o365.pth" ) else: raise ValueError(f"Model name {model_name} not supported" ) snake_case_ : int = torch.load(lowerCAmelCase_ , map_location="cpu" )["model"] # original state dict for name, param in state_dict.items(): print(lowerCAmelCase_ , param.shape ) # rename keys snake_case_ : str = create_rename_keys(lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) read_in_swin_q_k_v(lowerCAmelCase_ , config.backbone_config ) read_in_decoder_q_k_v(lowerCAmelCase_ , lowerCAmelCase_ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: snake_case_ : Dict = state_dict.pop(lowerCAmelCase_ ) snake_case_ : Optional[int] = val if "input_proj" in key: snake_case_ : Optional[Any] = state_dict.pop(lowerCAmelCase_ ) snake_case_ : Dict = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: snake_case_ : Union[str, Any] = state_dict.pop(lowerCAmelCase_ ) snake_case_ : str = val # finally, create HuggingFace model and load state dict snake_case_ : int = DetaForObjectDetection(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) model.eval() snake_case_ : Any = "cuda" if torch.cuda.is_available() else "cpu" model.to(lowerCAmelCase_ ) # load image processor snake_case_ : List[str] = DetaImageProcessor(format="coco_detection" ) # verify our conversion on image snake_case_ : Optional[Any] = prepare_img() snake_case_ : int = processor(images=lowerCAmelCase_ , return_tensors="pt" ) snake_case_ : List[Any] = encoding["pixel_values"] snake_case_ : List[Any] = model(pixel_values.to(lowerCAmelCase_ ) ) # verify logits print("Logits:" , outputs.logits[0, :3, :3] ) print("Boxes:" , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": snake_case_ : Any = torch.tensor( [[-7.6_3_0_8, -2.8_4_8_5, -5.3_7_3_7], [-7.2_0_3_7, -4.5_5_0_5, -4.8_0_2_7], [-7.2_9_4_3, -4.2_6_1_1, -4.6_6_1_7]] ) snake_case_ : Any = torch.tensor([[0.4_9_8_7, 0.4_9_6_9, 0.9_9_9_9], [0.2_5_4_9, 0.5_4_9_8, 0.4_8_0_5], [0.5_4_9_8, 0.2_7_5_7, 0.0_5_6_9]] ) elif model_name == "deta-swin-large-o365": snake_case_ : List[str] = torch.tensor( [[-8.0_1_2_2, -3.5_7_2_0, -4.9_7_1_7], [-8.1_5_4_7, -3.6_8_8_6, -4.6_3_8_9], [-7.6_6_1_0, -3.6_1_9_4, -5.0_1_3_4]] ) snake_case_ : str = torch.tensor([[0.2_5_2_3, 0.5_5_4_9, 0.4_8_8_1], [0.7_7_1_5, 0.4_1_4_9, 0.4_6_0_1], [0.5_5_0_3, 0.2_7_5_3, 0.0_5_7_5]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(lowerCAmelCase_ ) , atol=1e-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(lowerCAmelCase_ ) , atol=1e-4 ) print("Everything ok!" ) if pytorch_dump_folder_path: # Save model and processor logger.info(f"Saving PyTorch model and processor to {pytorch_dump_folder_path}..." ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) # Push to hub if push_to_hub: print("Pushing model and processor to hub..." ) model.push_to_hub(f"jozhang97/{model_name}" ) processor.push_to_hub(f"jozhang97/{model_name}" ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( "--model_name", type=str, default="deta-swin-large", choices=["deta-swin-large", "deta-swin-large-o365"], help="Name of the model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) UpperCAmelCase = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
666
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: tuple[int, int] , lowerCAmelCase_: int ): snake_case_ ,snake_case_ : Dict = position snake_case_ : int = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] snake_case_ : Union[str, Any] = [] for position in positions: snake_case_ ,snake_case_ : Union[str, Any] = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(lowerCAmelCase_ ) return permissible_positions def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[list[int]] , lowerCAmelCase_: tuple[int, int] , lowerCAmelCase_: int ): if is_complete(lowerCAmelCase_ ): return True for position in get_valid_pos(lowerCAmelCase_ , len(lowerCAmelCase_ ) ): snake_case_ ,snake_case_ : Dict = position if board[y][x] == 0: snake_case_ : List[str] = curr + 1 if open_knight_tour_helper(lowerCAmelCase_ , lowerCAmelCase_ , curr + 1 ): return True snake_case_ : Dict = 0 return False def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Any = [[0 for i in range(lowerCAmelCase_ )] for j in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): snake_case_ : Optional[Any] = 1 if open_knight_tour_helper(lowerCAmelCase_ , (i, j) , 1 ): return board snake_case_ : Dict = 0 snake_case_ : str = f"Open Kight Tour cannot be performed on a board of size {n}" raise ValueError(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
666
1
from math import loga def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): if a < 0: raise ValueError("Input value must be a positive integer" ) elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("Input value must be a 'int' type" ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
666
from ...configuration_utils import PretrainedConfig class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = "bert-generation" def __init__( self : Optional[int] , A__ : List[Any]=5_03_58 , A__ : Any=10_24 , A__ : Any=24 , A__ : List[Any]=16 , A__ : List[Any]=40_96 , A__ : int="gelu" , A__ : List[str]=0.1 , A__ : List[str]=0.1 , A__ : str=5_12 , A__ : int=0.02 , A__ : Any=1E-12 , A__ : Optional[Any]=0 , A__ : List[str]=2 , A__ : Optional[int]=1 , A__ : str="absolute" , A__ : Any=True , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , **A__ ) snake_case_ : str = vocab_size snake_case_ : int = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = hidden_act snake_case_ : Tuple = intermediate_size snake_case_ : str = hidden_dropout_prob snake_case_ : Optional[Any] = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Optional[Any] = initializer_range snake_case_ : Optional[int] = layer_norm_eps snake_case_ : str = position_embedding_type snake_case_ : Dict = use_cache
666
1
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/config.json", # See all BART models at https://huggingface.co/models?filter=bart } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = "bart" _SCREAMING_SNAKE_CASE : Optional[Any] = ["past_key_values"] _SCREAMING_SNAKE_CASE : List[Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Optional[int] , A__ : Tuple=5_02_65 , A__ : Dict=10_24 , A__ : Optional[int]=12 , A__ : Tuple=40_96 , A__ : str=16 , A__ : Any=12 , A__ : List[str]=40_96 , A__ : int=16 , A__ : str=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]="gelu" , A__ : Optional[Any]=10_24 , A__ : Optional[int]=0.1 , A__ : Optional[Any]=0.0 , A__ : List[str]=0.0 , A__ : List[Any]=0.02 , A__ : Dict=0.0 , A__ : Optional[Any]=False , A__ : Optional[int]=True , A__ : Optional[Any]=3 , A__ : List[Any]=1 , A__ : str=0 , A__ : List[Any]=2 , A__ : Any=True , A__ : Optional[Any]=2 , A__ : Dict=2 , **A__ : Union[str, Any] , ) -> Any: '''simple docstring''' snake_case_ : List[str] = vocab_size snake_case_ : int = max_position_embeddings snake_case_ : List[Any] = d_model snake_case_ : Dict = encoder_ffn_dim snake_case_ : Optional[int] = encoder_layers snake_case_ : Any = encoder_attention_heads snake_case_ : Any = decoder_ffn_dim snake_case_ : Dict = decoder_layers snake_case_ : int = decoder_attention_heads snake_case_ : Union[str, Any] = dropout snake_case_ : str = attention_dropout snake_case_ : List[str] = activation_dropout snake_case_ : int = activation_function snake_case_ : Optional[Any] = init_std snake_case_ : List[str] = encoder_layerdrop snake_case_ : Tuple = decoder_layerdrop snake_case_ : Dict = classifier_dropout snake_case_ : List[str] = use_cache snake_case_ : Optional[int] = encoder_layers snake_case_ : Any = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=A__ , pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , is_encoder_decoder=A__ , decoder_start_token_id=A__ , forced_eos_token_id=A__ , **A__ , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , A__ ): snake_case_ : Any = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " "The config can simply be saved and uploaded again to be fixed." ) class snake_case__ ( _UpperCamelCase ): @property def UpperCAmelCase__ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: snake_case_ : str = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: snake_case_ : List[str] = {0: "batch"} snake_case_ : int = {0: "batch", 1: "past_decoder_sequence + sequence"} else: snake_case_ : Any = {0: "batch", 1: "decoder_sequence"} snake_case_ : List[Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(A__ , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. snake_case_ : Tuple = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: snake_case_ ,snake_case_ : str = self.num_layers for i in range(A__ ): snake_case_ : Any = {0: "batch", 2: "past_sequence + sequence"} snake_case_ : Union[str, Any] = {0: "batch", 2: "past_sequence + sequence"} else: snake_case_ : str = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def UpperCAmelCase__ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: snake_case_ : Optional[int] = super().outputs else: snake_case_ : str = super(A__ , self ).outputs if self.use_past: snake_case_ ,snake_case_ : int = self.num_layers for i in range(A__ ): snake_case_ : List[str] = {0: "batch", 2: "past_sequence + sequence"} snake_case_ : Tuple = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def UpperCAmelCase__ ( self : Tuple , A__ : PreTrainedTokenizer , A__ : int = -1 , A__ : int = -1 , A__ : bool = False , A__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : Union[str, Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A__ , A__ , A__ , A__ , A__ ) # Generate decoder inputs snake_case_ : Optional[Any] = seq_length if not self.use_past else 1 snake_case_ : Optional[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A__ , A__ , A__ , A__ , A__ ) snake_case_ : List[str] = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} snake_case_ : Dict = dict(**A__ , **A__ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch snake_case_ ,snake_case_ : Optional[Any] = common_inputs["input_ids"].shape snake_case_ : List[Any] = common_inputs["decoder_input_ids"].shape[1] snake_case_ ,snake_case_ : int = self.num_attention_heads snake_case_ : int = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) snake_case_ : int = decoder_seq_length + 3 snake_case_ : List[Any] = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) snake_case_ : List[str] = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(A__ , A__ )] , dim=1 ) snake_case_ : str = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered snake_case_ ,snake_case_ : List[Any] = self.num_layers snake_case_ : str = min(A__ , A__ ) snake_case_ : List[str] = max(A__ , A__ ) - min_num_layers snake_case_ : Dict = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(A__ ): common_inputs["past_key_values"].append( ( torch.zeros(A__ ), torch.zeros(A__ ), torch.zeros(A__ ), torch.zeros(A__ ), ) ) # TODO: test this. snake_case_ : Dict = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(A__ , A__ ): common_inputs["past_key_values"].append((torch.zeros(A__ ), torch.zeros(A__ )) ) return common_inputs def UpperCAmelCase__ ( self : Optional[Any] , A__ : PreTrainedTokenizer , A__ : int = -1 , A__ : int = -1 , A__ : bool = False , A__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A__ , A__ , A__ , A__ , A__ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch snake_case_ ,snake_case_ : List[str] = common_inputs["input_ids"].shape # Not using the same length for past_key_values snake_case_ : Optional[Any] = seqlen + 2 snake_case_ ,snake_case_ : List[str] = self.num_layers snake_case_ ,snake_case_ : List[Any] = self.num_attention_heads snake_case_ : Optional[int] = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) snake_case_ : List[str] = common_inputs["attention_mask"].dtype snake_case_ : int = torch.cat( [common_inputs["attention_mask"], torch.ones(A__ , A__ , dtype=A__ )] , dim=1 ) snake_case_ : Dict = [ (torch.zeros(A__ ), torch.zeros(A__ )) for _ in range(A__ ) ] return common_inputs def UpperCAmelCase__ ( self : List[str] , A__ : PreTrainedTokenizer , A__ : int = -1 , A__ : int = -1 , A__ : bool = False , A__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : List[Any] = compute_effective_axis_dimension( A__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX snake_case_ : List[Any] = tokenizer.num_special_tokens_to_add(A__ ) snake_case_ : Any = compute_effective_axis_dimension( A__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A__ ) # Generate dummy inputs according to compute batch and sequence snake_case_ : Union[str, Any] = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size snake_case_ : Dict = dict(tokenizer(A__ , return_tensors=A__ ) ) return common_inputs def UpperCAmelCase__ ( self : Union[str, Any] , A__ : PreTrainedTokenizer , A__ : int = -1 , A__ : int = -1 , A__ : bool = False , A__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: snake_case_ : Union[str, Any] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( A__ , batch_size=A__ , seq_length=A__ , is_pair=A__ , framework=A__ ) elif self.task == "causal-lm": snake_case_ : List[str] = self._generate_dummy_inputs_for_causal_lm( A__ , batch_size=A__ , seq_length=A__ , is_pair=A__ , framework=A__ ) else: snake_case_ : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A__ , batch_size=A__ , seq_length=A__ , is_pair=A__ , framework=A__ ) return common_inputs def UpperCAmelCase__ ( self : Optional[Any] , A__ : Any , A__ : Optional[int] , A__ : Optional[int] , A__ : List[str] ) -> List[str]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: snake_case_ : Any = super()._flatten_past_key_values_(A__ , A__ , A__ , A__ ) else: snake_case_ : Optional[Any] = super(A__ , self )._flatten_past_key_values_( A__ , A__ , A__ , A__ )
666
import math def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Any = [] snake_case_ : List[str] = 2 snake_case_ : Optional[int] = int(math.sqrt(lowerCAmelCase_ ) ) # Size of every segment snake_case_ : str = [True] * (end + 1) snake_case_ : Any = [] while start <= end: if temp[start] is True: in_prime.append(lowerCAmelCase_ ) for i in range(start * start , end + 1 , lowerCAmelCase_ ): snake_case_ : Union[str, Any] = False start += 1 prime += in_prime snake_case_ : Dict = end + 1 snake_case_ : Dict = min(2 * end , lowerCAmelCase_ ) while low <= n: snake_case_ : Any = [True] * (high - low + 1) for each in in_prime: snake_case_ : Optional[Any] = math.floor(low / each ) * each if t < low: t += each for j in range(lowerCAmelCase_ , high + 1 , lowerCAmelCase_ ): snake_case_ : List[Any] = False for j in range(len(lowerCAmelCase_ ) ): if temp[j] is True: prime.append(j + low ) snake_case_ : int = high + 1 snake_case_ : Union[str, Any] = min(high + end , lowerCAmelCase_ ) return prime print(sieve(1_0**6))
666
1
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( _UpperCamelCase ): def __init__( self : Union[str, Any] , A__ : VQModel , A__ : UNetaDModel , A__ : DDIMScheduler ) -> List[Any]: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : str , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : float = 0.0 , A__ : int = 50 , A__ : Optional[str] = "pil" , A__ : bool = True , **A__ : Optional[Any] , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' snake_case_ : Optional[int] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=A__ , ) snake_case_ : List[Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ : Any = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(A__ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature snake_case_ : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ : List[Any] = {} if accepts_eta: snake_case_ : int = eta for t in self.progress_bar(self.scheduler.timesteps ): snake_case_ : Union[str, Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual snake_case_ : Dict = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case_ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VAE snake_case_ : int = self.vqvae.decode(A__ ).sample snake_case_ : Dict = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ : Optional[int] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
666
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self : List[str] , A__ : List[Any] , A__ : int=7 , A__ : Union[str, Any]=3 , A__ : List[str]=30 , A__ : Optional[int]=4_00 , A__ : Optional[Any]=True , A__ : Optional[int]=None , A__ : Optional[Any]=True , A__ : Any=[0.5, 0.5, 0.5] , A__ : int=[0.5, 0.5, 0.5] , A__ : Any=True , A__ : int=1 / 2_55 , A__ : List[str]=True , ) -> Dict: '''simple docstring''' snake_case_ : int = size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33} snake_case_ : Any = parent snake_case_ : Optional[int] = batch_size snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = min_resolution snake_case_ : List[Any] = max_resolution snake_case_ : Tuple = do_resize snake_case_ : Dict = size snake_case_ : Optional[Any] = do_normalize snake_case_ : int = image_mean snake_case_ : List[Any] = image_std snake_case_ : Tuple = do_rescale snake_case_ : Any = rescale_factor snake_case_ : Optional[int] = do_pad def UpperCAmelCase__ ( self : int ) -> List[str]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self : Optional[int] , A__ : Optional[int] , A__ : Any=False ) -> Optional[Any]: '''simple docstring''' if not batched: snake_case_ : Any = image_inputs[0] if isinstance(A__ , Image.Image ): snake_case_ ,snake_case_ : Dict = image.size else: snake_case_ ,snake_case_ : int = image.shape[1], image.shape[2] if w < h: snake_case_ : Dict = int(self.size["shortest_edge"] * h / w ) snake_case_ : Optional[int] = self.size["shortest_edge"] elif w > h: snake_case_ : Optional[int] = self.size["shortest_edge"] snake_case_ : str = int(self.size["shortest_edge"] * w / h ) else: snake_case_ : Optional[int] = self.size["shortest_edge"] snake_case_ : List[Any] = self.size["shortest_edge"] else: snake_case_ : str = [] for image in image_inputs: snake_case_ ,snake_case_ : Tuple = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) snake_case_ : List[Any] = max(A__ , key=lambda A__ : item[0] )[0] snake_case_ : int = max(A__ , key=lambda A__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = ConditionalDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Tuple ) -> Dict: '''simple docstring''' snake_case_ : List[str] = ConditionalDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Any ) -> Tuple: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , "image_mean" ) ) self.assertTrue(hasattr(A__ , "image_std" ) ) self.assertTrue(hasattr(A__ , "do_normalize" ) ) self.assertTrue(hasattr(A__ , "do_resize" ) ) self.assertTrue(hasattr(A__ , "size" ) ) def UpperCAmelCase__ ( self : List[str] ) -> Tuple: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 13_33} ) self.assertEqual(image_processor.do_pad , A__ ) snake_case_ : Optional[int] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A__ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , A__ ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: '''simple docstring''' pass def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : Optional[Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ ,snake_case_ : List[Any] = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) snake_case_ : int = image_processing(A__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : int ) -> Any: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , numpify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , np.ndarray ) # Test not batched input snake_case_ : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : List[str] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Optional[int] = image_processing(A__ , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : Dict = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : Tuple ) -> str: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , torchify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , torch.Tensor ) # Test not batched input snake_case_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : List[Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Any = image_processing(A__ , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : int = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: snake_case_ : Optional[Any] = json.loads(f.read() ) snake_case_ : int = {"image_id": 3_97_69, "annotations": target} # encode them snake_case_ : Optional[int] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) snake_case_ : Any = image_processing(images=A__ , annotations=A__ , return_tensors="pt" ) # verify pixel values snake_case_ : List[Any] = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , A__ ) snake_case_ : List[str] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Tuple = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A__ ) ) # verify boxes snake_case_ : Any = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A__ ) snake_case_ : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : List[Any] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A__ ) ) # verify is_crowd snake_case_ : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A__ ) ) # verify class_labels snake_case_ : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A__ ) ) # verify orig_size snake_case_ : Any = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A__ ) ) # verify size snake_case_ : List[str] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A__ ) ) @slow def UpperCAmelCase__ ( self : int ) -> str: '''simple docstring''' snake_case_ : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: snake_case_ : Any = json.loads(f.read() ) snake_case_ : Optional[Any] = {"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target} snake_case_ : int = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them snake_case_ : Union[str, Any] = ConditionalDetrImageProcessor(format="coco_panoptic" ) snake_case_ : str = image_processing(images=A__ , annotations=A__ , masks_path=A__ , return_tensors="pt" ) # verify pixel values snake_case_ : int = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , A__ ) snake_case_ : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Optional[int] = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A__ ) ) # verify boxes snake_case_ : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A__ ) snake_case_ : str = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : List[str] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A__ ) ) # verify is_crowd snake_case_ : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A__ ) ) # verify class_labels snake_case_ : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A__ ) ) # verify masks snake_case_ : Union[str, Any] = 82_28_73 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , A__ ) # verify orig_size snake_case_ : Dict = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A__ ) ) # verify size snake_case_ : str = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A__ ) )
666
1
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger("transformers.models.speecht5") def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple , lowerCAmelCase_: Optional[int] , lowerCAmelCase_: int ): hf_model.apply_weight_norm() snake_case_ : Any = checkpoint["input_conv.weight_g"] snake_case_ : Union[str, Any] = checkpoint["input_conv.weight_v"] snake_case_ : List[Any] = checkpoint["input_conv.bias"] for i in range(len(config.upsample_rates ) ): snake_case_ : str = checkpoint[f"upsamples.{i}.1.weight_g"] snake_case_ : List[Any] = checkpoint[f"upsamples.{i}.1.weight_v"] snake_case_ : Optional[int] = checkpoint[f"upsamples.{i}.1.bias"] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): snake_case_ : Tuple = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_g"] snake_case_ : Dict = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_v"] snake_case_ : Dict = checkpoint[f"blocks.{i}.convs1.{j}.1.bias"] snake_case_ : Union[str, Any] = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_g"] snake_case_ : int = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_v"] snake_case_ : Dict = checkpoint[f"blocks.{i}.convs2.{j}.1.bias"] snake_case_ : Any = checkpoint["output_conv.1.weight_g"] snake_case_ : Optional[int] = checkpoint["output_conv.1.weight_v"] snake_case_ : str = checkpoint["output_conv.1.bias"] hf_model.remove_weight_norm() @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] , lowerCAmelCase_: Dict , lowerCAmelCase_: Optional[int] , lowerCAmelCase_: Dict=None , lowerCAmelCase_: Tuple=None , ): if config_path is not None: snake_case_ : int = SpeechTaHifiGanConfig.from_pretrained(lowerCAmelCase_ ) else: snake_case_ : Tuple = SpeechTaHifiGanConfig() snake_case_ : Dict = SpeechTaHifiGan(lowerCAmelCase_ ) snake_case_ : int = torch.load(lowerCAmelCase_ ) load_weights(orig_checkpoint["model"]["generator"] , lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : str = np.load(lowerCAmelCase_ ) snake_case_ : int = stats[0].reshape(-1 ) snake_case_ : Optional[Any] = stats[1].reshape(-1 ) snake_case_ : List[str] = torch.from_numpy(lowerCAmelCase_ ).float() snake_case_ : Union[str, Any] = torch.from_numpy(lowerCAmelCase_ ).float() model.save_pretrained(lowerCAmelCase_ ) if repo_id: print("Pushing to the hub..." ) model.push_to_hub(lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--stats_path", required=True, default=None, type=str, help="Path to stats.npy file") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
666
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) UpperCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class snake_case__ : _SCREAMING_SNAKE_CASE : str = field( default=_UpperCamelCase , metadata={"help": "Model type selected in the list: " + ", ".join(_UpperCamelCase )} ) _SCREAMING_SNAKE_CASE : str = field( default=_UpperCamelCase , metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} ) _SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) _SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."} , ) _SCREAMING_SNAKE_CASE : int = field( default=6_4 , metadata={ "help": ( "The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length." ) } , ) _SCREAMING_SNAKE_CASE : int = field( default=3_0 , metadata={ "help": ( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ) } , ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"} ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} ) _SCREAMING_SNAKE_CASE : float = field( default=0.0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) _SCREAMING_SNAKE_CASE : int = field( default=2_0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) _SCREAMING_SNAKE_CASE : int = field( default=0 , metadata={ "help": ( "language id of input for language-specific xlm models (see" " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)" ) } , ) _SCREAMING_SNAKE_CASE : int = field(default=1 , metadata={"help": "multiple threads for converting example to features"} ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = "train" _SCREAMING_SNAKE_CASE : Any = "dev" class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : SquadDataTrainingArguments _SCREAMING_SNAKE_CASE : List[SquadFeatures] _SCREAMING_SNAKE_CASE : Split _SCREAMING_SNAKE_CASE : bool def __init__( self : str , A__ : SquadDataTrainingArguments , A__ : PreTrainedTokenizer , A__ : Optional[int] = None , A__ : Union[str, Split] = Split.train , A__ : Optional[bool] = False , A__ : Optional[str] = None , A__ : Optional[str] = "pt" , ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = args snake_case_ : int = is_language_sensitive snake_case_ : int = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(A__ , A__ ): try: snake_case_ : List[str] = Split[mode] except KeyError: raise KeyError("mode is not a valid split name" ) snake_case_ : Tuple = mode # Load data features from cache or dataset file snake_case_ : Dict = "v2" if args.version_2_with_negative else "v1" snake_case_ : List[Any] = os.path.join( cache_dir if cache_dir is not None else args.data_dir , f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : List[Any] = cached_features_file + ".lock" with FileLock(A__ ): if os.path.exists(A__ ) and not args.overwrite_cache: snake_case_ : int = time.time() snake_case_ : List[Any] = torch.load(A__ ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. snake_case_ : Tuple = self.old_features["features"] snake_case_ : List[str] = self.old_features.get("dataset" , A__ ) snake_case_ : Tuple = self.old_features.get("examples" , A__ ) logger.info( f"Loading features from cached file {cached_features_file} [took %.3f s]" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in" " future run" ) else: if mode == Split.dev: snake_case_ : Tuple = self.processor.get_dev_examples(args.data_dir ) else: snake_case_ : Tuple = self.processor.get_train_examples(args.data_dir ) snake_case_ ,snake_case_ : Optional[Any] = squad_convert_examples_to_features( examples=self.examples , tokenizer=A__ , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=A__ , ) snake_case_ : Any = time.time() torch.save( {"features": self.features, "dataset": self.dataset, "examples": self.examples} , A__ , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" ) def __len__( self : str ) -> Dict: '''simple docstring''' return len(self.features ) def __getitem__( self : Optional[int] , A__ : Optional[int] ) -> Dict[str, torch.Tensor]: '''simple docstring''' snake_case_ : Any = self.features[i] snake_case_ : Optional[int] = torch.tensor(feature.input_ids , dtype=torch.long ) snake_case_ : Union[str, Any] = torch.tensor(feature.attention_mask , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.token_type_ids , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.cls_index , dtype=torch.long ) snake_case_ : str = torch.tensor(feature.p_mask , dtype=torch.float ) snake_case_ : str = torch.tensor(feature.is_impossible , dtype=torch.float ) snake_case_ : Optional[int] = { "input_ids": input_ids, "attention_mask": attention_mask, "token_type_ids": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"cls_index": cls_index, "p_mask": p_mask} ) if self.args.version_2_with_negative: inputs.update({"is_impossible": is_impossible} ) if self.is_language_sensitive: inputs.update({"langs": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: snake_case_ : Any = torch.tensor(feature.start_position , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({"start_positions": start_positions, "end_positions": end_positions} ) return inputs
666
1
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files" , [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos.json"], ["full:README.md"], ] , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: Any ): snake_case_ : Any = tmp_path_factory.mktemp("dset_infos_dir" ) if "full:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("---\ndataset_info:\n dataset_size: 42\n---" ) if "empty:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / "dataset_infos.json" , "w" ) as f: f.write("{\"default\": {\"dataset_size\": 42}}" ) snake_case_ : str = DatasetInfosDict.from_directory(lowerCAmelCase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 4_2 @pytest.mark.parametrize( "dataset_info" , [ DatasetInfo(), DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=4_2 , ), ] , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: DatasetInfo ): snake_case_ : Optional[Any] = str(lowerCAmelCase_ ) dataset_info.write_to_directory(lowerCAmelCase_ ) snake_case_ : List[str] = DatasetInfo.from_directory(lowerCAmelCase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowerCAmelCase_ , "dataset_info.json" ) ) def SCREAMING_SNAKE_CASE_ ( ): snake_case_ : Union[str, Any] = DatasetInfo( description="foo" , citation="bar" , homepage="https://foo.bar" , license="CC0" , features=Features({"a": Value("int32" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train", "num_examples": 4_2}] , download_checksums={} , download_size=1_3_3_7 , post_processing_size=4_4_2 , dataset_size=1_2_3_4 , size_in_bytes=1_3_3_7 + 4_4_2 + 1_2_3_4 , ) snake_case_ : Any = dataset_info._to_yaml_dict() assert sorted(lowerCAmelCase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) snake_case_ : int = yaml.safe_dump(lowerCAmelCase_ ) snake_case_ : int = yaml.safe_load(lowerCAmelCase_ ) assert dataset_info_yaml_dict == reloaded def SCREAMING_SNAKE_CASE_ ( ): snake_case_ : Union[str, Any] = DatasetInfo() snake_case_ : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( "dataset_infos_dict" , [ DatasetInfosDict(), DatasetInfosDict({"default": DatasetInfo()} ), DatasetInfosDict({"my_config_name": DatasetInfo()} ), DatasetInfosDict( { "default": DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=4_2 , ) } ), DatasetInfosDict( { "v1": DatasetInfo(dataset_size=4_2 ), "v2": DatasetInfo(dataset_size=1_3_3_7 ), } ), ] , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: DatasetInfosDict ): snake_case_ : Tuple = str(lowerCAmelCase_ ) dataset_infos_dict.write_to_directory(lowerCAmelCase_ ) snake_case_ : Any = DatasetInfosDict.from_directory(lowerCAmelCase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): snake_case_ : Union[str, Any] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml snake_case_ : List[str] = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowerCAmelCase_ , "README.md" ) )
666
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "git_vision_model" def __init__( self : int , A__ : Union[str, Any]=7_68 , A__ : List[Any]=30_72 , A__ : Tuple=12 , A__ : Optional[Any]=12 , A__ : Optional[int]=3 , A__ : List[str]=2_24 , A__ : Dict=16 , A__ : int="quick_gelu" , A__ : Any=1E-5 , A__ : Tuple=0.0 , A__ : Optional[int]=0.02 , **A__ : List[str] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : str = intermediate_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Optional[int] = num_channels snake_case_ : Union[str, Any] = patch_size snake_case_ : List[str] = image_size snake_case_ : List[Any] = initializer_range snake_case_ : Any = attention_dropout snake_case_ : Any = layer_norm_eps snake_case_ : int = hidden_act @classmethod def UpperCAmelCase__ ( cls : List[Any] , A__ : Union[str, os.PathLike] , **A__ : Optional[int] ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(A__ ) snake_case_ ,snake_case_ : Tuple = cls.get_config_dict(A__ , **A__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("model_type" ) == "git": snake_case_ : 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(A__ , **A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = "git" def __init__( self : Any , A__ : List[str]=None , A__ : List[str]=3_05_22 , A__ : Tuple=7_68 , A__ : Tuple=6 , A__ : str=12 , A__ : Any=30_72 , A__ : List[str]="gelu" , A__ : int=0.1 , A__ : Dict=0.1 , A__ : Any=10_24 , A__ : Optional[Any]=0.02 , A__ : Optional[Any]=1E-12 , A__ : Dict=0 , A__ : Any="absolute" , A__ : Tuple=True , A__ : Any=False , A__ : Tuple=1_01 , A__ : Tuple=1_02 , A__ : List[Any]=None , **A__ : List[str] , ) -> int: '''simple docstring''' super().__init__(bos_token_id=A__ , eos_token_id=A__ , pad_token_id=A__ , **A__ ) if vision_config is None: snake_case_ : int = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values." ) snake_case_ : str = GitVisionConfig(**A__ ) snake_case_ : int = vocab_size snake_case_ : List[Any] = hidden_size snake_case_ : Tuple = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Any = hidden_act snake_case_ : Dict = intermediate_size snake_case_ : Any = hidden_dropout_prob snake_case_ : Any = attention_probs_dropout_prob snake_case_ : Union[str, Any] = max_position_embeddings snake_case_ : List[str] = initializer_range snake_case_ : List[str] = layer_norm_eps snake_case_ : Any = position_embedding_type snake_case_ : Union[str, Any] = use_cache snake_case_ : str = tie_word_embeddings snake_case_ : List[Any] = num_image_with_embedding snake_case_ : Dict = bos_token_id snake_case_ : int = eos_token_id def UpperCAmelCase__ ( self : Any ) -> int: '''simple docstring''' snake_case_ : Tuple = copy.deepcopy(self.__dict__ ) snake_case_ : Optional[int] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output
666
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) UpperCAmelCase = logging.getLogger(__name__) @dataclass class snake_case__ : _SCREAMING_SNAKE_CASE : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) _SCREAMING_SNAKE_CASE : bool = field(default=_UpperCamelCase , metadata={"help": "Whether tp freeze the encoder."} ) _SCREAMING_SNAKE_CASE : bool = field(default=_UpperCamelCase , metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class snake_case__ : _SCREAMING_SNAKE_CASE : str = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default="summarization" , metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"} , ) _SCREAMING_SNAKE_CASE : Optional[int] = field( default=1_0_2_4 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) _SCREAMING_SNAKE_CASE : Optional[int] = field( default=1_2_8 , metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) _SCREAMING_SNAKE_CASE : Optional[int] = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) } , ) _SCREAMING_SNAKE_CASE : Optional[int] = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) _SCREAMING_SNAKE_CASE : Optional[int] = field(default=-1 , metadata={"help": "# training examples. -1 means use all."} ) _SCREAMING_SNAKE_CASE : Optional[int] = field(default=-1 , metadata={"help": "# validation examples. -1 means use all."} ) _SCREAMING_SNAKE_CASE : Optional[int] = field(default=-1 , metadata={"help": "# test examples. -1 means use all."} ) _SCREAMING_SNAKE_CASE : Optional[str] = field(default=_UpperCamelCase , metadata={"help": "Source language id for translation."} ) _SCREAMING_SNAKE_CASE : Optional[str] = field(default=_UpperCamelCase , metadata={"help": "Target language id for translation."} ) _SCREAMING_SNAKE_CASE : Optional[int] = field(default=_UpperCamelCase , metadata={"help": "# num_beams to use for evaluation."} ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."} , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: Optional[int] ): logger.info(f"***** {split} metrics *****" ) for key in sorted(metrics.keys() ): logger.info(f" {key} = {metrics[key]}" ) save_json(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , f"{split}_results.json" ) ) def SCREAMING_SNAKE_CASE_ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. snake_case_ : str = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case_ ,snake_case_ ,snake_case_ : int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case_ ,snake_case_ ,snake_case_ : Dict = parser.parse_args_into_dataclasses() check_output_dir(lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ : Optional[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case_ : str = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): assert hasattr(lowerCAmelCase_ , lowerCAmelCase_ ), f"({config.__class__.__name__}) doesn't have a `{p}` attribute" setattr(lowerCAmelCase_ , lowerCAmelCase_ , getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) snake_case_ : Dict = 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 , ) snake_case_ : List[str] = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(lowerCAmelCase_ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: snake_case_ : Union[str, Any] = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(lowerCAmelCase_ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): snake_case_ : Optional[Any] = tokenizer.lang_code_to_id[data_args.tgt_lang] else: snake_case_ : Any = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(lowerCAmelCase_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) snake_case_ : str = SeqaSeqDataset # Get datasets snake_case_ : Dict = ( dataset_class( lowerCAmelCase_ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) snake_case_ : Tuple = ( dataset_class( lowerCAmelCase_ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) snake_case_ : int = ( dataset_class( lowerCAmelCase_ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer snake_case_ : List[Any] = ( build_compute_metrics_fn(data_args.task , lowerCAmelCase_ ) if training_args.predict_with_generate else None ) snake_case_ : int = SeqaSeqTrainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , data_args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , data_collator=SeqaSeqDataCollator( lowerCAmelCase_ , lowerCAmelCase_ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , ) snake_case_ : Tuple = {} # Training if training_args.do_train: logger.info("*** Train ***" ) snake_case_ : Dict = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) snake_case_ : Union[str, Any] = train_result.metrics snake_case_ : Dict = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , lowerCAmelCase_ , training_args.output_dir ) all_metrics.update(lowerCAmelCase_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) snake_case_ : int = trainer.evaluate(metric_key_prefix="val" ) snake_case_ : Dict = data_args.n_val snake_case_ : Union[str, Any] = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , lowerCAmelCase_ , training_args.output_dir ) all_metrics.update(lowerCAmelCase_ ) if training_args.do_predict: logger.info("*** Predict ***" ) snake_case_ : Any = trainer.predict(test_dataset=lowerCAmelCase_ , metric_key_prefix="test" ) snake_case_ : Dict = test_output.metrics snake_case_ : str = data_args.n_test if trainer.is_world_process_zero(): snake_case_ : Dict = round(metrics["test_loss"] , 4 ) handle_metrics("test" , lowerCAmelCase_ , training_args.output_dir ) all_metrics.update(lowerCAmelCase_ ) if training_args.predict_with_generate: snake_case_ : int = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ ) snake_case_ : str = lmap(str.strip , lowerCAmelCase_ ) write_txt_file(lowerCAmelCase_ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(lowerCAmelCase_ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
666
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: str ): def get_matched_characters(lowerCAmelCase_: str , lowerCAmelCase_: str ) -> str: snake_case_ : Tuple = [] snake_case_ : Tuple = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): snake_case_ : str = int(max(0 , i - limit ) ) snake_case_ : Optional[int] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCAmelCase_ ) snake_case_ : List[Any] = f"{_stra[0:_stra.index(lowerCAmelCase_ )]} {_stra[_stra.index(lowerCAmelCase_ ) + 1:]}" return "".join(lowerCAmelCase_ ) # matching characters snake_case_ : List[Any] = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : int = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = len(lowerCAmelCase_ ) # transposition snake_case_ : List[str] = ( len([(ca, ca) for ca, ca in zip(lowerCAmelCase_ , lowerCAmelCase_ ) if ca != ca] ) // 2 ) if not match_count: snake_case_ : str = 0.0 else: snake_case_ : Optional[Any] = ( 1 / 3 * ( match_count / len(lowerCAmelCase_ ) + match_count / len(lowerCAmelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters snake_case_ : Optional[Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
666
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Union[List[PIL.Image.Image], np.ndarray] _SCREAMING_SNAKE_CASE : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.26.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version(">=", "0.0.12") ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : np.ndarray _SCREAMING_SNAKE_CASE : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
666
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) set_seed(7_7_0) UpperCAmelCase = { "c_attn": "att_proj", "c_proj": "out_proj", "c_fc": "in_proj", "transformer.": "", "h.": "layers.", "ln_1": "layernorm_1", "ln_2": "layernorm_2", "ln_f": "layernorm_final", "wpe": "position_embeds_layer", "wte": "input_embeds_layer", } UpperCAmelCase = { "text_small": { "repo_id": "suno/bark", "file_name": "text.pt", }, "coarse_small": { "repo_id": "suno/bark", "file_name": "coarse.pt", }, "fine_small": { "repo_id": "suno/bark", "file_name": "fine.pt", }, "text": { "repo_id": "suno/bark", "file_name": "text_2.pt", }, "coarse": { "repo_id": "suno/bark", "file_name": "coarse_2.pt", }, "fine": { "repo_id": "suno/bark", "file_name": "fine_2.pt", }, } UpperCAmelCase = os.path.dirname(os.path.abspath(__file__)) UpperCAmelCase = os.path.join(os.path.expanduser("~"), ".cache") UpperCAmelCase = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: List[str]=False ): snake_case_ : Union[str, Any] = model_type if use_small: key += "_small" return os.path.join(lowerCAmelCase_ , REMOTE_MODEL_PATHS[key]["file_name"] ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: List[str] ): os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) hf_hub_download(repo_id=lowerCAmelCase_ , filename=lowerCAmelCase_ , local_dir=lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: Dict , lowerCAmelCase_: List[str]=False , lowerCAmelCase_: Dict="text" ): if model_type == "text": snake_case_ : int = BarkSemanticModel snake_case_ : str = BarkSemanticConfig snake_case_ : Optional[Any] = BarkSemanticGenerationConfig elif model_type == "coarse": snake_case_ : str = BarkCoarseModel snake_case_ : Optional[int] = BarkCoarseConfig snake_case_ : Any = BarkCoarseGenerationConfig elif model_type == "fine": snake_case_ : Optional[int] = BarkFineModel snake_case_ : Tuple = BarkFineConfig snake_case_ : List[str] = BarkFineGenerationConfig else: raise NotImplementedError() snake_case_ : Optional[Any] = f"{model_type}_small" if use_small else model_type snake_case_ : Any = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(lowerCAmelCase_ ): logger.info(f"{model_type} model not found, downloading into `{CACHE_DIR}`." ) _download(model_info["repo_id"] , model_info["file_name"] ) snake_case_ : Any = torch.load(lowerCAmelCase_ , map_location=lowerCAmelCase_ ) # this is a hack snake_case_ : Union[str, Any] = checkpoint["model_args"] if "input_vocab_size" not in model_args: snake_case_ : str = model_args["vocab_size"] snake_case_ : Union[str, Any] = model_args["vocab_size"] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments snake_case_ : Union[str, Any] = model_args.pop("n_head" ) snake_case_ : int = model_args.pop("n_embd" ) snake_case_ : Any = model_args.pop("n_layer" ) snake_case_ : List[str] = ConfigClass(**checkpoint["model_args"] ) snake_case_ : Optional[Any] = ModelClass(config=lowerCAmelCase_ ) snake_case_ : Tuple = GenerationConfigClass() snake_case_ : List[str] = model_generation_config snake_case_ : Optional[int] = checkpoint["model"] # fixup checkpoint snake_case_ : Optional[int] = "_orig_mod." for k, v in list(state_dict.items() ): if k.startswith(lowerCAmelCase_ ): # replace part of the key with corresponding layer name in HF implementation snake_case_ : Tuple = k[len(lowerCAmelCase_ ) :] for old_layer_name in new_layer_name_dict: snake_case_ : int = new_k.replace(lowerCAmelCase_ , new_layer_name_dict[old_layer_name] ) snake_case_ : int = state_dict.pop(lowerCAmelCase_ ) snake_case_ : Optional[int] = set(state_dict.keys() ) - set(model.state_dict().keys() ) snake_case_ : str = {k for k in extra_keys if not k.endswith(".attn.bias" )} snake_case_ : Any = set(model.state_dict().keys() ) - set(state_dict.keys() ) snake_case_ : List[Any] = {k for k in missing_keys if not k.endswith(".attn.bias" )} if len(lowerCAmelCase_ ) != 0: raise ValueError(f"extra keys found: {extra_keys}" ) if len(lowerCAmelCase_ ) != 0: raise ValueError(f"missing keys: {missing_keys}" ) model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) snake_case_ : str = model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) snake_case_ : Union[str, Any] = checkpoint["best_val_loss"].item() logger.info(f"model loaded: {round(n_params/1e6 , 1 )}M params, {round(lowerCAmelCase_ , 3 )} loss" ) model.eval() model.to(lowerCAmelCase_ ) del checkpoint, state_dict return model def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] , lowerCAmelCase_: str=False , lowerCAmelCase_: int="text" ): if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() snake_case_ : int = "cpu" # do conversion on cpu snake_case_ : Optional[Any] = _get_ckpt_path(lowerCAmelCase_ , use_small=lowerCAmelCase_ ) snake_case_ : Tuple = _load_model(lowerCAmelCase_ , lowerCAmelCase_ , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) # load bark initial model snake_case_ : int = _bark_load_model(lowerCAmelCase_ , "cpu" , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) if model_type == "text": snake_case_ : Union[str, Any] = bark_model["model"] if model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) != bark_model.get_num_params(): raise ValueError("initial and new models don't have the same number of parameters" ) # check if same output as the bark model snake_case_ : Optional[Any] = 5 snake_case_ : Optional[int] = 1_0 if model_type in ["text", "coarse"]: snake_case_ : Optional[Any] = torch.randint(2_5_6 , (batch_size, sequence_length) , dtype=torch.int ) snake_case_ : str = bark_model(lowerCAmelCase_ )[0] snake_case_ : Tuple = model(lowerCAmelCase_ ) # take last logits snake_case_ : List[str] = output_new_model_total.logits[:, [-1], :] else: snake_case_ : Optional[int] = 3 snake_case_ : str = 8 snake_case_ : List[str] = torch.randint(2_5_6 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) snake_case_ : Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Union[str, Any] = bark_model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("initial and new outputs don't have the same shape" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("initial and new outputs are not equal" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple , lowerCAmelCase_: List[str] , lowerCAmelCase_: Any , lowerCAmelCase_: List[Any] , lowerCAmelCase_: int , lowerCAmelCase_: Optional[Any] , ): snake_case_ : Optional[Any] = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkSemanticConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = BarkCoarseConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[str] = BarkFineConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = EncodecConfig.from_pretrained("facebook/encodec_24khz" ) snake_case_ : List[str] = BarkSemanticModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkCoarseModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Tuple = BarkFineModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_24khz" ) snake_case_ : Tuple = BarkConfig.from_sub_model_configs( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : List[Any] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) snake_case_ : Optional[int] = BarkModel(lowerCAmelCase_ ) snake_case_ : int = semantic snake_case_ : List[str] = coarseAcoustic snake_case_ : str = fineAcoustic snake_case_ : Optional[Any] = codec snake_case_ : Any = bark_generation_config Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) bark.save_pretrained(lowerCAmelCase_ , repo_id=lowerCAmelCase_ , push_to_hub=lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") UpperCAmelCase = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
666
1
from __future__ import annotations import os from collections.abc import Mapping UpperCAmelCase = tuple[int, int] class snake_case__ : def __init__( self : Optional[Any] , A__ : set[int] , A__ : Mapping[EdgeT, int] ) -> None: '''simple docstring''' snake_case_ : set[int] = vertices snake_case_ : dict[EdgeT, int] = { (min(A__ ), max(A__ )): weight for edge, weight in edges.items() } def UpperCAmelCase__ ( self : Dict , A__ : EdgeT , A__ : int ) -> None: '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) snake_case_ : Tuple = weight def UpperCAmelCase__ ( self : List[str] ) -> Graph: '''simple docstring''' snake_case_ : Graph = Graph({min(self.vertices )} , {} ) snake_case_ : EdgeT snake_case_ : int snake_case_ : EdgeT snake_case_ : int while len(subgraph.vertices ) < len(self.vertices ): snake_case_ : str = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: snake_case_ : str = edge snake_case_ : Dict = weight subgraph.add_edge(A__ , A__ ) return subgraph def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str = "p107_network.txt" ): snake_case_ : str = os.path.abspath(os.path.dirname(lowerCAmelCase_ ) ) snake_case_ : str = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : dict[EdgeT, int] = {} snake_case_ : list[str] snake_case_ : int snake_case_ : int with open(lowerCAmelCase_ ) as f: snake_case_ : List[str] = f.read().strip().split("\n" ) snake_case_ : Tuple = [line.split("," ) for line in data] for edgea in range(1 , len(lowerCAmelCase_ ) ): for edgea in range(lowerCAmelCase_ ): if adjaceny_matrix[edgea][edgea] != "-": snake_case_ : Dict = int(adjaceny_matrix[edgea][edgea] ) snake_case_ : Graph = Graph(set(range(len(lowerCAmelCase_ ) ) ) , lowerCAmelCase_ ) snake_case_ : Graph = graph.prims_algorithm() snake_case_ : int = sum(graph.edges.values() ) snake_case_ : int = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
666
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase = { "configuration_upernet": ["UperNetConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "UperNetForSemanticSegmentation", "UperNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
1
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class snake_case__ ( unittest.TestCase ): def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase__ ( self : List[str] ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = 1 snake_case_ : List[Any] = 3 snake_case_ : Union[str, Any] = (32, 32) snake_case_ : List[Any] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(A__ ) return image @property def UpperCAmelCase__ ( self : List[str] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : Any = 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 , ) return model @property def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCAmelCase__ ( self : int ) -> Any: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModel(A__ ) @property def UpperCAmelCase__ ( self : int ) -> Optional[int]: '''simple docstring''' def extract(*A__ : Dict , **A__ : Optional[int] ): class snake_case__ : def __init__( self : List[str] ) -> str: '''simple docstring''' snake_case_ : str = torch.ones([0] ) def UpperCAmelCase__ ( self : Any , A__ : Dict ) -> List[Any]: '''simple docstring''' self.pixel_values.to(A__ ) return self return Out() return extract def UpperCAmelCase__ ( self : Dict ) -> str: '''simple docstring''' snake_case_ : int = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case_ : Dict = self.dummy_cond_unet snake_case_ : int = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=A__ , set_alpha_to_one=A__ , ) snake_case_ : str = self.dummy_vae snake_case_ : Any = self.dummy_text_encoder snake_case_ : str = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk snake_case_ : Optional[Any] = StableDiffusionPipeline( unet=A__ , scheduler=A__ , vae=A__ , text_encoder=A__ , tokenizer=A__ , safety_checker=A__ , feature_extractor=self.dummy_extractor , ) snake_case_ : Optional[Any] = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) snake_case_ : List[str] = "A painting of a squirrel eating a burger" snake_case_ : int = torch.Generator(device=A__ ).manual_seed(0 ) snake_case_ : Tuple = sd_pipe([prompt] , generator=A__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) snake_case_ : Union[str, Any] = output.images snake_case_ : Union[str, Any] = torch.Generator(device=A__ ).manual_seed(0 ) snake_case_ : List[Any] = sd_pipe( [prompt] , generator=A__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=A__ , )[0] snake_case_ : Optional[Any] = image[0, -3:, -3:, -1] snake_case_ : Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ : List[str] = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : List[Any] ) -> str: '''simple docstring''' snake_case_ : int = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case_ : Optional[int] = self.dummy_cond_unet snake_case_ : str = PNDMScheduler(skip_prk_steps=A__ ) snake_case_ : List[Any] = self.dummy_vae snake_case_ : Tuple = self.dummy_text_encoder snake_case_ : List[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk snake_case_ : Union[str, Any] = StableDiffusionPipeline( unet=A__ , scheduler=A__ , vae=A__ , text_encoder=A__ , tokenizer=A__ , safety_checker=A__ , feature_extractor=self.dummy_extractor , ) snake_case_ : Optional[Any] = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) snake_case_ : Union[str, Any] = "A painting of a squirrel eating a burger" snake_case_ : Optional[Any] = torch.Generator(device=A__ ).manual_seed(0 ) snake_case_ : Tuple = sd_pipe([prompt] , generator=A__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) snake_case_ : Optional[Any] = output.images snake_case_ : int = torch.Generator(device=A__ ).manual_seed(0 ) snake_case_ : Optional[Any] = sd_pipe( [prompt] , generator=A__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=A__ , )[0] snake_case_ : Dict = image[0, -3:, -3:, -1] snake_case_ : Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ : Any = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' snake_case_ : Any = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=A__ ) assert isinstance(A__ , A__ ) assert isinstance(pipe.scheduler , A__ ) assert pipe.safety_checker is None snake_case_ : Optional[Any] = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(A__ ) snake_case_ : List[str] = StableDiffusionPipeline.from_pretrained(A__ ) # sanity check that the pipeline still works assert pipe.safety_checker is None snake_case_ : List[str] = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCAmelCase__ ( self : str ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = self.dummy_cond_unet snake_case_ : List[Any] = PNDMScheduler(skip_prk_steps=A__ ) snake_case_ : str = self.dummy_vae snake_case_ : Dict = self.dummy_text_encoder snake_case_ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 snake_case_ : Dict = unet.half() snake_case_ : List[str] = vae.half() snake_case_ : str = bert.half() # make sure here that pndm scheduler skips prk snake_case_ : str = StableDiffusionPipeline( unet=A__ , scheduler=A__ , vae=A__ , text_encoder=A__ , tokenizer=A__ , safety_checker=A__ , feature_extractor=self.dummy_extractor , ) snake_case_ : List[str] = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) snake_case_ : List[str] = "A painting of a squirrel eating a burger" snake_case_ : Optional[Any] = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class snake_case__ ( unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> Tuple: '''simple docstring''' snake_case_ : Dict = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=A__ ) snake_case_ : Tuple = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) snake_case_ : Dict = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) snake_case_ : int = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) snake_case_ : Tuple = 40_03_66_03_46 snake_case_ : Optional[int] = 7 # without safety guidance (sld_guidance_scale = 0) snake_case_ : Optional[Any] = torch.manual_seed(A__ ) snake_case_ : Optional[Any] = sd_pipe( [prompt] , generator=A__ , guidance_scale=A__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) snake_case_ : Optional[int] = output.images snake_case_ : Optional[int] = image[0, -3:, -3:, -1] snake_case_ : Dict = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) snake_case_ : int = torch.manual_seed(A__ ) snake_case_ : Any = sd_pipe( [prompt] , generator=A__ , guidance_scale=A__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) snake_case_ : str = output.images snake_case_ : Optional[int] = image[0, -3:, -3:, -1] snake_case_ : Tuple = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[Any] = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=A__ ) snake_case_ : Optional[Any] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) snake_case_ : Optional[int] = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) snake_case_ : int = "padme amidala taking a bath artwork, safe for work, no nudity" snake_case_ : List[str] = 27_34_97_17_55 snake_case_ : str = 7 snake_case_ : Optional[int] = torch.manual_seed(A__ ) snake_case_ : Dict = sd_pipe( [prompt] , generator=A__ , guidance_scale=A__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) snake_case_ : List[str] = output.images snake_case_ : Optional[int] = image[0, -3:, -3:, -1] snake_case_ : int = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 snake_case_ : Optional[Any] = torch.manual_seed(A__ ) snake_case_ : Union[str, Any] = sd_pipe( [prompt] , generator=A__ , guidance_scale=A__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) snake_case_ : List[Any] = output.images snake_case_ : Dict = image[0, -3:, -3:, -1] snake_case_ : str = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : int ) -> Tuple: '''simple docstring''' snake_case_ : int = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) snake_case_ : Optional[Any] = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) snake_case_ : List[Any] = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) snake_case_ : List[Any] = 10_44_35_52_34 snake_case_ : Tuple = 12 snake_case_ : List[str] = torch.manual_seed(A__ ) snake_case_ : Optional[Any] = sd_pipe( [prompt] , generator=A__ , guidance_scale=A__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) snake_case_ : Optional[int] = output.images snake_case_ : int = image[0, -3:, -3:, -1] snake_case_ : str = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 snake_case_ : Dict = torch.manual_seed(A__ ) snake_case_ : int = sd_pipe( [prompt] , generator=A__ , guidance_scale=A__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) snake_case_ : List[Any] = output.images snake_case_ : Union[str, Any] = image[0, -3:, -3:, -1] snake_case_ : int = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
666
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch UpperCAmelCase = logging.get_logger(__name__) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : str = ["pixel_values"] def __init__( self : List[Any] , A__ : bool = True , A__ : Optional[Dict[str, int]] = None , A__ : PILImageResampling = PILImageResampling.BILINEAR , A__ : bool = True , A__ : Dict[str, int] = None , A__ : bool = True , A__ : Union[int, float] = 1 / 2_55 , A__ : bool = True , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , **A__ : int , ) -> None: '''simple docstring''' super().__init__(**A__ ) snake_case_ : Optional[int] = size if size is not None else {"shortest_edge": 2_56} snake_case_ : Dict = get_size_dict(A__ , default_to_square=A__ ) snake_case_ : List[str] = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} snake_case_ : Any = get_size_dict(A__ , param_name="crop_size" ) snake_case_ : int = do_resize snake_case_ : Optional[Any] = size snake_case_ : Optional[Any] = resample snake_case_ : Optional[int] = do_center_crop snake_case_ : List[Any] = crop_size snake_case_ : List[Any] = do_rescale snake_case_ : Optional[int] = rescale_factor snake_case_ : Optional[Any] = do_normalize snake_case_ : List[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN snake_case_ : Optional[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase__ ( self : List[str] , A__ : np.ndarray , A__ : Dict[str, int] , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : str , ) -> np.ndarray: '''simple docstring''' snake_case_ : Optional[Any] = get_size_dict(A__ , default_to_square=A__ ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) snake_case_ : Any = get_resize_output_image_size(A__ , size=size["shortest_edge"] , default_to_square=A__ ) return resize(A__ , size=A__ , resample=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : int , A__ : np.ndarray , A__ : Dict[str, int] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Union[str, Any] , ) -> np.ndarray: '''simple docstring''' snake_case_ : Tuple = get_size_dict(A__ ) if "height" not in size or "width" not in size: raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}" ) return center_crop(A__ , size=(size["height"], size["width"]) , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : List[str] , A__ : np.ndarray , A__ : float , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Tuple ) -> np.ndarray: '''simple docstring''' return rescale(A__ , scale=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : np.ndarray , A__ : Union[float, List[float]] , A__ : Union[float, List[float]] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Dict , ) -> np.ndarray: '''simple docstring''' return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , A__ : ImageInput , A__ : Optional[bool] = None , A__ : Dict[str, int] = None , A__ : PILImageResampling = None , A__ : bool = None , A__ : Dict[str, int] = None , A__ : Optional[bool] = None , A__ : Optional[float] = None , A__ : Optional[bool] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[str, TensorType]] = None , A__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **A__ : Union[str, Any] , ) -> Optional[int]: '''simple docstring''' snake_case_ : Union[str, Any] = do_resize if do_resize is not None else self.do_resize snake_case_ : Dict = size if size is not None else self.size snake_case_ : Optional[Any] = get_size_dict(A__ , default_to_square=A__ ) snake_case_ : Tuple = resample if resample is not None else self.resample snake_case_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ : str = crop_size if crop_size is not None else self.crop_size snake_case_ : Tuple = get_size_dict(A__ , param_name="crop_size" ) snake_case_ : Dict = do_rescale if do_rescale is not None else self.do_rescale snake_case_ : str = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ : Any = do_normalize if do_normalize is not None else self.do_normalize snake_case_ : Any = image_mean if image_mean is not None else self.image_mean snake_case_ : List[str] = image_std if image_std is not None else self.image_std snake_case_ : Dict = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. snake_case_ : Tuple = [to_numpy_array(A__ ) for image in images] if do_resize: snake_case_ : Any = [self.resize(image=A__ , size=A__ , resample=A__ ) for image in images] if do_center_crop: snake_case_ : List[str] = [self.center_crop(image=A__ , size=A__ ) for image in images] if do_rescale: snake_case_ : Any = [self.rescale(image=A__ , scale=A__ ) for image in images] if do_normalize: snake_case_ : Union[str, Any] = [self.normalize(image=A__ , mean=A__ , std=A__ ) for image in images] snake_case_ : Optional[Any] = [to_channel_dimension_format(A__ , A__ ) for image in images] snake_case_ : Any = {"pixel_values": images} return BatchFeature(data=A__ , tensor_type=A__ ) def UpperCAmelCase__ ( self : List[str] , A__ : Dict , A__ : List[Tuple] = None ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A__ ) != len(A__ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(A__ ): snake_case_ : Dict = target_sizes.numpy() snake_case_ : int = [] for idx in range(len(A__ ) ): snake_case_ : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=A__ ) snake_case_ : int = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A__ ) else: snake_case_ : List[Any] = logits.argmax(dim=1 ) snake_case_ : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
666
1
import warnings warnings.warn( "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: " "`from accelerate import find_executable_batch_size` to avoid this warning.", FutureWarning, )
666
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
1
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: UpperCAmelCase = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self : Dict , A__ : Optional[int] , A__ : List[Any]=7 , A__ : List[str]=3 , A__ : Union[str, Any]=18 , A__ : Union[str, Any]=30 , A__ : str=4_00 , A__ : Tuple=None , A__ : Union[str, Any]=True , A__ : Union[str, Any]=True , A__ : str=None , ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = size if size is not None else {"height": 20, "width": 20} snake_case_ : Optional[int] = parent snake_case_ : List[Any] = batch_size snake_case_ : int = num_channels snake_case_ : Any = image_size snake_case_ : Dict = min_resolution snake_case_ : Optional[Any] = max_resolution snake_case_ : Optional[int] = size snake_case_ : str = do_normalize snake_case_ : List[Any] = do_convert_rgb snake_case_ : Optional[Any] = [5_12, 10_24, 20_48, 40_96] snake_case_ : str = patch_size if patch_size is not None else {"height": 16, "width": 16} def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def UpperCAmelCase__ ( self : str ) -> Dict: '''simple docstring''' snake_case_ : Dict = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" snake_case_ : List[str] = Image.open(requests.get(A__ , stream=A__ ).raw ).convert("RGB" ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`." , ) @require_torch @require_vision class snake_case__ ( _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[Any] = PixaStructImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' snake_case_ : List[Any] = PixaStructImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , "do_normalize" ) ) self.assertTrue(hasattr(A__ , "do_convert_rgb" ) ) def UpperCAmelCase__ ( self : int ) -> List[str]: '''simple docstring''' snake_case_ : List[Any] = self.image_processor_tester.prepare_dummy_image() snake_case_ : Tuple = self.image_processing_class(**self.image_processor_dict ) snake_case_ : Optional[Any] = 20_48 snake_case_ : Optional[int] = image_processor(A__ , return_tensors="pt" , max_patches=A__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1E-3 , rtol=1E-3 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> str: '''simple docstring''' snake_case_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : str = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case_ : Optional[Any] = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case_ : int = image_processor( A__ , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : Dict = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 snake_case_ : str = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(A__ ): snake_case_ : str = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=A__ ).flattened_patches snake_case_ : Tuple = "Hello" snake_case_ : Tuple = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=A__ , header_text=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case_ : Dict = image_processor( A__ , return_tensors="pt" , max_patches=A__ , header_text=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def UpperCAmelCase__ ( self : int ) -> Tuple: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , numpify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , np.ndarray ) snake_case_ : str = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case_ : Tuple = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case_ : Optional[int] = image_processor( A__ , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' snake_case_ : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , torchify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , torch.Tensor ) # Test not batched input snake_case_ : Optional[Any] = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case_ : List[Any] = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case_ : Optional[int] = image_processor( A__ , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`." , ) @require_torch @require_vision class snake_case__ ( _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Any = PixaStructImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' snake_case_ : Dict = PixaStructImageProcessingTester(self , num_channels=4 ) snake_case_ : List[str] = 3 @property def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , "do_normalize" ) ) self.assertTrue(hasattr(A__ , "do_convert_rgb" ) ) def UpperCAmelCase__ ( self : Tuple ) -> Any: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : Optional[Any] = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case_ : Optional[int] = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case_ : Any = image_processor( A__ , return_tensors="pt" , max_patches=A__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
666
from ...configuration_utils import PretrainedConfig UpperCAmelCase = { "google/tapas-base-finetuned-sqa": ( "https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json" ), "google/tapas-base-finetuned-wtq": ( "https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json" ), "google/tapas-base-finetuned-wikisql-supervised": ( "https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json" ), "google/tapas-base-finetuned-tabfact": ( "https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json" ), } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "tapas" def __init__( self : List[Any] , A__ : str=3_05_22 , A__ : Tuple=7_68 , A__ : List[Any]=12 , A__ : Optional[Any]=12 , A__ : Union[str, Any]=30_72 , A__ : Dict="gelu" , A__ : List[Any]=0.1 , A__ : str=0.1 , A__ : List[Any]=10_24 , A__ : Optional[int]=[3, 2_56, 2_56, 2, 2_56, 2_56, 10] , A__ : Union[str, Any]=0.02 , A__ : Tuple=1E-12 , A__ : Tuple=0 , A__ : Any=10.0 , A__ : List[str]=0 , A__ : List[str]=1.0 , A__ : Optional[Any]=None , A__ : Tuple=1.0 , A__ : Union[str, Any]=False , A__ : Any=None , A__ : Union[str, Any]=1.0 , A__ : int=1.0 , A__ : str=False , A__ : int=False , A__ : Optional[Any]="ratio" , A__ : str=None , A__ : int=None , A__ : Dict=64 , A__ : int=32 , A__ : Optional[Any]=False , A__ : List[str]=True , A__ : List[Any]=False , A__ : str=False , A__ : Any=True , A__ : Tuple=False , A__ : str=None , A__ : str=None , **A__ : List[str] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=A__ , **A__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) snake_case_ : int = vocab_size snake_case_ : int = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Optional[int] = hidden_act snake_case_ : Optional[int] = intermediate_size snake_case_ : str = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : Any = max_position_embeddings snake_case_ : List[Any] = type_vocab_sizes snake_case_ : str = initializer_range snake_case_ : Optional[Any] = layer_norm_eps # Fine-tuning task hyperparameters snake_case_ : Optional[int] = positive_label_weight snake_case_ : Dict = num_aggregation_labels snake_case_ : List[str] = aggregation_loss_weight snake_case_ : str = use_answer_as_supervision snake_case_ : int = answer_loss_importance snake_case_ : Any = use_normalized_answer_loss snake_case_ : int = huber_loss_delta snake_case_ : List[Any] = temperature snake_case_ : str = aggregation_temperature snake_case_ : List[str] = use_gumbel_for_cells snake_case_ : List[str] = use_gumbel_for_aggregation snake_case_ : Dict = average_approximation_function snake_case_ : List[str] = cell_selection_preference snake_case_ : Dict = answer_loss_cutoff snake_case_ : List[str] = max_num_rows snake_case_ : Union[str, Any] = max_num_columns snake_case_ : str = average_logits_per_cell snake_case_ : Union[str, Any] = select_one_column snake_case_ : Dict = allow_empty_column_selection snake_case_ : List[Any] = init_cell_selection_weights_to_zero snake_case_ : str = reset_position_index_per_cell snake_case_ : List[Any] = disable_per_token_loss # Aggregation hyperparameters snake_case_ : List[str] = aggregation_labels snake_case_ : Union[str, Any] = no_aggregation_label_index if isinstance(self.aggregation_labels , A__ ): snake_case_ : Optional[int] = {int(A__ ): v for k, v in aggregation_labels.items()}
666
1
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] ): snake_case_ : str = len(lowerCAmelCase_ ) // 2 # choose the middle 3 elements snake_case_ : int = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
666
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class snake_case__ ( datasets.BeamBasedBuilder ): def UpperCAmelCase__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"content": datasets.Value("string" )} ) , supervised_keys=A__ , ) def UpperCAmelCase__ ( self : Optional[Any] , A__ : str , A__ : str ) -> Optional[int]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_dummy_examples()} )] def UpperCAmelCase__ ( self : int , A__ : Optional[int] , A__ : Dict ) -> Optional[Any]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) class snake_case__ ( datasets.BeamBasedBuilder ): def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) , supervised_keys=A__ , ) def UpperCAmelCase__ ( self : Any , A__ : List[str] , A__ : str ) -> Optional[int]: '''simple docstring''' return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_nested_examples()} ) ] def UpperCAmelCase__ ( self : List[Any] , A__ : List[str] , A__ : Optional[int] ) -> List[str]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) def SCREAMING_SNAKE_CASE_ ( ): return [(i, {"content": content}) for i, content in enumerate(["foo", "bar", "foobar"] )] def SCREAMING_SNAKE_CASE_ ( ): return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["foo", "bar", "foobar"] )] class snake_case__ ( _UpperCamelCase ): @require_beam def UpperCAmelCase__ ( self : str ) -> List[str]: '''simple docstring''' snake_case_ : Union[str, Any] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : Dict = DummyBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) snake_case_ : Optional[int] = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) self.assertDictEqual(dset["train"][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def UpperCAmelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' import apache_beam as beam snake_case_ : Tuple = beam.io.parquetio.WriteToParquet snake_case_ : Union[str, Any] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : List[Any] = DummyBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) with patch("apache_beam.io.parquetio.WriteToParquet" ) as write_parquet_mock: snake_case_ : int = partial(A__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) snake_case_ : Optional[Any] = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["train"]["content"] ) , sorted(["foo", "bar", "foobar"] ) ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : Tuple = DummyBeamDataset(cache_dir=A__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : List[str] = NestedBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) ) snake_case_ : int = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) self.assertDictEqual(dset["train"][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset
666
1
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class snake_case__ ( unittest.TestCase ): def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' snake_case_ : Tuple = 0 @slow def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): snake_case_ : Dict = AutoTokenizer.from_pretrained(A__ ) self.assertIsNotNone(A__ ) self.assertIsInstance(A__ , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(A__ ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): snake_case_ : Optional[Any] = AutoTokenizer.from_pretrained(A__ ) self.assertIsNotNone(A__ ) self.assertIsInstance(A__ , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(A__ ) , 0 ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' snake_case_ : str = AutoTokenizer.from_pretrained(A__ ) self.assertIsInstance(A__ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = AutoTokenizer.from_pretrained(A__ ) self.assertIsInstance(A__ , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def UpperCAmelCase__ ( self : Tuple ) -> Any: '''simple docstring''' snake_case_ : List[Any] = AutoConfig.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) # Check that tokenizer_type ≠ model_type snake_case_ : str = AutoTokenizer.from_pretrained(A__ , config=A__ ) self.assertIsInstance(A__ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.txt" , os.path.join(A__ , "vocab.txt" ) ) snake_case_ : Union[str, Any] = AutoTokenizer.from_pretrained(A__ , tokenizer_type="bert" , use_fast=A__ ) self.assertIsInstance(A__ , A__ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.json" , os.path.join(A__ , "vocab.json" ) ) shutil.copy("./tests/fixtures/merges.txt" , os.path.join(A__ , "merges.txt" ) ) snake_case_ : Any = AutoTokenizer.from_pretrained(A__ , tokenizer_type="gpt2" , use_fast=A__ ) self.assertIsInstance(A__ , A__ ) @require_tokenizers def UpperCAmelCase__ ( self : Optional[int] ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.txt" , os.path.join(A__ , "vocab.txt" ) ) snake_case_ : Any = AutoTokenizer.from_pretrained(A__ , tokenizer_type="bert" ) self.assertIsInstance(A__ , A__ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.json" , os.path.join(A__ , "vocab.json" ) ) shutil.copy("./tests/fixtures/merges.txt" , os.path.join(A__ , "merges.txt" ) ) snake_case_ : Optional[int] = AutoTokenizer.from_pretrained(A__ , tokenizer_type="gpt2" ) self.assertIsInstance(A__ , A__ ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: '''simple docstring''' with pytest.raises(A__ ): AutoTokenizer.from_pretrained("./" , tokenizer_type="xxx" ) @require_tokenizers def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: snake_case_ : Optional[Any] = tokenizer_class.from_pretrained("wietsedv/bert-base-dutch-cased" ) self.assertIsInstance(A__ , (BertTokenizer, BertTokenizerFast) ) if isinstance(A__ , A__ ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , A__ ) else: self.assertEqual(tokenizer.do_lower_case , A__ ) self.assertEqual(tokenizer.model_max_length , 5_12 ) @require_tokenizers def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( A__ , "julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier" , ): snake_case_ : str = tokenizer_class.from_pretrained("julien-c/herlolip-not-exists" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' snake_case_ : int = TOKENIZER_MAPPING.values() snake_case_ : Any = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(A__ ) @require_tokenizers def UpperCAmelCase__ ( self : Optional[int] ) -> int: '''simple docstring''' self.assertIsInstance(AutoTokenizer.from_pretrained("bert-base-cased" , use_fast=A__ ) , A__ ) self.assertIsInstance(AutoTokenizer.from_pretrained("bert-base-cased" ) , A__ ) @require_tokenizers def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' snake_case_ : Tuple = AutoTokenizer.from_pretrained("distilbert-base-uncased" , do_lower_case=A__ ) snake_case_ : List[str] = "Hello, world. How are you?" snake_case_ : Optional[int] = tokenizer.tokenize(A__ ) self.assertEqual("[UNK]" , tokens[0] ) snake_case_ : List[str] = AutoTokenizer.from_pretrained("microsoft/mpnet-base" , do_lower_case=A__ ) snake_case_ : str = tokenizer.tokenize(A__ ) self.assertEqual("[UNK]" , tokens[0] ) @require_tokenizers def UpperCAmelCase__ ( self : List[Any] ) -> Dict: '''simple docstring''' snake_case_ : Any = AutoTokenizer.from_pretrained("robot-test/dummy-tokenizer-fast-with-model-config" ) self.assertEqual(type(A__ ) , A__ ) self.assertEqual(tokenizer.model_max_length , 5_12 ) self.assertEqual(tokenizer.vocab_size , 3_00_00 ) self.assertEqual(tokenizer.unk_token , "[UNK]" ) self.assertEqual(tokenizer.padding_side , "right" ) self.assertEqual(tokenizer.truncation_side , "right" ) def UpperCAmelCase__ ( self : str ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = AutoTokenizer.from_pretrained(A__ ) self.assertIsInstance(A__ , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A__ ) snake_case_ : Union[str, Any] = AutoTokenizer.from_pretrained(A__ ) self.assertIsInstance(A__ , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def UpperCAmelCase__ ( self : Any ) -> Tuple: '''simple docstring''' snake_case_ : int = AutoTokenizer.from_pretrained("ctrl" ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(A__ , A__ ) def UpperCAmelCase__ ( self : Dict ) -> str: '''simple docstring''' snake_case_ : Any = get_tokenizer_config("bert-base-cased" ) snake_case_ : Dict = config.pop("_commit_hash" , A__ ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(A__ , {"do_lower_case": False} ) # This model does not have a tokenizer_config so we get back an empty dict. snake_case_ : Optional[int] = get_tokenizer_config(A__ ) self.assertDictEqual(A__ , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. snake_case_ : Any = AutoTokenizer.from_pretrained(A__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A__ ) snake_case_ : Tuple = get_tokenizer_config(A__ ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config["tokenizer_class"] , "BertTokenizer" ) def UpperCAmelCase__ ( self : Any ) -> Any: '''simple docstring''' try: AutoConfig.register("custom" , A__ ) AutoTokenizer.register(A__ , slow_tokenizer_class=A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoTokenizer.register(A__ , slow_tokenizer_class=A__ ) snake_case_ : Union[str, Any] = CustomTokenizer.from_pretrained(A__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A__ ) snake_case_ : Tuple = AutoTokenizer.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def UpperCAmelCase__ ( self : str ) -> int: '''simple docstring''' try: AutoConfig.register("custom" , A__ ) # Can register in two steps AutoTokenizer.register(A__ , slow_tokenizer_class=A__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(A__ , fast_tokenizer_class=A__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( A__ , slow_tokenizer_class=A__ , fast_tokenizer_class=A__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoTokenizer.register(A__ , fast_tokenizer_class=A__ ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ : int = BertTokenizerFast.from_pretrained(A__ ) bert_tokenizer.save_pretrained(A__ ) snake_case_ : Dict = CustomTokenizerFast.from_pretrained(A__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A__ ) snake_case_ : Tuple = AutoTokenizer.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) snake_case_ : str = AutoTokenizer.from_pretrained(A__ , use_fast=A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCAmelCase__ ( self : int ) -> Dict: '''simple docstring''' with self.assertRaises(A__ ): snake_case_ : str = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): snake_case_ : List[str] = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer" , trust_remote_code=A__ ) snake_case_ : str = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" , trust_remote_code=A__ ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A__ ) snake_case_ : Union[str, Any] = AutoTokenizer.from_pretrained(A__ , trust_remote_code=A__ ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , "NewTokenizerFast" ) # Test we can also load the slow version snake_case_ : Any = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer" , trust_remote_code=A__ , use_fast=A__ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A__ ) snake_case_ : Optional[int] = AutoTokenizer.from_pretrained(A__ , trust_remote_code=A__ , use_fast=A__ ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , "NewTokenizer" ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , "NewTokenizer" ) @require_tokenizers def UpperCAmelCase__ ( self : List[str] ) -> str: '''simple docstring''' class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = False class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Any = NewTokenizer _SCREAMING_SNAKE_CASE : Tuple = False try: AutoConfig.register("custom" , A__ ) AutoTokenizer.register(A__ , slow_tokenizer_class=A__ ) AutoTokenizer.register(A__ , fast_tokenizer_class=A__ ) # If remote code is not set, the default is to use local snake_case_ : Optional[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" ) self.assertFalse(tokenizer.special_attribute_present ) snake_case_ : Any = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" , use_fast=A__ ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. snake_case_ : int = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer" , trust_remote_code=A__ ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" ) self.assertFalse(tokenizer.special_attribute_present ) snake_case_ : str = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer" , trust_remote_code=A__ , use_fast=A__ ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub snake_case_ : Optional[Any] = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer" , trust_remote_code=A__ ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" ) self.assertTrue(tokenizer.special_attribute_present ) snake_case_ : Union[str, Any] = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer" , trust_remote_code=A__ , use_fast=A__ ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCAmelCase__ ( self : Any ) -> List[Any]: '''simple docstring''' snake_case_ : str = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer_legacy" , trust_remote_code=A__ ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" ) # Test we can also load the slow version snake_case_ : List[Any] = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer_legacy" , trust_remote_code=A__ , use_fast=A__ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) else: self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) def UpperCAmelCase__ ( self : int ) -> str: '''simple docstring''' with self.assertRaisesRegex( A__ , "bert-base is not a local folder and is not a valid model identifier" ): snake_case_ : List[str] = AutoTokenizer.from_pretrained("bert-base" ) def UpperCAmelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' with self.assertRaisesRegex( A__ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): snake_case_ : str = AutoTokenizer.from_pretrained(A__ , revision="aaaaaa" ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) with RequestCounter() as counter: snake_case_ : str = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
666
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple ): class snake_case__ : def __init__( self : Any , A__ : List[str] ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = metric_id class snake_case__ : _SCREAMING_SNAKE_CASE : List[str] = [MetricMock(_UpperCamelCase ) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: '''simple docstring''' return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple , lowerCAmelCase_: int , lowerCAmelCase_: List[Any] , lowerCAmelCase_: Any , lowerCAmelCase_: List[str] ): if "tmp_path" in args: snake_case_ : List[Any] = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase_ , match="https://huggingface.co/docs/evaluate" ): func(*lowerCAmelCase_ )
666
1
from random import shuffle import tensorflow as tf from numpy import array def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Dict , lowerCAmelCase_: Dict ): snake_case_ : int = int(lowerCAmelCase_ ) assert noofclusters < len(lowerCAmelCase_ ) # Find out the dimensionality snake_case_ : Union[str, Any] = len(vectors[0] ) # Will help select random centroids from among the available vectors snake_case_ : Optional[int] = list(range(len(lowerCAmelCase_ ) ) ) shuffle(lowerCAmelCase_ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. snake_case_ : Optional[Any] = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION snake_case_ : Tuple = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points snake_case_ : Union[str, Any] = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(lowerCAmelCase_ ) ] ##These nodes will assign the centroid Variables the appropriate ##values snake_case_ : Optional[Any] = tf.placeholder("float64" , [dim] ) snake_case_ : Union[str, Any] = [] for centroid in centroids: cent_assigns.append(tf.assign(lowerCAmelCase_ , lowerCAmelCase_ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) snake_case_ : Optional[Any] = [tf.Variable(0 ) for i in range(len(lowerCAmelCase_ ) )] ##These nodes will assign an assignment Variable the appropriate ##value snake_case_ : Tuple = tf.placeholder("int32" ) snake_case_ : Optional[int] = [] for assignment in assignments: cluster_assigns.append(tf.assign(lowerCAmelCase_ , lowerCAmelCase_ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input snake_case_ : Union[str, Any] = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors snake_case_ : str = tf.reduce_mean(lowerCAmelCase_ , 0 ) ##Node for computing Euclidean distances # Placeholders for input snake_case_ : Union[str, Any] = tf.placeholder("float" , [dim] ) snake_case_ : Dict = tf.placeholder("float" , [dim] ) snake_case_ : Any = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowerCAmelCase_ , lowerCAmelCase_ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input snake_case_ : Tuple = tf.placeholder("float" , [noofclusters] ) snake_case_ : str = tf.argmin(lowerCAmelCase_ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. snake_case_ : str = tf.initialize_all_variables() # Initialize all variables sess.run(lowerCAmelCase_ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. snake_case_ : int = 1_0_0 for _ in range(lowerCAmelCase_ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(lowerCAmelCase_ ) ): snake_case_ : int = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. snake_case_ : int = [ sess.run(lowerCAmelCase_ , feed_dict={va: vect, va: sess.run(lowerCAmelCase_ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input snake_case_ : List[str] = sess.run( lowerCAmelCase_ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(lowerCAmelCase_ ): # Collect all the vectors assigned to this cluster snake_case_ : Union[str, Any] = [ vectors[i] for i in range(len(lowerCAmelCase_ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location snake_case_ : Optional[int] = sess.run( lowerCAmelCase_ , feed_dict={mean_input: array(lowerCAmelCase_ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments snake_case_ : Dict = sess.run(lowerCAmelCase_ ) snake_case_ : Optional[Any] = sess.run(lowerCAmelCase_ ) return centroids, assignments
666
from __future__ import annotations import bisect def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): if hi < 0: snake_case_ : Any = len(lowerCAmelCase_ ) while lo < hi: snake_case_ : List[Any] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: snake_case_ : Tuple = mid + 1 else: snake_case_ : Dict = mid return lo def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): if hi < 0: snake_case_ : Optional[Any] = len(lowerCAmelCase_ ) while lo < hi: snake_case_ : Union[str, Any] = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: snake_case_ : Optional[Any] = mid + 1 else: snake_case_ : Tuple = mid return lo def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): sorted_collection.insert(bisect_left(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): sorted_collection.insert(bisect_right(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int ): snake_case_ : Dict = 0 snake_case_ : Tuple = len(lowerCAmelCase_ ) - 1 while left <= right: snake_case_ : int = left + (right - left) // 2 snake_case_ : Optional[Any] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: snake_case_ : Optional[Any] = midpoint - 1 else: snake_case_ : Optional[int] = midpoint + 1 return None def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int ): snake_case_ : Optional[int] = bisect.bisect_left(lowerCAmelCase_ , lowerCAmelCase_ ) if index != len(lowerCAmelCase_ ) and sorted_collection[index] == item: return index return None def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int , lowerCAmelCase_: int ): if right < left: return None snake_case_ : List[Any] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , midpoint - 1 ) else: return binary_search_by_recursion(lowerCAmelCase_ , lowerCAmelCase_ , midpoint + 1 , lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = input("Enter numbers separated by comma:\n").strip() UpperCAmelCase = sorted(int(item) for item in user_input.split(",")) UpperCAmelCase = int(input("Enter a single number to be found in the list:\n")) UpperCAmelCase = binary_search(collection, target) if result is None: print(F"{target} was not found in {collection}.") else: print(F"{target} was found at position {result} in {collection}.")
666
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "openai/imagegpt-small": "", "openai/imagegpt-medium": "", "openai/imagegpt-large": "", } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : int = "imagegpt" _SCREAMING_SNAKE_CASE : int = ["past_key_values"] _SCREAMING_SNAKE_CASE : Optional[int] = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[Any] , A__ : Any=5_12 + 1 , A__ : Optional[int]=32 * 32 , A__ : Optional[Any]=5_12 , A__ : Dict=24 , A__ : Optional[int]=8 , A__ : Optional[int]=None , A__ : Optional[int]="quick_gelu" , A__ : Any=0.1 , A__ : Union[str, Any]=0.1 , A__ : Dict=0.1 , A__ : List[str]=1E-5 , A__ : int=0.02 , A__ : List[str]=True , A__ : Optional[Any]=True , A__ : Dict=False , A__ : List[str]=False , A__ : str=False , **A__ : Union[str, Any] , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = vocab_size snake_case_ : Tuple = n_positions snake_case_ : Tuple = n_embd snake_case_ : str = n_layer snake_case_ : Optional[Any] = n_head snake_case_ : Any = n_inner snake_case_ : Dict = activation_function snake_case_ : List[Any] = resid_pdrop snake_case_ : Optional[Any] = embd_pdrop snake_case_ : int = attn_pdrop snake_case_ : List[str] = layer_norm_epsilon snake_case_ : List[str] = initializer_range snake_case_ : Union[str, Any] = scale_attn_weights snake_case_ : str = use_cache snake_case_ : str = scale_attn_by_inverse_layer_idx snake_case_ : Dict = reorder_and_upcast_attn snake_case_ : List[Any] = tie_word_embeddings super().__init__(tie_word_embeddings=A__ , **A__ ) class snake_case__ ( _UpperCamelCase ): @property def UpperCAmelCase__ ( self : int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ] ) def UpperCAmelCase__ ( self : int , A__ : "FeatureExtractionMixin" , A__ : int = 1 , A__ : int = -1 , A__ : bool = False , A__ : Optional["TensorType"] = None , A__ : int = 3 , A__ : int = 32 , A__ : int = 32 , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : Dict = self._generate_dummy_images(A__ , A__ , A__ , A__ ) snake_case_ : Optional[int] = dict(preprocessor(images=A__ , return_tensors=A__ ) ) return inputs
666
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( _UpperCamelCase ): def __init__( self : Union[str, Any] , A__ : VQModel , A__ : UNetaDModel , A__ : DDIMScheduler ) -> List[Any]: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : str , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : float = 0.0 , A__ : int = 50 , A__ : Optional[str] = "pil" , A__ : bool = True , **A__ : Optional[Any] , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' snake_case_ : Optional[int] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=A__ , ) snake_case_ : List[Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ : Any = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(A__ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature snake_case_ : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ : List[Any] = {} if accepts_eta: snake_case_ : int = eta for t in self.progress_bar(self.scheduler.timesteps ): snake_case_ : Union[str, Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual snake_case_ : Dict = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case_ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VAE snake_case_ : int = self.vqvae.decode(A__ ).sample snake_case_ : Dict = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ : Optional[int] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
666
1
from sklearn.metrics import fa_score import datasets UpperCAmelCase = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" UpperCAmelCase = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" UpperCAmelCase = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def UpperCAmelCase__ ( self : Optional[int] , A__ : Any , A__ : str , A__ : int=None , A__ : Optional[int]=1 , A__ : Any="binary" , A__ : int=None ) -> Any: '''simple docstring''' snake_case_ : Any = fa_score( A__ , A__ , labels=A__ , pos_label=A__ , average=A__ , sample_weight=A__ ) return {"f1": float(A__ ) if score.size == 1 else score}
666
from decimal import Decimal, getcontext from math import ceil, factorial def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) snake_case_ : List[str] = precision snake_case_ : Union[str, Any] = ceil(precision / 1_4 ) snake_case_ : List[str] = 4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt() snake_case_ : str = 1 snake_case_ : List[str] = 1_3_5_9_1_4_0_9 snake_case_ : str = Decimal(lowerCAmelCase_ ) for k in range(1 , lowerCAmelCase_ ): snake_case_ : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(lowerCAmelCase_ ) ** 3) linear_term += 5_4_5_1_4_0_1_3_4 exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": UpperCAmelCase = 5_0 print(F"The first {n} digits of pi is: {pi(n)}")
666
1
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: NDArray[floataa] , lowerCAmelCase_: NDArray[floataa] , lowerCAmelCase_: list[int] , lowerCAmelCase_: int , ): snake_case_ ,snake_case_ : Optional[int] = coefficient_matrix.shape snake_case_ ,snake_case_ : str = constant_matrix.shape if rowsa != colsa: snake_case_ : Dict = f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(lowerCAmelCase_ ) if colsa != 1: snake_case_ : Union[str, Any] = f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(lowerCAmelCase_ ) if rowsa != rowsa: snake_case_ : str = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) != rowsa: snake_case_ : List[str] = ( "Number of initial values must be equal to number of rows in coefficient " f"matrix but received {len(lowerCAmelCase_ )} and {rowsa}" ) raise ValueError(lowerCAmelCase_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) snake_case_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) snake_case_ ,snake_case_ : List[Any] = table.shape strictly_diagonally_dominant(lowerCAmelCase_ ) # Iterates the whole matrix for given number of times for _ in range(lowerCAmelCase_ ): snake_case_ : str = [] for row in range(lowerCAmelCase_ ): snake_case_ : Optional[Any] = 0 for col in range(lowerCAmelCase_ ): if col == row: snake_case_ : str = table[row][col] elif col == cols - 1: snake_case_ : List[str] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] snake_case_ : Any = (temp + val) / denom new_val.append(lowerCAmelCase_ ) snake_case_ : int = new_val return [float(lowerCAmelCase_ ) for i in new_val] def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: NDArray[floataa] ): snake_case_ ,snake_case_ : List[Any] = table.shape snake_case_ : int = True for i in range(0 , lowerCAmelCase_ ): snake_case_ : List[str] = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
666
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int = 1_0_0_0 ): snake_case_ ,snake_case_ : List[str] = 1, 1 snake_case_ : List[str] = 2 while True: snake_case_ : Tuple = 0 snake_case_ : Union[str, Any] = fa + fa snake_case_ ,snake_case_ : str = fa, f index += 1 for _ in str(lowerCAmelCase_ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
666
1
import requests from bsa import BeautifulSoup def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: dict ): snake_case_ : List[Any] = BeautifulSoup(requests.get(lowerCAmelCase_ , params=lowerCAmelCase_ ).content , "html.parser" ) snake_case_ : List[Any] = soup.find("div" , attrs={"class": "gs_ri"} ) snake_case_ : Optional[Any] = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": UpperCAmelCase = { "title": ( "Precisely geometry controlled microsupercapacitors for ultrahigh areal " "capacitance, volumetric capacitance, and energy density" ), "journal": "Chem. Mater.", "volume": 3_0, "pages": "3979-3990", "year": 2_0_1_8, "hl": "en", } print(get_citation("https://scholar.google.com/scholar_lookup", params=params))
666
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int | float] , lowerCAmelCase_: int , lowerCAmelCase_: int ): if len(lowerCAmelCase_ ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(lowerCAmelCase_ ) or left < -len(lowerCAmelCase_ ) or right >= len(lowerCAmelCase_ ) or right < -len(lowerCAmelCase_ ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] snake_case_ : List[Any] = (left + right) >> 1 # the middle snake_case_ : Dict = find_max(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # find max in range[left, mid] snake_case_ : int = find_max(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
666
1
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: dict ): snake_case_ : set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack snake_case_ : set[int] = set() return any( node not in visited and depth_first_search(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for node in graph ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: dict , lowerCAmelCase_: int , lowerCAmelCase_: set , lowerCAmelCase_: set ): visited.add(lowerCAmelCase_ ) rec_stk.add(lowerCAmelCase_ ) for node in graph[vertex]: if node not in visited: if depth_first_search(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(lowerCAmelCase_ ) return False if __name__ == "__main__": from doctest import testmod testmod()
666
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase = { "vocab_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/vocab.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/vocab.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/vocab.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json" ), }, "merges_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/merges.txt", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/merges.txt", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/merges.txt", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt" ), }, "tokenizer_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/tokenizer.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/tokenizer.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json", "roberta-base-openai-detector": ( "https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json" ), "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json" ), }, } UpperCAmelCase = { "roberta-base": 5_1_2, "roberta-large": 5_1_2, "roberta-large-mnli": 5_1_2, "distilroberta-base": 5_1_2, "roberta-base-openai-detector": 5_1_2, "roberta-large-openai-detector": 5_1_2, } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : int = ["input_ids", "attention_mask"] _SCREAMING_SNAKE_CASE : List[str] = RobertaTokenizer def __init__( self : Optional[int] , A__ : List[Any]=None , A__ : Optional[int]=None , A__ : List[str]=None , A__ : Dict="replace" , A__ : List[str]="<s>" , A__ : Optional[Any]="</s>" , A__ : List[str]="</s>" , A__ : List[Any]="<s>" , A__ : int="<unk>" , A__ : int="<pad>" , A__ : List[Any]="<mask>" , A__ : Any=False , A__ : Optional[int]=True , **A__ : Union[str, Any] , ) -> int: '''simple docstring''' super().__init__( A__ , A__ , tokenizer_file=A__ , errors=A__ , bos_token=A__ , eos_token=A__ , sep_token=A__ , cls_token=A__ , unk_token=A__ , pad_token=A__ , mask_token=A__ , add_prefix_space=A__ , trim_offsets=A__ , **A__ , ) snake_case_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , A__ ) != add_prefix_space: snake_case_ : List[Any] = getattr(A__ , pre_tok_state.pop("type" ) ) snake_case_ : Any = add_prefix_space snake_case_ : List[Any] = pre_tok_class(**A__ ) snake_case_ : Optional[int] = add_prefix_space snake_case_ : List[str] = "post_processor" snake_case_ : Tuple = getattr(self.backend_tokenizer , A__ , A__ ) if tokenizer_component_instance: snake_case_ : List[str] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: snake_case_ : str = tuple(state["sep"] ) if "cls" in state: snake_case_ : Tuple = tuple(state["cls"] ) snake_case_ : Tuple = False if state.get("add_prefix_space" , A__ ) != add_prefix_space: snake_case_ : Optional[Any] = add_prefix_space snake_case_ : str = True if state.get("trim_offsets" , A__ ) != trim_offsets: snake_case_ : Optional[int] = trim_offsets snake_case_ : List[Any] = True if changes_to_apply: snake_case_ : int = getattr(A__ , state.pop("type" ) ) snake_case_ : List[Any] = component_class(**A__ ) setattr(self.backend_tokenizer , A__ , A__ ) @property def UpperCAmelCase__ ( self : Optional[Any] ) -> str: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def UpperCAmelCase__ ( self : Tuple , A__ : Dict ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else value snake_case_ : Any = value def UpperCAmelCase__ ( self : int , *A__ : Optional[Any] , **A__ : int ) -> BatchEncoding: '''simple docstring''' snake_case_ : Optional[Any] = kwargs.get("is_split_into_words" , A__ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*A__ , **A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , *A__ : Any , **A__ : List[Any] ) -> BatchEncoding: '''simple docstring''' snake_case_ : Optional[int] = kwargs.get("is_split_into_words" , A__ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' snake_case_ : Optional[Any] = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ ) def UpperCAmelCase__ ( self : int , A__ : List[str] , A__ : Union[str, Any]=None ) -> Any: '''simple docstring''' snake_case_ : List[str] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCAmelCase__ ( self : Dict , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' snake_case_ : str = [self.sep_token_id] snake_case_ : 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 + sep + token_ids_a + sep ) * [0]
666
1
import random class snake_case__ : @staticmethod def UpperCAmelCase__ ( A__ : str ) -> tuple[list[int], list[int]]: '''simple docstring''' snake_case_ : Optional[Any] = [ord(A__ ) for i in text] snake_case_ : Any = [] snake_case_ : List[Any] = [] for i in plain: snake_case_ : Optional[int] = random.randint(1 , 3_00 ) snake_case_ : Dict = (i + k) * k cipher.append(A__ ) key.append(A__ ) return cipher, key @staticmethod def UpperCAmelCase__ ( A__ : list[int] , A__ : list[int] ) -> str: '''simple docstring''' snake_case_ : List[Any] = [] for i in range(len(A__ ) ): snake_case_ : List[Any] = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(A__ ) ) return "".join(A__ ) if __name__ == "__main__": UpperCAmelCase , UpperCAmelCase = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
666
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = TFXLMRobertaModel.from_pretrained("jplu/tf-xlm-roberta-base" ) snake_case_ : Any = { "input_ids": tf.convert_to_tensor([[0, 26_46, 1_02_69, 83, 9_99_42, 2]] , dtype=tf.intaa ), # "My dog is cute" "attention_mask": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } snake_case_ : List[str] = model(A__ )["last_hidden_state"] snake_case_ : str = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , A__ ) # compare the actual values for a slice. snake_case_ : List[str] = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
666
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/config.json"} class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = "openai-gpt" _SCREAMING_SNAKE_CASE : Tuple = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Optional[int] , A__ : Optional[Any]=4_04_78 , A__ : List[Any]=5_12 , A__ : Optional[int]=7_68 , A__ : Union[str, Any]=12 , A__ : int=12 , A__ : Optional[int]="gelu" , A__ : Dict=0.1 , A__ : List[str]=0.1 , A__ : str=0.1 , A__ : str=1E-5 , A__ : Union[str, Any]=0.02 , A__ : Dict="cls_index" , A__ : Dict=True , A__ : Dict=None , A__ : Union[str, Any]=True , A__ : List[str]=0.1 , **A__ : Optional[int] , ) -> int: '''simple docstring''' snake_case_ : Dict = vocab_size snake_case_ : Dict = n_positions snake_case_ : int = n_embd snake_case_ : List[Any] = n_layer snake_case_ : str = n_head snake_case_ : Any = afn snake_case_ : str = resid_pdrop snake_case_ : Tuple = embd_pdrop snake_case_ : Tuple = attn_pdrop snake_case_ : str = layer_norm_epsilon snake_case_ : Tuple = initializer_range snake_case_ : Optional[Any] = summary_type snake_case_ : List[str] = summary_use_proj snake_case_ : Any = summary_activation snake_case_ : Optional[Any] = summary_first_dropout snake_case_ : List[str] = summary_proj_to_labels super().__init__(**A__ )
666
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging UpperCAmelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = ["pixel_values"] def __init__( self : Union[str, Any] , A__ : bool = True , A__ : Dict[str, int] = None , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : bool = True , A__ : Dict[str, int] = None , A__ : bool = True , A__ : Union[int, float] = 1 / 2_55 , A__ : bool = True , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : bool = True , **A__ : Optional[int] , ) -> None: '''simple docstring''' super().__init__(**A__ ) snake_case_ : str = size if size is not None else {"shortest_edge": 2_24} snake_case_ : Union[str, Any] = get_size_dict(A__ , default_to_square=A__ ) snake_case_ : List[Any] = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} snake_case_ : Dict = get_size_dict(A__ , default_to_square=A__ , param_name="crop_size" ) snake_case_ : str = do_resize snake_case_ : str = size snake_case_ : Optional[Any] = resample snake_case_ : Any = do_center_crop snake_case_ : Any = crop_size snake_case_ : str = do_rescale snake_case_ : Optional[Any] = rescale_factor snake_case_ : int = do_normalize snake_case_ : Optional[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN snake_case_ : List[str] = image_std if image_std is not None else OPENAI_CLIP_STD snake_case_ : int = do_convert_rgb def UpperCAmelCase__ ( self : Optional[int] , A__ : np.ndarray , A__ : Dict[str, int] , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[str] , ) -> np.ndarray: '''simple docstring''' snake_case_ : str = get_size_dict(A__ , default_to_square=A__ ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) snake_case_ : str = get_resize_output_image_size(A__ , size=size["shortest_edge"] , default_to_square=A__ ) return resize(A__ , size=A__ , resample=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : np.ndarray , A__ : Dict[str, int] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[Any] , ) -> np.ndarray: '''simple docstring''' snake_case_ : Optional[int] = get_size_dict(A__ ) if "height" not in size or "width" not in size: raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(A__ , size=(size["height"], size["width"]) , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Optional[Any] , A__ : np.ndarray , A__ : Union[int, float] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[str] , ) -> str: '''simple docstring''' return rescale(A__ , scale=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Any , A__ : np.ndarray , A__ : Union[float, List[float]] , A__ : Union[float, List[float]] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Any , ) -> np.ndarray: '''simple docstring''' return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : List[Any] , A__ : ImageInput , A__ : bool = None , A__ : Dict[str, int] = None , A__ : PILImageResampling = None , A__ : bool = None , A__ : int = None , A__ : bool = None , A__ : float = None , A__ : bool = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : bool = None , A__ : Optional[Union[str, TensorType]] = None , A__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **A__ : Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' snake_case_ : List[Any] = do_resize if do_resize is not None else self.do_resize snake_case_ : Union[str, Any] = size if size is not None else self.size snake_case_ : Any = get_size_dict(A__ , param_name="size" , default_to_square=A__ ) snake_case_ : Optional[int] = resample if resample is not None else self.resample snake_case_ : int = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ : List[str] = crop_size if crop_size is not None else self.crop_size snake_case_ : Tuple = get_size_dict(A__ , param_name="crop_size" , default_to_square=A__ ) snake_case_ : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale snake_case_ : str = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ : List[Any] = do_normalize if do_normalize is not None else self.do_normalize snake_case_ : Any = image_mean if image_mean is not None else self.image_mean snake_case_ : List[str] = image_std if image_std is not None else self.image_std snake_case_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case_ : List[Any] = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: snake_case_ : Dict = [convert_to_rgb(A__ ) for image in images] # All transformations expect numpy arrays. snake_case_ : Dict = [to_numpy_array(A__ ) for image in images] if do_resize: snake_case_ : Dict = [self.resize(image=A__ , size=A__ , resample=A__ ) for image in images] if do_center_crop: snake_case_ : Tuple = [self.center_crop(image=A__ , size=A__ ) for image in images] if do_rescale: snake_case_ : str = [self.rescale(image=A__ , scale=A__ ) for image in images] if do_normalize: snake_case_ : int = [self.normalize(image=A__ , mean=A__ , std=A__ ) for image in images] snake_case_ : List[Any] = [to_channel_dimension_format(A__ , A__ ) for image in images] snake_case_ : Tuple = {"pixel_values": images} return BatchFeature(data=A__ , tensor_type=A__ )
666
1
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets UpperCAmelCase = "\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" UpperCAmelCase = "\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n" UpperCAmelCase = "\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=[\"About 95 species are currently accepted .\"]\n >>> predictions=[\"About 95 you now get in .\"]\n >>> references=[[\"About 95 species are currently known .\"]]\n >>> wiki_split = datasets.load_metric(\"wiki_split\")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0}\n" def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any ): def remove_articles(lowerCAmelCase_: Dict ): snake_case_ : Optional[int] = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_: Tuple ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_: Dict ): snake_case_ : Optional[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_: int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: Union[str, Any] ): return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[str] , lowerCAmelCase_: Optional[Any] ): snake_case_ : List[str] = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 1_0_0 def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: List[Any] , lowerCAmelCase_: str , lowerCAmelCase_: List[Any] ): snake_case_ : Dict = [rgram for rgrams in rgramslist for rgram in rgrams] snake_case_ : Any = Counter(lowerCAmelCase_ ) snake_case_ : Optional[Any] = Counter(lowerCAmelCase_ ) snake_case_ : List[str] = Counter() for sgram, scount in sgramcounter.items(): snake_case_ : Optional[Any] = scount * numref snake_case_ : int = Counter(lowerCAmelCase_ ) snake_case_ : str = Counter() for cgram, ccount in cgramcounter.items(): snake_case_ : Union[str, Any] = ccount * numref # KEEP snake_case_ : Dict = sgramcounter_rep & cgramcounter_rep snake_case_ : Optional[int] = keepgramcounter_rep & rgramcounter snake_case_ : List[str] = sgramcounter_rep & rgramcounter snake_case_ : Any = 0 snake_case_ : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. snake_case_ : List[Any] = 1 snake_case_ : Any = 1 if len(lowerCAmelCase_ ) > 0: snake_case_ : List[Any] = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) snake_case_ : int = keeptmpscorea / sum(keepgramcounterall_rep.values() ) snake_case_ : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: snake_case_ : List[Any] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION snake_case_ : Optional[Any] = sgramcounter_rep - cgramcounter_rep snake_case_ : str = delgramcounter_rep - rgramcounter snake_case_ : Optional[int] = sgramcounter_rep - rgramcounter snake_case_ : Optional[int] = 0 snake_case_ : List[Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. snake_case_ : str = 1 if len(lowerCAmelCase_ ) > 0: snake_case_ : Union[str, Any] = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION snake_case_ : int = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) snake_case_ : str = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) snake_case_ : int = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) snake_case_ : int = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. snake_case_ : Dict = 1 snake_case_ : List[Any] = 1 if len(lowerCAmelCase_ ) > 0: snake_case_ : Union[str, Any] = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: snake_case_ : Optional[int] = addtmpscore / len(lowerCAmelCase_ ) snake_case_ : List[str] = 0 if addscore_precision > 0 or addscore_recall > 0: snake_case_ : Union[str, Any] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Optional[int] , lowerCAmelCase_: Dict , lowerCAmelCase_: List[Any] ): snake_case_ : Union[str, Any] = len(lowerCAmelCase_ ) snake_case_ : List[Any] = ssent.split(" " ) snake_case_ : List[Any] = csent.split(" " ) snake_case_ : List[Any] = [] snake_case_ : Optional[int] = [] snake_case_ : Tuple = [] snake_case_ : List[str] = [] snake_case_ : Tuple = [] snake_case_ : Tuple = [] snake_case_ : Union[str, Any] = [] snake_case_ : Dict = [] snake_case_ : List[Any] = [] snake_case_ : Union[str, Any] = [] for rsent in rsents: snake_case_ : Optional[Any] = rsent.split(" " ) snake_case_ : Dict = [] snake_case_ : Dict = [] snake_case_ : int = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: snake_case_ : Optional[int] = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: snake_case_ : Dict = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: snake_case_ : Optional[int] = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: snake_case_ : List[Any] = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: snake_case_ : Optional[int] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: snake_case_ : Any = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: snake_case_ : Any = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: snake_case_ : Optional[int] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: snake_case_ : str = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((snake_case_) ,(snake_case_) ,(snake_case_)) : Any = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((snake_case_) ,(snake_case_) ,(snake_case_)) : Union[str, Any] = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((snake_case_) ,(snake_case_) ,(snake_case_)) : int = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((snake_case_) ,(snake_case_) ,(snake_case_)) : Optional[Any] = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : List[Any] = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 snake_case_ : Optional[Any] = sum([delascore, delascore, delascore, delascore] ) / 4 snake_case_ : List[str] = sum([addascore, addascore, addascore, addascore] ) / 4 snake_case_ : List[str] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: bool = True , lowerCAmelCase_: str = "13a" , lowerCAmelCase_: bool = True ): # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: snake_case_ : int = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: snake_case_ : str = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: snake_case_ : Tuple = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": snake_case_ : Optional[Any] = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": snake_case_ : Tuple = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: snake_case_ : int = sentence if not return_str: snake_case_ : Optional[Any] = normalized_sent.split() return normalized_sent def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: Optional[Any] ): if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) snake_case_ : List[Any] = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) snake_case_ : str = sari_score / len(lowerCAmelCase_ ) return 1_0_0 * sari_score def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: str="exp" , lowerCAmelCase_: List[Any]=None , lowerCAmelCase_: Dict=False , lowerCAmelCase_: Tuple=False , lowerCAmelCase_: Optional[int]=False , ): snake_case_ : Dict = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) snake_case_ : Union[str, Any] = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] snake_case_ : Dict = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase__ ( self : str , A__ : Union[str, Any] , A__ : Union[str, Any] , A__ : List[Any] ) -> Optional[int]: '''simple docstring''' snake_case_ : Dict = {} result.update({"sari": compute_sari(sources=A__ , predictions=A__ , references=A__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=A__ , references=A__ )} ) result.update({"exact": compute_em(predictions=A__ , references=A__ )} ) return result
666
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: tuple[int, int] , lowerCAmelCase_: int ): snake_case_ ,snake_case_ : Dict = position snake_case_ : int = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] snake_case_ : Union[str, Any] = [] for position in positions: snake_case_ ,snake_case_ : Union[str, Any] = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(lowerCAmelCase_ ) return permissible_positions def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[list[int]] , lowerCAmelCase_: tuple[int, int] , lowerCAmelCase_: int ): if is_complete(lowerCAmelCase_ ): return True for position in get_valid_pos(lowerCAmelCase_ , len(lowerCAmelCase_ ) ): snake_case_ ,snake_case_ : Dict = position if board[y][x] == 0: snake_case_ : List[str] = curr + 1 if open_knight_tour_helper(lowerCAmelCase_ , lowerCAmelCase_ , curr + 1 ): return True snake_case_ : Dict = 0 return False def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Any = [[0 for i in range(lowerCAmelCase_ )] for j in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): snake_case_ : Optional[Any] = 1 if open_knight_tour_helper(lowerCAmelCase_ , (i, j) , 1 ): return board snake_case_ : Dict = 0 snake_case_ : str = f"Open Kight Tour cannot be performed on a board of size {n}" raise ValueError(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
666
1
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset UpperCAmelCase = "bert-base-cased" UpperCAmelCase = "google/pegasus-xsum" UpperCAmelCase = [" Sam ate lunch today.", "Sams lunch ingredients."] UpperCAmelCase = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"] UpperCAmelCase = "patrickvonplaten/t5-tiny-random" UpperCAmelCase = "sshleifer/bart-tiny-random" UpperCAmelCase = "sshleifer/tiny-mbart" UpperCAmelCase = "sshleifer/tiny-marian-en-de" def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Path , lowerCAmelCase_: list ): snake_case_ : int = "\n".join(lowerCAmelCase_ ) Path(lowerCAmelCase_ ).open("w" ).writelines(lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str ): for split in ["train", "val", "test"]: _dump_articles(os.path.join(lowerCAmelCase_ , f"{split}.source" ) , lowerCAmelCase_ ) _dump_articles(os.path.join(lowerCAmelCase_ , f"{split}.target" ) , lowerCAmelCase_ ) return tmp_dir class snake_case__ ( _UpperCamelCase ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def UpperCAmelCase__ ( self : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = AutoTokenizer.from_pretrained(A__ ) snake_case_ : int = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) snake_case_ : Tuple = max(len(tokenizer.encode(A__ ) ) for a in ARTICLES ) snake_case_ : Tuple = max(len(tokenizer.encode(A__ ) ) for a in SUMMARIES ) snake_case_ : Optional[int] = 4 snake_case_ : str = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated snake_case_ ,snake_case_ : Any = "ro_RO", "de_DE" # ignored for all but mbart, but never causes error. snake_case_ : int = SeqaSeqDataset( A__ , data_dir=A__ , type_path="train" , max_source_length=A__ , max_target_length=A__ , src_lang=A__ , tgt_lang=A__ , ) snake_case_ : Optional[int] = DataLoader(A__ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(A__ , A__ ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place snake_case_ : Any = shift_tokens_right(batch["labels"] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def UpperCAmelCase__ ( self : Dict , A__ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Union[str, Any] = AutoTokenizer.from_pretrained(A__ ) snake_case_ : Optional[Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) snake_case_ : int = max(len(tokenizer.encode(A__ ) ) for a in ARTICLES ) snake_case_ : Any = max(len(tokenizer.encode(A__ ) ) for a in SUMMARIES ) snake_case_ : Optional[int] = 4 snake_case_ : List[str] = LegacySeqaSeqDataset( A__ , data_dir=A__ , type_path="train" , max_source_length=20 , max_target_length=A__ , ) snake_case_ : Dict = DataLoader(A__ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25" ) snake_case_ : Tuple = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) snake_case_ : Union[str, Any] = tmp_dir.joinpath("train.source" ).open().readlines() snake_case_ : List[Any] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(A__ , A__ , 1_28 , A__ ) snake_case_ : Union[str, Any] = {x.name for x in tmp_dir.iterdir()} snake_case_ : List[str] = {x.name for x in save_dir.iterdir()} snake_case_ : Dict = save_dir.joinpath("train.source" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(A__ ) < len(A__ ) assert len(A__ ) == 1 assert len(packed_examples[0] ) == sum(len(A__ ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="This test requires fairseq" ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' if not FAIRSEQ_AVAILABLE: return snake_case_ ,snake_case_ ,snake_case_ : List[str] = self._get_dataset(max_len=64 ) snake_case_ : Dict = 64 snake_case_ : Optional[Any] = ds.make_dynamic_sampler(A__ , required_batch_size_multiple=A__ ) snake_case_ : Optional[int] = [len(A__ ) for x in batch_sampler] assert len(set(A__ ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(A__ ) == len(A__ ) # no dropped or added examples snake_case_ : Any = DataLoader(A__ , batch_sampler=A__ , collate_fn=ds.collate_fn , num_workers=2 ) snake_case_ : Any = [] snake_case_ : Tuple = [] for batch in data_loader: snake_case_ : str = batch["input_ids"].shape snake_case_ : Any = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple snake_case_ : Tuple = np.product(batch["input_ids"].shape ) num_src_per_batch.append(A__ ) if num_src_tokens > (max_tokens * 1.1): failures.append(A__ ) assert num_src_per_batch[0] == max(A__ ) if failures: raise AssertionError(f"too many tokens in {len(A__ )} batches" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' snake_case_ ,snake_case_ ,snake_case_ : str = self._get_dataset(max_len=5_12 ) snake_case_ : str = 2 snake_case_ : List[Any] = ds.make_sortish_sampler(A__ , shuffle=A__ ) snake_case_ : Optional[Any] = DataLoader(A__ , batch_size=A__ , collate_fn=ds.collate_fn , num_workers=2 ) snake_case_ : Any = DataLoader(A__ , batch_size=A__ , collate_fn=ds.collate_fn , num_workers=2 , sampler=A__ ) snake_case_ : Union[str, Any] = tokenizer.pad_token_id def count_pad_tokens(A__ : Optional[int] , A__ : List[Any]="input_ids" ): return [batch[k].eq(A__ ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(A__ , k="labels" ) ) < sum(count_pad_tokens(A__ , k="labels" ) ) assert sum(count_pad_tokens(A__ ) ) < sum(count_pad_tokens(A__ ) ) assert len(A__ ) == len(A__ ) def UpperCAmelCase__ ( self : str , A__ : Dict=10_00 , A__ : Dict=1_28 ) -> Dict: '''simple docstring''' if os.getenv("USE_REAL_DATA" , A__ ): snake_case_ : Union[str, Any] = "examples/seq2seq/wmt_en_ro" snake_case_ : Tuple = max_len * 2 * 64 if not Path(A__ ).joinpath("train.len" ).exists(): save_len_file(A__ , A__ ) else: snake_case_ : Tuple = "examples/seq2seq/test_data/wmt_en_ro" snake_case_ : Tuple = max_len * 4 save_len_file(A__ , A__ ) snake_case_ : Optional[int] = AutoTokenizer.from_pretrained(A__ ) snake_case_ : List[Any] = SeqaSeqDataset( A__ , data_dir=A__ , type_path="train" , max_source_length=A__ , max_target_length=A__ , n_obs=A__ , ) return ds, max_tokens, tokenizer def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: '''simple docstring''' snake_case_ ,snake_case_ ,snake_case_ : List[Any] = self._get_dataset() snake_case_ : Union[str, Any] = set(DistributedSortishSampler(A__ , 2_56 , num_replicas=2 , rank=0 , add_extra_examples=A__ ) ) snake_case_ : List[Any] = set(DistributedSortishSampler(A__ , 2_56 , num_replicas=2 , rank=1 , add_extra_examples=A__ ) ) assert idsa.intersection(A__ ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def UpperCAmelCase__ ( self : Optional[int] , A__ : Optional[int] ) -> Any: '''simple docstring''' snake_case_ : Dict = AutoTokenizer.from_pretrained(A__ , use_fast=A__ ) if tok_name == MBART_TINY: snake_case_ : int = SeqaSeqDataset( A__ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , src_lang="EN" , tgt_lang="FR" , ) snake_case_ : str = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: snake_case_ : Dict = SeqaSeqDataset( A__ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , ) snake_case_ : Tuple = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(A__ ) == 1 if tok_name == BART_TINY else len(A__ ) == 0
666
from ...configuration_utils import PretrainedConfig class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = "bert-generation" def __init__( self : Optional[int] , A__ : List[Any]=5_03_58 , A__ : Any=10_24 , A__ : Any=24 , A__ : List[Any]=16 , A__ : List[Any]=40_96 , A__ : int="gelu" , A__ : List[str]=0.1 , A__ : List[str]=0.1 , A__ : str=5_12 , A__ : int=0.02 , A__ : Any=1E-12 , A__ : Optional[Any]=0 , A__ : List[str]=2 , A__ : Optional[int]=1 , A__ : str="absolute" , A__ : Any=True , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , **A__ ) snake_case_ : str = vocab_size snake_case_ : int = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = hidden_act snake_case_ : Tuple = intermediate_size snake_case_ : str = hidden_dropout_prob snake_case_ : Optional[Any] = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Optional[Any] = initializer_range snake_case_ : Optional[int] = layer_norm_eps snake_case_ : str = position_embedding_type snake_case_ : Dict = use_cache
666
1
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase = { "facebook/mask2former-swin-small-coco-instance": ( "https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase = logging.get_logger(__name__) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = "mask2former" _SCREAMING_SNAKE_CASE : Optional[int] = ["swin"] _SCREAMING_SNAKE_CASE : Any = {"hidden_size": "hidden_dim"} def __init__( self : int , A__ : Optional[Dict] = None , A__ : int = 2_56 , A__ : int = 2_56 , A__ : int = 2_56 , A__ : int = 10_24 , A__ : str = "relu" , A__ : int = 6 , A__ : int = 10 , A__ : int = 8 , A__ : float = 0.0 , A__ : int = 20_48 , A__ : bool = False , A__ : bool = False , A__ : int = 4 , A__ : int = 2_55 , A__ : int = 1_00 , A__ : float = 0.1 , A__ : float = 2.0 , A__ : float = 5.0 , A__ : float = 5.0 , A__ : int = 1_25_44 , A__ : float = 3.0 , A__ : float = 0.75 , A__ : float = 0.02 , A__ : float = 1.0 , A__ : bool = True , A__ : List[int] = [4, 8, 16, 32] , A__ : bool = None , **A__ : Optional[int] , ) -> str: '''simple docstring''' if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `Swin` backbone." ) snake_case_ : Dict = CONFIG_MAPPING["swin"]( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=A__ , out_features=["stage1", "stage2", "stage3", "stage4"] , ) if isinstance(A__ , A__ ): snake_case_ : Optional[int] = backbone_config.pop("model_type" ) snake_case_ : Dict = CONFIG_MAPPING[backbone_model_type] snake_case_ : Tuple = config_class.from_dict(A__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " f"Supported model types: {','.join(self.backbones_supported )}" ) snake_case_ : Optional[int] = backbone_config snake_case_ : Tuple = feature_size snake_case_ : int = mask_feature_size snake_case_ : Optional[Any] = hidden_dim snake_case_ : Optional[Any] = encoder_feedforward_dim snake_case_ : str = activation_function snake_case_ : str = encoder_layers snake_case_ : Optional[Any] = decoder_layers snake_case_ : str = num_attention_heads snake_case_ : Union[str, Any] = dropout snake_case_ : Dict = dim_feedforward snake_case_ : List[str] = pre_norm snake_case_ : Union[str, Any] = enforce_input_projection snake_case_ : List[Any] = common_stride snake_case_ : str = ignore_value snake_case_ : str = num_queries snake_case_ : Optional[int] = no_object_weight snake_case_ : Optional[int] = class_weight snake_case_ : Tuple = mask_weight snake_case_ : Tuple = dice_weight snake_case_ : int = train_num_points snake_case_ : Tuple = oversample_ratio snake_case_ : Union[str, Any] = importance_sample_ratio snake_case_ : Any = init_std snake_case_ : Union[str, Any] = init_xavier_std snake_case_ : Dict = use_auxiliary_loss snake_case_ : Optional[Any] = feature_strides snake_case_ : Union[str, Any] = output_auxiliary_logits snake_case_ : Optional[int] = decoder_layers super().__init__(**A__ ) @classmethod def UpperCAmelCase__ ( cls : Dict , A__ : PretrainedConfig , **A__ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' return cls( backbone_config=A__ , **A__ , ) def UpperCAmelCase__ ( self : List[str] ) -> Dict[str, any]: '''simple docstring''' snake_case_ : Optional[int] = copy.deepcopy(self.__dict__ ) snake_case_ : List[Any] = self.backbone_config.to_dict() snake_case_ : List[Any] = self.__class__.model_type return output
666
import math def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Any = [] snake_case_ : List[str] = 2 snake_case_ : Optional[int] = int(math.sqrt(lowerCAmelCase_ ) ) # Size of every segment snake_case_ : str = [True] * (end + 1) snake_case_ : Any = [] while start <= end: if temp[start] is True: in_prime.append(lowerCAmelCase_ ) for i in range(start * start , end + 1 , lowerCAmelCase_ ): snake_case_ : Union[str, Any] = False start += 1 prime += in_prime snake_case_ : Dict = end + 1 snake_case_ : Dict = min(2 * end , lowerCAmelCase_ ) while low <= n: snake_case_ : Any = [True] * (high - low + 1) for each in in_prime: snake_case_ : Optional[Any] = math.floor(low / each ) * each if t < low: t += each for j in range(lowerCAmelCase_ , high + 1 , lowerCAmelCase_ ): snake_case_ : List[Any] = False for j in range(len(lowerCAmelCase_ ) ): if temp[j] is True: prime.append(j + low ) snake_case_ : int = high + 1 snake_case_ : Union[str, Any] = min(high + end , lowerCAmelCase_ ) return prime print(sieve(1_0**6))
666
1
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: int ): snake_case_ : Tuple = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): snake_case_ : Optional[int] = n - k # Calculate C(n,k) for i in range(lowerCAmelCase_ ): result *= n - i result //= i + 1 return result def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): return binomial_coefficient(2 * node_count , lowerCAmelCase_ ) // (node_count + 1) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): if n < 0: raise ValueError("factorial() not defined for negative values" ) snake_case_ : List[str] = 1 for i in range(1 , n + 1 ): result *= i return result def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): return catalan_number(lowerCAmelCase_ ) * factorial(lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( F"Given {node_count} nodes, there are {binary_tree_count(node_count)} " F"binary trees and {catalan_number(node_count)} binary search trees." )
666
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self : List[str] , A__ : List[Any] , A__ : int=7 , A__ : Union[str, Any]=3 , A__ : List[str]=30 , A__ : Optional[int]=4_00 , A__ : Optional[Any]=True , A__ : Optional[int]=None , A__ : Optional[Any]=True , A__ : Any=[0.5, 0.5, 0.5] , A__ : int=[0.5, 0.5, 0.5] , A__ : Any=True , A__ : int=1 / 2_55 , A__ : List[str]=True , ) -> Dict: '''simple docstring''' snake_case_ : int = size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33} snake_case_ : Any = parent snake_case_ : Optional[int] = batch_size snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = min_resolution snake_case_ : List[Any] = max_resolution snake_case_ : Tuple = do_resize snake_case_ : Dict = size snake_case_ : Optional[Any] = do_normalize snake_case_ : int = image_mean snake_case_ : List[Any] = image_std snake_case_ : Tuple = do_rescale snake_case_ : Any = rescale_factor snake_case_ : Optional[int] = do_pad def UpperCAmelCase__ ( self : int ) -> List[str]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self : Optional[int] , A__ : Optional[int] , A__ : Any=False ) -> Optional[Any]: '''simple docstring''' if not batched: snake_case_ : Any = image_inputs[0] if isinstance(A__ , Image.Image ): snake_case_ ,snake_case_ : Dict = image.size else: snake_case_ ,snake_case_ : int = image.shape[1], image.shape[2] if w < h: snake_case_ : Dict = int(self.size["shortest_edge"] * h / w ) snake_case_ : Optional[int] = self.size["shortest_edge"] elif w > h: snake_case_ : Optional[int] = self.size["shortest_edge"] snake_case_ : str = int(self.size["shortest_edge"] * w / h ) else: snake_case_ : Optional[int] = self.size["shortest_edge"] snake_case_ : List[Any] = self.size["shortest_edge"] else: snake_case_ : str = [] for image in image_inputs: snake_case_ ,snake_case_ : Tuple = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) snake_case_ : List[Any] = max(A__ , key=lambda A__ : item[0] )[0] snake_case_ : int = max(A__ , key=lambda A__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = ConditionalDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Tuple ) -> Dict: '''simple docstring''' snake_case_ : List[str] = ConditionalDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Any ) -> Tuple: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , "image_mean" ) ) self.assertTrue(hasattr(A__ , "image_std" ) ) self.assertTrue(hasattr(A__ , "do_normalize" ) ) self.assertTrue(hasattr(A__ , "do_resize" ) ) self.assertTrue(hasattr(A__ , "size" ) ) def UpperCAmelCase__ ( self : List[str] ) -> Tuple: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 13_33} ) self.assertEqual(image_processor.do_pad , A__ ) snake_case_ : Optional[int] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A__ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , A__ ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: '''simple docstring''' pass def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : Optional[Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ ,snake_case_ : List[Any] = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) snake_case_ : int = image_processing(A__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : int ) -> Any: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , numpify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , np.ndarray ) # Test not batched input snake_case_ : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : List[str] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Optional[int] = image_processing(A__ , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : Dict = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : Tuple ) -> str: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , torchify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , torch.Tensor ) # Test not batched input snake_case_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : List[Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Any = image_processing(A__ , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : int = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: snake_case_ : Optional[Any] = json.loads(f.read() ) snake_case_ : int = {"image_id": 3_97_69, "annotations": target} # encode them snake_case_ : Optional[int] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) snake_case_ : Any = image_processing(images=A__ , annotations=A__ , return_tensors="pt" ) # verify pixel values snake_case_ : List[Any] = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , A__ ) snake_case_ : List[str] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Tuple = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A__ ) ) # verify boxes snake_case_ : Any = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A__ ) snake_case_ : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : List[Any] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A__ ) ) # verify is_crowd snake_case_ : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A__ ) ) # verify class_labels snake_case_ : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A__ ) ) # verify orig_size snake_case_ : Any = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A__ ) ) # verify size snake_case_ : List[str] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A__ ) ) @slow def UpperCAmelCase__ ( self : int ) -> str: '''simple docstring''' snake_case_ : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: snake_case_ : Any = json.loads(f.read() ) snake_case_ : Optional[Any] = {"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target} snake_case_ : int = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them snake_case_ : Union[str, Any] = ConditionalDetrImageProcessor(format="coco_panoptic" ) snake_case_ : str = image_processing(images=A__ , annotations=A__ , masks_path=A__ , return_tensors="pt" ) # verify pixel values snake_case_ : int = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , A__ ) snake_case_ : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Optional[int] = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A__ ) ) # verify boxes snake_case_ : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A__ ) snake_case_ : str = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : List[str] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A__ ) ) # verify is_crowd snake_case_ : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A__ ) ) # verify class_labels snake_case_ : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A__ ) ) # verify masks snake_case_ : Union[str, Any] = 82_28_73 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , A__ ) # verify orig_size snake_case_ : Dict = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A__ ) ) # verify size snake_case_ : str = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A__ ) )
666
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class snake_case__ ( datasets.BeamBasedBuilder ): def UpperCAmelCase__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"content": datasets.Value("string" )} ) , supervised_keys=A__ , ) def UpperCAmelCase__ ( self : Optional[Any] , A__ : str , A__ : str ) -> Optional[int]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_dummy_examples()} )] def UpperCAmelCase__ ( self : int , A__ : Optional[int] , A__ : Dict ) -> Optional[Any]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) class snake_case__ ( datasets.BeamBasedBuilder ): def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) , supervised_keys=A__ , ) def UpperCAmelCase__ ( self : Any , A__ : List[str] , A__ : str ) -> Optional[int]: '''simple docstring''' return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_nested_examples()} ) ] def UpperCAmelCase__ ( self : List[Any] , A__ : List[str] , A__ : Optional[int] ) -> List[str]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) def SCREAMING_SNAKE_CASE_ ( ): return [(i, {"content": content}) for i, content in enumerate(["foo", "bar", "foobar"] )] def SCREAMING_SNAKE_CASE_ ( ): return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["foo", "bar", "foobar"] )] class snake_case__ ( _UpperCamelCase ): @require_beam def UpperCAmelCase__ ( self : str ) -> List[str]: '''simple docstring''' snake_case_ : Union[str, Any] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : Dict = DummyBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) snake_case_ : Optional[int] = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) self.assertDictEqual(dset["train"][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def UpperCAmelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' import apache_beam as beam snake_case_ : Tuple = beam.io.parquetio.WriteToParquet snake_case_ : Union[str, Any] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : List[Any] = DummyBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) with patch("apache_beam.io.parquetio.WriteToParquet" ) as write_parquet_mock: snake_case_ : int = partial(A__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) snake_case_ : Optional[Any] = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["train"]["content"] ) , sorted(["foo", "bar", "foobar"] ) ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : Tuple = DummyBeamDataset(cache_dir=A__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : List[str] = NestedBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) ) snake_case_ : int = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) self.assertDictEqual(dset["train"][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset
666
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) UpperCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class snake_case__ : _SCREAMING_SNAKE_CASE : str = field( default=_UpperCamelCase , metadata={"help": "Model type selected in the list: " + ", ".join(_UpperCamelCase )} ) _SCREAMING_SNAKE_CASE : str = field( default=_UpperCamelCase , metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} ) _SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) _SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."} , ) _SCREAMING_SNAKE_CASE : int = field( default=6_4 , metadata={ "help": ( "The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length." ) } , ) _SCREAMING_SNAKE_CASE : int = field( default=3_0 , metadata={ "help": ( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ) } , ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"} ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} ) _SCREAMING_SNAKE_CASE : float = field( default=0.0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) _SCREAMING_SNAKE_CASE : int = field( default=2_0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) _SCREAMING_SNAKE_CASE : int = field( default=0 , metadata={ "help": ( "language id of input for language-specific xlm models (see" " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)" ) } , ) _SCREAMING_SNAKE_CASE : int = field(default=1 , metadata={"help": "multiple threads for converting example to features"} ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = "train" _SCREAMING_SNAKE_CASE : Any = "dev" class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : SquadDataTrainingArguments _SCREAMING_SNAKE_CASE : List[SquadFeatures] _SCREAMING_SNAKE_CASE : Split _SCREAMING_SNAKE_CASE : bool def __init__( self : str , A__ : SquadDataTrainingArguments , A__ : PreTrainedTokenizer , A__ : Optional[int] = None , A__ : Union[str, Split] = Split.train , A__ : Optional[bool] = False , A__ : Optional[str] = None , A__ : Optional[str] = "pt" , ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = args snake_case_ : int = is_language_sensitive snake_case_ : int = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(A__ , A__ ): try: snake_case_ : List[str] = Split[mode] except KeyError: raise KeyError("mode is not a valid split name" ) snake_case_ : Tuple = mode # Load data features from cache or dataset file snake_case_ : Dict = "v2" if args.version_2_with_negative else "v1" snake_case_ : List[Any] = os.path.join( cache_dir if cache_dir is not None else args.data_dir , f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : List[Any] = cached_features_file + ".lock" with FileLock(A__ ): if os.path.exists(A__ ) and not args.overwrite_cache: snake_case_ : int = time.time() snake_case_ : List[Any] = torch.load(A__ ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. snake_case_ : Tuple = self.old_features["features"] snake_case_ : List[str] = self.old_features.get("dataset" , A__ ) snake_case_ : Tuple = self.old_features.get("examples" , A__ ) logger.info( f"Loading features from cached file {cached_features_file} [took %.3f s]" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in" " future run" ) else: if mode == Split.dev: snake_case_ : Tuple = self.processor.get_dev_examples(args.data_dir ) else: snake_case_ : Tuple = self.processor.get_train_examples(args.data_dir ) snake_case_ ,snake_case_ : Optional[Any] = squad_convert_examples_to_features( examples=self.examples , tokenizer=A__ , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=A__ , ) snake_case_ : Any = time.time() torch.save( {"features": self.features, "dataset": self.dataset, "examples": self.examples} , A__ , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" ) def __len__( self : str ) -> Dict: '''simple docstring''' return len(self.features ) def __getitem__( self : Optional[int] , A__ : Optional[int] ) -> Dict[str, torch.Tensor]: '''simple docstring''' snake_case_ : Any = self.features[i] snake_case_ : Optional[int] = torch.tensor(feature.input_ids , dtype=torch.long ) snake_case_ : Union[str, Any] = torch.tensor(feature.attention_mask , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.token_type_ids , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.cls_index , dtype=torch.long ) snake_case_ : str = torch.tensor(feature.p_mask , dtype=torch.float ) snake_case_ : str = torch.tensor(feature.is_impossible , dtype=torch.float ) snake_case_ : Optional[int] = { "input_ids": input_ids, "attention_mask": attention_mask, "token_type_ids": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"cls_index": cls_index, "p_mask": p_mask} ) if self.args.version_2_with_negative: inputs.update({"is_impossible": is_impossible} ) if self.is_language_sensitive: inputs.update({"langs": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: snake_case_ : Any = torch.tensor(feature.start_position , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({"start_positions": start_positions, "end_positions": end_positions} ) return inputs
666
1
import re import string import numpy as np import datasets UpperCAmelCase = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" UpperCAmelCase = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" UpperCAmelCase = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): def UpperCAmelCase__ ( self : List[Any] ) -> Any: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def UpperCAmelCase__ ( self : Union[str, Any] , A__ : str , A__ : Dict , A__ : Dict=None , A__ : int=False , A__ : Union[str, Any]=False , A__ : int=False , ) -> int: '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: snake_case_ : Any = np.array([re.sub(A__ , "" , A__ ) for x in predictions] ) snake_case_ : Optional[Any] = np.array([re.sub(A__ , "" , A__ ) for x in references] ) else: snake_case_ : Optional[int] = np.asarray(A__ ) snake_case_ : List[str] = np.asarray(A__ ) if ignore_case: snake_case_ : Dict = np.char.lower(A__ ) snake_case_ : Optional[int] = np.char.lower(A__ ) if ignore_punctuation: snake_case_ : Union[str, Any] = string.punctuation.maketrans("" , "" , string.punctuation ) snake_case_ : Dict = np.char.translate(A__ , table=A__ ) snake_case_ : List[str] = np.char.translate(A__ , table=A__ ) if ignore_numbers: snake_case_ : Optional[Any] = string.digits.maketrans("" , "" , string.digits ) snake_case_ : List[Any] = np.char.translate(A__ , table=A__ ) snake_case_ : Union[str, Any] = np.char.translate(A__ , table=A__ ) snake_case_ : str = predictions == references return {"exact_match": np.mean(A__ ) * 1_00}
666
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "git_vision_model" def __init__( self : int , A__ : Union[str, Any]=7_68 , A__ : List[Any]=30_72 , A__ : Tuple=12 , A__ : Optional[Any]=12 , A__ : Optional[int]=3 , A__ : List[str]=2_24 , A__ : Dict=16 , A__ : int="quick_gelu" , A__ : Any=1E-5 , A__ : Tuple=0.0 , A__ : Optional[int]=0.02 , **A__ : List[str] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : str = intermediate_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Optional[int] = num_channels snake_case_ : Union[str, Any] = patch_size snake_case_ : List[str] = image_size snake_case_ : List[Any] = initializer_range snake_case_ : Any = attention_dropout snake_case_ : Any = layer_norm_eps snake_case_ : int = hidden_act @classmethod def UpperCAmelCase__ ( cls : List[Any] , A__ : Union[str, os.PathLike] , **A__ : Optional[int] ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(A__ ) snake_case_ ,snake_case_ : Tuple = cls.get_config_dict(A__ , **A__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("model_type" ) == "git": snake_case_ : 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(A__ , **A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = "git" def __init__( self : Any , A__ : List[str]=None , A__ : List[str]=3_05_22 , A__ : Tuple=7_68 , A__ : Tuple=6 , A__ : str=12 , A__ : Any=30_72 , A__ : List[str]="gelu" , A__ : int=0.1 , A__ : Dict=0.1 , A__ : Any=10_24 , A__ : Optional[Any]=0.02 , A__ : Optional[Any]=1E-12 , A__ : Dict=0 , A__ : Any="absolute" , A__ : Tuple=True , A__ : Any=False , A__ : Tuple=1_01 , A__ : Tuple=1_02 , A__ : List[Any]=None , **A__ : List[str] , ) -> int: '''simple docstring''' super().__init__(bos_token_id=A__ , eos_token_id=A__ , pad_token_id=A__ , **A__ ) if vision_config is None: snake_case_ : int = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values." ) snake_case_ : str = GitVisionConfig(**A__ ) snake_case_ : int = vocab_size snake_case_ : List[Any] = hidden_size snake_case_ : Tuple = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Any = hidden_act snake_case_ : Dict = intermediate_size snake_case_ : Any = hidden_dropout_prob snake_case_ : Any = attention_probs_dropout_prob snake_case_ : Union[str, Any] = max_position_embeddings snake_case_ : List[str] = initializer_range snake_case_ : List[str] = layer_norm_eps snake_case_ : Any = position_embedding_type snake_case_ : Union[str, Any] = use_cache snake_case_ : str = tie_word_embeddings snake_case_ : List[Any] = num_image_with_embedding snake_case_ : Dict = bos_token_id snake_case_ : int = eos_token_id def UpperCAmelCase__ ( self : Any ) -> int: '''simple docstring''' snake_case_ : Tuple = copy.deepcopy(self.__dict__ ) snake_case_ : Optional[int] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output
666
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "transfo-xl" _SCREAMING_SNAKE_CASE : Tuple = ["mems"] _SCREAMING_SNAKE_CASE : str = { "n_token": "vocab_size", "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[Any] , A__ : Union[str, Any]=26_77_35 , A__ : Any=[2_00_00, 4_00_00, 20_00_00] , A__ : Union[str, Any]=10_24 , A__ : List[str]=10_24 , A__ : List[str]=16 , A__ : List[Any]=64 , A__ : Any=40_96 , A__ : List[Any]=4 , A__ : Tuple=False , A__ : List[Any]=18 , A__ : List[Any]=16_00 , A__ : Union[str, Any]=10_00 , A__ : Union[str, Any]=True , A__ : Optional[Any]=True , A__ : List[Any]=0 , A__ : List[str]=-1 , A__ : Tuple=True , A__ : Optional[int]=0.1 , A__ : Tuple=0.0 , A__ : Tuple=True , A__ : Union[str, Any]="normal" , A__ : str=0.01 , A__ : str=0.01 , A__ : Tuple=0.02 , A__ : List[str]=1E-5 , A__ : Dict=0 , **A__ : Any , ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = vocab_size snake_case_ : Optional[int] = [] self.cutoffs.extend(A__ ) if proj_share_all_but_first: snake_case_ : List[str] = [False] + [True] * len(self.cutoffs ) else: snake_case_ : int = [False] + [False] * len(self.cutoffs ) snake_case_ : Union[str, Any] = d_model snake_case_ : Dict = d_embed snake_case_ : List[str] = d_head snake_case_ : Any = d_inner snake_case_ : List[Any] = div_val snake_case_ : Dict = pre_lnorm snake_case_ : str = n_layer snake_case_ : Union[str, Any] = n_head snake_case_ : Dict = mem_len snake_case_ : int = same_length snake_case_ : Dict = attn_type snake_case_ : Union[str, Any] = clamp_len snake_case_ : Dict = sample_softmax snake_case_ : Optional[int] = adaptive snake_case_ : Any = dropout snake_case_ : Dict = dropatt snake_case_ : Tuple = untie_r snake_case_ : str = init snake_case_ : Optional[Any] = init_range snake_case_ : Optional[Any] = proj_init_std snake_case_ : List[str] = init_std snake_case_ : int = layer_norm_epsilon super().__init__(eos_token_id=A__ , **A__ ) @property def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: '''simple docstring''' logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit." ) return -1 @max_position_embeddings.setter def UpperCAmelCase__ ( self : Optional[Any] , A__ : List[Any] ) -> List[Any]: '''simple docstring''' raise NotImplementedError( f"The model {self.model_type} is one of the few models that has no sequence length limit." )
666
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: str ): def get_matched_characters(lowerCAmelCase_: str , lowerCAmelCase_: str ) -> str: snake_case_ : Tuple = [] snake_case_ : Tuple = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): snake_case_ : str = int(max(0 , i - limit ) ) snake_case_ : Optional[int] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCAmelCase_ ) snake_case_ : List[Any] = f"{_stra[0:_stra.index(lowerCAmelCase_ )]} {_stra[_stra.index(lowerCAmelCase_ ) + 1:]}" return "".join(lowerCAmelCase_ ) # matching characters snake_case_ : List[Any] = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : int = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = len(lowerCAmelCase_ ) # transposition snake_case_ : List[str] = ( len([(ca, ca) for ca, ca in zip(lowerCAmelCase_ , lowerCAmelCase_ ) if ca != ca] ) // 2 ) if not match_count: snake_case_ : str = 0.0 else: snake_case_ : Optional[Any] = ( 1 / 3 * ( match_count / len(lowerCAmelCase_ ) + match_count / len(lowerCAmelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters snake_case_ : Optional[Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
666
1
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} UpperCAmelCase = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } UpperCAmelCase = { "allenai/longformer-base-4096": 4_0_9_6, "allenai/longformer-large-4096": 4_0_9_6, "allenai/longformer-large-4096-finetuned-triviaqa": 4_0_9_6, "allenai/longformer-base-4096-extra.pos.embd.only": 4_0_9_6, "allenai/longformer-large-4096-extra.pos.embd.only": 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def SCREAMING_SNAKE_CASE_ ( ): snake_case_ : Tuple = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) snake_case_ : List[str] = bs[:] snake_case_ : Any = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase_ ) cs.append(2**8 + n ) n += 1 snake_case_ : Optional[Any] = [chr(lowerCAmelCase_ ) for n in cs] return dict(zip(lowerCAmelCase_ , lowerCAmelCase_ ) ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] ): snake_case_ : Optional[int] = set() snake_case_ : Tuple = word[0] for char in word[1:]: pairs.add((prev_char, char) ) snake_case_ : List[Any] = char return pairs class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : int = ["input_ids", "attention_mask"] def __init__( self : Dict , A__ : Dict , A__ : Tuple , A__ : Dict="replace" , A__ : int="<s>" , A__ : Optional[Any]="</s>" , A__ : Optional[int]="</s>" , A__ : Any="<s>" , A__ : Optional[Any]="<unk>" , A__ : Dict="<pad>" , A__ : int="<mask>" , A__ : Tuple=False , **A__ : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' snake_case_ : str = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else bos_token snake_case_ : str = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else eos_token snake_case_ : Optional[int] = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else sep_token snake_case_ : Optional[Any] = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else cls_token snake_case_ : List[Any] = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else unk_token snake_case_ : Tuple = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it snake_case_ : Union[str, Any] = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else mask_token super().__init__( errors=A__ , bos_token=A__ , eos_token=A__ , unk_token=A__ , sep_token=A__ , cls_token=A__ , pad_token=A__ , mask_token=A__ , add_prefix_space=A__ , **A__ , ) with open(A__ , encoding="utf-8" ) as vocab_handle: snake_case_ : List[str] = json.load(A__ ) snake_case_ : List[str] = {v: k for k, v in self.encoder.items()} snake_case_ : Dict = errors # how to handle errors in decoding snake_case_ : Any = bytes_to_unicode() snake_case_ : List[str] = {v: k for k, v in self.byte_encoder.items()} with open(A__ , encoding="utf-8" ) as merges_handle: snake_case_ : List[str] = merges_handle.read().split("\n" )[1:-1] snake_case_ : Union[str, Any] = [tuple(merge.split() ) for merge in bpe_merges] snake_case_ : str = dict(zip(A__ , range(len(A__ ) ) ) ) snake_case_ : str = {} snake_case_ : str = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions snake_case_ : List[str] = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: '''simple docstring''' return len(self.encoder ) def UpperCAmelCase__ ( self : Any ) -> Any: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase__ ( self : Any , A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' if token in self.cache: return self.cache[token] snake_case_ : Any = tuple(A__ ) snake_case_ : Union[str, Any] = get_pairs(A__ ) if not pairs: return token while True: snake_case_ : List[Any] = min(A__ , key=lambda A__ : self.bpe_ranks.get(A__ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break snake_case_ ,snake_case_ : int = bigram snake_case_ : List[Any] = [] snake_case_ : Any = 0 while i < len(A__ ): try: snake_case_ : List[str] = word.index(A__ , A__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) snake_case_ : Any = j if word[i] == first and i < len(A__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 snake_case_ : Tuple = tuple(A__ ) snake_case_ : Optional[Any] = new_word if len(A__ ) == 1: break else: snake_case_ : Union[str, Any] = get_pairs(A__ ) snake_case_ : Any = " ".join(A__ ) snake_case_ : str = word return word def UpperCAmelCase__ ( self : Dict , A__ : List[Any] ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = [] for token in re.findall(self.pat , A__ ): snake_case_ : str = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(A__ ).split(" " ) ) return bpe_tokens def UpperCAmelCase__ ( self : Dict , A__ : Any ) -> Any: '''simple docstring''' return self.encoder.get(A__ , self.encoder.get(self.unk_token ) ) def UpperCAmelCase__ ( self : int , A__ : List[Any] ) -> str: '''simple docstring''' return self.decoder.get(A__ ) def UpperCAmelCase__ ( self : Dict , A__ : Tuple ) -> str: '''simple docstring''' snake_case_ : int = "".join(A__ ) snake_case_ : List[str] = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def UpperCAmelCase__ ( self : Optional[Any] , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A__ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return snake_case_ : Any = os.path.join( A__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) snake_case_ : Dict = os.path.join( A__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(A__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=A__ , ensure_ascii=A__ ) + "\n" ) snake_case_ : List[str] = 0 with open(A__ , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda A__ : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!" ) snake_case_ : List[Any] = token_index writer.write(" ".join(A__ ) + "\n" ) index += 1 return vocab_file, merge_file def UpperCAmelCase__ ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ : Optional[Any] = [self.cls_token_id] snake_case_ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase__ ( self : Optional[Any] , A__ : List[int] , A__ : Optional[List[int]] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A__ , token_ids_a=A__ , already_has_special_tokens=A__ ) if token_ids_a is None: return [1] + ([0] * len(A__ )) + [1] return [1] + ([0] * len(A__ )) + [1, 1] + ([0] * len(A__ )) + [1] def UpperCAmelCase__ ( self : Optional[int] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' snake_case_ : Union[str, Any] = [self.sep_token_id] snake_case_ : 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 + sep + token_ids_a + sep ) * [0] def UpperCAmelCase__ ( self : List[Any] , A__ : str , A__ : List[Any]=False , **A__ : Tuple ) -> List[str]: '''simple docstring''' snake_case_ : Dict = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(A__ ) > 0 and not text[0].isspace()): snake_case_ : Tuple = " " + text return (text, kwargs)
666
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) set_seed(7_7_0) UpperCAmelCase = { "c_attn": "att_proj", "c_proj": "out_proj", "c_fc": "in_proj", "transformer.": "", "h.": "layers.", "ln_1": "layernorm_1", "ln_2": "layernorm_2", "ln_f": "layernorm_final", "wpe": "position_embeds_layer", "wte": "input_embeds_layer", } UpperCAmelCase = { "text_small": { "repo_id": "suno/bark", "file_name": "text.pt", }, "coarse_small": { "repo_id": "suno/bark", "file_name": "coarse.pt", }, "fine_small": { "repo_id": "suno/bark", "file_name": "fine.pt", }, "text": { "repo_id": "suno/bark", "file_name": "text_2.pt", }, "coarse": { "repo_id": "suno/bark", "file_name": "coarse_2.pt", }, "fine": { "repo_id": "suno/bark", "file_name": "fine_2.pt", }, } UpperCAmelCase = os.path.dirname(os.path.abspath(__file__)) UpperCAmelCase = os.path.join(os.path.expanduser("~"), ".cache") UpperCAmelCase = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: List[str]=False ): snake_case_ : Union[str, Any] = model_type if use_small: key += "_small" return os.path.join(lowerCAmelCase_ , REMOTE_MODEL_PATHS[key]["file_name"] ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: List[str] ): os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) hf_hub_download(repo_id=lowerCAmelCase_ , filename=lowerCAmelCase_ , local_dir=lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: Dict , lowerCAmelCase_: List[str]=False , lowerCAmelCase_: Dict="text" ): if model_type == "text": snake_case_ : int = BarkSemanticModel snake_case_ : str = BarkSemanticConfig snake_case_ : Optional[Any] = BarkSemanticGenerationConfig elif model_type == "coarse": snake_case_ : str = BarkCoarseModel snake_case_ : Optional[int] = BarkCoarseConfig snake_case_ : Any = BarkCoarseGenerationConfig elif model_type == "fine": snake_case_ : Optional[int] = BarkFineModel snake_case_ : Tuple = BarkFineConfig snake_case_ : List[str] = BarkFineGenerationConfig else: raise NotImplementedError() snake_case_ : Optional[Any] = f"{model_type}_small" if use_small else model_type snake_case_ : Any = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(lowerCAmelCase_ ): logger.info(f"{model_type} model not found, downloading into `{CACHE_DIR}`." ) _download(model_info["repo_id"] , model_info["file_name"] ) snake_case_ : Any = torch.load(lowerCAmelCase_ , map_location=lowerCAmelCase_ ) # this is a hack snake_case_ : Union[str, Any] = checkpoint["model_args"] if "input_vocab_size" not in model_args: snake_case_ : str = model_args["vocab_size"] snake_case_ : Union[str, Any] = model_args["vocab_size"] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments snake_case_ : Union[str, Any] = model_args.pop("n_head" ) snake_case_ : int = model_args.pop("n_embd" ) snake_case_ : Any = model_args.pop("n_layer" ) snake_case_ : List[str] = ConfigClass(**checkpoint["model_args"] ) snake_case_ : Optional[Any] = ModelClass(config=lowerCAmelCase_ ) snake_case_ : Tuple = GenerationConfigClass() snake_case_ : List[str] = model_generation_config snake_case_ : Optional[int] = checkpoint["model"] # fixup checkpoint snake_case_ : Optional[int] = "_orig_mod." for k, v in list(state_dict.items() ): if k.startswith(lowerCAmelCase_ ): # replace part of the key with corresponding layer name in HF implementation snake_case_ : Tuple = k[len(lowerCAmelCase_ ) :] for old_layer_name in new_layer_name_dict: snake_case_ : int = new_k.replace(lowerCAmelCase_ , new_layer_name_dict[old_layer_name] ) snake_case_ : int = state_dict.pop(lowerCAmelCase_ ) snake_case_ : Optional[int] = set(state_dict.keys() ) - set(model.state_dict().keys() ) snake_case_ : str = {k for k in extra_keys if not k.endswith(".attn.bias" )} snake_case_ : Any = set(model.state_dict().keys() ) - set(state_dict.keys() ) snake_case_ : List[Any] = {k for k in missing_keys if not k.endswith(".attn.bias" )} if len(lowerCAmelCase_ ) != 0: raise ValueError(f"extra keys found: {extra_keys}" ) if len(lowerCAmelCase_ ) != 0: raise ValueError(f"missing keys: {missing_keys}" ) model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) snake_case_ : str = model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) snake_case_ : Union[str, Any] = checkpoint["best_val_loss"].item() logger.info(f"model loaded: {round(n_params/1e6 , 1 )}M params, {round(lowerCAmelCase_ , 3 )} loss" ) model.eval() model.to(lowerCAmelCase_ ) del checkpoint, state_dict return model def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] , lowerCAmelCase_: str=False , lowerCAmelCase_: int="text" ): if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() snake_case_ : int = "cpu" # do conversion on cpu snake_case_ : Optional[Any] = _get_ckpt_path(lowerCAmelCase_ , use_small=lowerCAmelCase_ ) snake_case_ : Tuple = _load_model(lowerCAmelCase_ , lowerCAmelCase_ , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) # load bark initial model snake_case_ : int = _bark_load_model(lowerCAmelCase_ , "cpu" , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) if model_type == "text": snake_case_ : Union[str, Any] = bark_model["model"] if model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) != bark_model.get_num_params(): raise ValueError("initial and new models don't have the same number of parameters" ) # check if same output as the bark model snake_case_ : Optional[Any] = 5 snake_case_ : Optional[int] = 1_0 if model_type in ["text", "coarse"]: snake_case_ : Optional[Any] = torch.randint(2_5_6 , (batch_size, sequence_length) , dtype=torch.int ) snake_case_ : str = bark_model(lowerCAmelCase_ )[0] snake_case_ : Tuple = model(lowerCAmelCase_ ) # take last logits snake_case_ : List[str] = output_new_model_total.logits[:, [-1], :] else: snake_case_ : Optional[int] = 3 snake_case_ : str = 8 snake_case_ : List[str] = torch.randint(2_5_6 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) snake_case_ : Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Union[str, Any] = bark_model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("initial and new outputs don't have the same shape" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("initial and new outputs are not equal" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple , lowerCAmelCase_: List[str] , lowerCAmelCase_: Any , lowerCAmelCase_: List[Any] , lowerCAmelCase_: int , lowerCAmelCase_: Optional[Any] , ): snake_case_ : Optional[Any] = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkSemanticConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = BarkCoarseConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[str] = BarkFineConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = EncodecConfig.from_pretrained("facebook/encodec_24khz" ) snake_case_ : List[str] = BarkSemanticModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkCoarseModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Tuple = BarkFineModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_24khz" ) snake_case_ : Tuple = BarkConfig.from_sub_model_configs( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : List[Any] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) snake_case_ : Optional[int] = BarkModel(lowerCAmelCase_ ) snake_case_ : int = semantic snake_case_ : List[str] = coarseAcoustic snake_case_ : str = fineAcoustic snake_case_ : Optional[Any] = codec snake_case_ : Any = bark_generation_config Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) bark.save_pretrained(lowerCAmelCase_ , repo_id=lowerCAmelCase_ , push_to_hub=lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") UpperCAmelCase = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
666
1
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: Any=1_0 ): snake_case_ : Optional[int] = [] for _ in range(lowerCAmelCase_ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: Union[str, Any]=1_0 ): snake_case_ : List[str] = [] for step in range(lowerCAmelCase_ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Optional[int] = os.path.join(lowerCAmelCase_ , "schedule.bin" ) torch.save(scheduler.state_dict() , lowerCAmelCase_ ) snake_case_ : Optional[int] = torch.load(lowerCAmelCase_ ) scheduler.load_state_dict(lowerCAmelCase_ ) return lrs @require_torch class snake_case__ ( unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[Any] , A__ : Tuple , A__ : Any , A__ : List[str] ) -> str: '''simple docstring''' self.assertEqual(len(A__ ) , len(A__ ) ) for a, b in zip(A__ , A__ ): self.assertAlmostEqual(A__ , A__ , delta=A__ ) def UpperCAmelCase__ ( self : Tuple ) -> int: '''simple docstring''' snake_case_ : Any = torch.tensor([0.1, -0.2, -0.1] , requires_grad=A__ ) snake_case_ : Tuple = torch.tensor([0.4, 0.2, -0.5] ) snake_case_ : List[Any] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping snake_case_ : int = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(1_00 ): snake_case_ : Union[str, Any] = criterion(A__ , A__ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def UpperCAmelCase__ ( self : Dict ) -> List[Any]: '''simple docstring''' snake_case_ : str = torch.tensor([0.1, -0.2, -0.1] , requires_grad=A__ ) snake_case_ : Dict = torch.tensor([0.4, 0.2, -0.5] ) snake_case_ : Union[str, Any] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping snake_case_ : int = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=A__ , weight_decay=0.0 , relative_step=A__ , scale_parameter=A__ , warmup_init=A__ , ) for _ in range(10_00 ): snake_case_ : Dict = criterion(A__ , A__ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class snake_case__ ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : str = nn.Linear(5_0 , 5_0 ) if is_torch_available() else None _SCREAMING_SNAKE_CASE : Tuple = AdamW(m.parameters() , lr=1_0.0 ) if is_torch_available() else None _SCREAMING_SNAKE_CASE : str = 1_0 def UpperCAmelCase__ ( self : str , A__ : Tuple , A__ : str , A__ : int , A__ : Dict=None ) -> Dict: '''simple docstring''' self.assertEqual(len(A__ ) , len(A__ ) ) for a, b in zip(A__ , A__ ): self.assertAlmostEqual(A__ , A__ , delta=A__ , msg=A__ ) def UpperCAmelCase__ ( self : str ) -> List[str]: '''simple docstring''' snake_case_ : int = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) snake_case_ : Optional[Any] = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): snake_case_ ,snake_case_ : List[str] = data snake_case_ : Dict = scheduler_func(self.optimizer , **A__ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) snake_case_ : Union[str, Any] = unwrap_schedule(A__ , self.num_steps ) self.assertListAlmostEqual( A__ , A__ , tol=1E-2 , msg=f"failed for {scheduler_func} in normal scheduler" , ) snake_case_ : List[str] = scheduler_func(self.optimizer , **A__ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(A__ ) # wrap to test picklability of the schedule snake_case_ : Tuple = unwrap_and_save_reload_schedule(A__ , self.num_steps ) self.assertListEqual(A__ , A__ , msg=f"failed for {scheduler_func} in save and reload" ) class snake_case__ : def __init__( self : int , A__ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' snake_case_ : str = fn def __call__( self : Dict , *A__ : List[str] , **A__ : str ) -> Optional[int]: '''simple docstring''' return self.fn(*A__ , **A__ ) @classmethod def UpperCAmelCase__ ( self : Optional[Any] , A__ : Dict ) -> Optional[int]: '''simple docstring''' snake_case_ : Dict = list(map(self , scheduler.lr_lambdas ) )
666
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase = { "configuration_upernet": ["UperNetConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "UperNetForSemanticSegmentation", "UperNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = {"configuration_reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["ReformerTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["ReformerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ReformerAttention", "ReformerForMaskedLM", "ReformerForQuestionAnswering", "ReformerForSequenceClassification", "ReformerLayer", "ReformerModel", "ReformerModelWithLMHead", "ReformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch UpperCAmelCase = logging.get_logger(__name__) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : str = ["pixel_values"] def __init__( self : List[Any] , A__ : bool = True , A__ : Optional[Dict[str, int]] = None , A__ : PILImageResampling = PILImageResampling.BILINEAR , A__ : bool = True , A__ : Dict[str, int] = None , A__ : bool = True , A__ : Union[int, float] = 1 / 2_55 , A__ : bool = True , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , **A__ : int , ) -> None: '''simple docstring''' super().__init__(**A__ ) snake_case_ : Optional[int] = size if size is not None else {"shortest_edge": 2_56} snake_case_ : Dict = get_size_dict(A__ , default_to_square=A__ ) snake_case_ : List[str] = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} snake_case_ : Any = get_size_dict(A__ , param_name="crop_size" ) snake_case_ : int = do_resize snake_case_ : Optional[Any] = size snake_case_ : Optional[Any] = resample snake_case_ : Optional[int] = do_center_crop snake_case_ : List[Any] = crop_size snake_case_ : List[Any] = do_rescale snake_case_ : Optional[int] = rescale_factor snake_case_ : Optional[Any] = do_normalize snake_case_ : List[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN snake_case_ : Optional[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase__ ( self : List[str] , A__ : np.ndarray , A__ : Dict[str, int] , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : str , ) -> np.ndarray: '''simple docstring''' snake_case_ : Optional[Any] = get_size_dict(A__ , default_to_square=A__ ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) snake_case_ : Any = get_resize_output_image_size(A__ , size=size["shortest_edge"] , default_to_square=A__ ) return resize(A__ , size=A__ , resample=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : int , A__ : np.ndarray , A__ : Dict[str, int] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Union[str, Any] , ) -> np.ndarray: '''simple docstring''' snake_case_ : Tuple = get_size_dict(A__ ) if "height" not in size or "width" not in size: raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}" ) return center_crop(A__ , size=(size["height"], size["width"]) , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : List[str] , A__ : np.ndarray , A__ : float , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Tuple ) -> np.ndarray: '''simple docstring''' return rescale(A__ , scale=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : np.ndarray , A__ : Union[float, List[float]] , A__ : Union[float, List[float]] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Dict , ) -> np.ndarray: '''simple docstring''' return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , A__ : ImageInput , A__ : Optional[bool] = None , A__ : Dict[str, int] = None , A__ : PILImageResampling = None , A__ : bool = None , A__ : Dict[str, int] = None , A__ : Optional[bool] = None , A__ : Optional[float] = None , A__ : Optional[bool] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[str, TensorType]] = None , A__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **A__ : Union[str, Any] , ) -> Optional[int]: '''simple docstring''' snake_case_ : Union[str, Any] = do_resize if do_resize is not None else self.do_resize snake_case_ : Dict = size if size is not None else self.size snake_case_ : Optional[Any] = get_size_dict(A__ , default_to_square=A__ ) snake_case_ : Tuple = resample if resample is not None else self.resample snake_case_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ : str = crop_size if crop_size is not None else self.crop_size snake_case_ : Tuple = get_size_dict(A__ , param_name="crop_size" ) snake_case_ : Dict = do_rescale if do_rescale is not None else self.do_rescale snake_case_ : str = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ : Any = do_normalize if do_normalize is not None else self.do_normalize snake_case_ : Any = image_mean if image_mean is not None else self.image_mean snake_case_ : List[str] = image_std if image_std is not None else self.image_std snake_case_ : Dict = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. snake_case_ : Tuple = [to_numpy_array(A__ ) for image in images] if do_resize: snake_case_ : Any = [self.resize(image=A__ , size=A__ , resample=A__ ) for image in images] if do_center_crop: snake_case_ : List[str] = [self.center_crop(image=A__ , size=A__ ) for image in images] if do_rescale: snake_case_ : Any = [self.rescale(image=A__ , scale=A__ ) for image in images] if do_normalize: snake_case_ : Union[str, Any] = [self.normalize(image=A__ , mean=A__ , std=A__ ) for image in images] snake_case_ : Optional[Any] = [to_channel_dimension_format(A__ , A__ ) for image in images] snake_case_ : Any = {"pixel_values": images} return BatchFeature(data=A__ , tensor_type=A__ ) def UpperCAmelCase__ ( self : List[str] , A__ : Dict , A__ : List[Tuple] = None ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A__ ) != len(A__ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(A__ ): snake_case_ : Dict = target_sizes.numpy() snake_case_ : int = [] for idx in range(len(A__ ) ): snake_case_ : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=A__ ) snake_case_ : int = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A__ ) else: snake_case_ : List[Any] = logits.argmax(dim=1 ) snake_case_ : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
666
1
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( "compression_format, is_archive" , [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ] , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: List[str] , lowerCAmelCase_: List[str] , lowerCAmelCase_: str , lowerCAmelCase_: int , lowerCAmelCase_: str , lowerCAmelCase_: Optional[int] , lowerCAmelCase_: List[Any] , lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: int , lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: Tuple , ): snake_case_ : Tuple = { "7z": (seven_zip_file, SevenZipExtractor), "bz2": (bza_file, BzipaExtractor), "gzip": (gz_file, GzipExtractor), "lz4": (lza_file, LzaExtractor), "tar": (tar_file, TarExtractor), "xz": (xz_file, XzExtractor), "zip": (zip_file, ZipExtractor), "zstd": (zstd_file, ZstdExtractor), } snake_case_ ,snake_case_ : int = input_paths_and_base_extractors[compression_format] if input_path is None: snake_case_ : Tuple = f"for '{compression_format}' compression_format, " if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(lowerCAmelCase_ ) assert base_extractor.is_extractable(lowerCAmelCase_ ) snake_case_ : int = tmp_path / ("extracted" if is_archive else "extracted.txt") base_extractor.extract(lowerCAmelCase_ , lowerCAmelCase_ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name snake_case_ : List[Any] = file_path.read_text(encoding="utf-8" ) else: snake_case_ : Union[str, Any] = output_path.read_text(encoding="utf-8" ) snake_case_ : Dict = text_file.read_text(encoding="utf-8" ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( "compression_format, is_archive" , [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ] , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Optional[int] , lowerCAmelCase_: int , lowerCAmelCase_: Dict , lowerCAmelCase_: int , lowerCAmelCase_: str , lowerCAmelCase_: List[str] , lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: List[str] , lowerCAmelCase_: Union[str, Any] , lowerCAmelCase_: Any , lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: str , ): snake_case_ : int = { "7z": seven_zip_file, "bz2": bza_file, "gzip": gz_file, "lz4": lza_file, "tar": tar_file, "xz": xz_file, "zip": zip_file, "zstd": zstd_file, } snake_case_ : List[Any] = input_paths[compression_format] if input_path is None: snake_case_ : Optional[Any] = f"for '{compression_format}' compression_format, " if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(lowerCAmelCase_ ) snake_case_ : str = Extractor.infer_extractor_format(lowerCAmelCase_ ) assert extractor_format is not None snake_case_ : int = tmp_path / ("extracted" if is_archive else "extracted.txt") Extractor.extract(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name snake_case_ : List[Any] = file_path.read_text(encoding="utf-8" ) else: snake_case_ : int = output_path.read_text(encoding="utf-8" ) snake_case_ : str = text_file.read_text(encoding="utf-8" ) assert extracted_file_content == expected_file_content @pytest.fixture def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: Any ): import tarfile snake_case_ : Any = tmp_path / "data_dot_dot" directory.mkdir() snake_case_ : Any = directory / "tar_file_with_dot_dot.tar" with tarfile.TarFile(lowerCAmelCase_ , "w" ) as f: f.add(lowerCAmelCase_ , arcname=os.path.join(".." , text_file.name ) ) return path @pytest.fixture def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Union[str, Any] ): import tarfile snake_case_ : Tuple = tmp_path / "data_sym_link" directory.mkdir() snake_case_ : int = directory / "tar_file_with_sym_link.tar" os.symlink(".." , directory / "subdir" , target_is_directory=lowerCAmelCase_ ) with tarfile.TarFile(lowerCAmelCase_ , "w" ) as f: f.add(str(directory / "subdir" ) , arcname="subdir" ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( "insecure_tar_file, error_log" , [("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")] , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Optional[int] , lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: Optional[Any] , lowerCAmelCase_: Optional[int] , lowerCAmelCase_: str , lowerCAmelCase_: List[Any] ): snake_case_ : Dict = { "tar_file_with_dot_dot": tar_file_with_dot_dot, "tar_file_with_sym_link": tar_file_with_sym_link, } snake_case_ : List[Any] = insecure_tar_files[insecure_tar_file] snake_case_ : Optional[Any] = tmp_path / "extracted" TarExtractor.extract(lowerCAmelCase_ , lowerCAmelCase_ ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple ): # We should have less false positives than zipfile.is_zipfile # We do that by checking only the magic number snake_case_ : Tuple = tmpdir / "not_a_zip_file" # From: https://github.com/python/cpython/pull/5053 snake_case_ : List[str] = ( b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00" b"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I" b"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07" b"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82" ) with not_a_zip_file.open("wb" ) as f: f.write(lowerCAmelCase_ ) assert zipfile.is_zipfile(str(lowerCAmelCase_ ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(lowerCAmelCase_ ) # but we're right
666
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
1
class snake_case__ : def __init__( self : Dict , A__ : str , A__ : Tuple , A__ : Union[str, Any] ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = None snake_case_ : Tuple = None snake_case_ : Optional[int] = graph self._normalize_graph(A__ , A__ ) snake_case_ : Union[str, Any] = len(A__ ) snake_case_ : Dict = None def UpperCAmelCase__ ( self : Any , A__ : List[str] , A__ : List[Any] ) -> int: '''simple docstring''' if sources is int: snake_case_ : List[str] = [sources] if sinks is int: snake_case_ : Tuple = [sinks] if len(A__ ) == 0 or len(A__ ) == 0: return snake_case_ : List[Any] = sources[0] snake_case_ : List[str] = sinks[0] # make fake vertex if there are more # than one source or sink if len(A__ ) > 1 or len(A__ ) > 1: snake_case_ : Optional[int] = 0 for i in sources: max_input_flow += sum(self.graph[i] ) snake_case_ : List[Any] = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: snake_case_ : Union[str, Any] = max_input_flow snake_case_ : Optional[int] = 0 snake_case_ : int = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: snake_case_ : Any = max_input_flow snake_case_ : int = size - 1 def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before." ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase__ ( self : Optional[Any] , A__ : Tuple ) -> Dict: '''simple docstring''' snake_case_ : int = algorithm(self ) class snake_case__ : def __init__( self : List[Any] , A__ : Dict ) -> List[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = flow_network snake_case_ : str = flow_network.verticesCount snake_case_ : Dict = flow_network.sourceIndex snake_case_ : List[Any] = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that snake_case_ : Optional[int] = flow_network.graph snake_case_ : Tuple = False def UpperCAmelCase__ ( self : List[Any] ) -> int: '''simple docstring''' if not self.executed: self._algorithm() snake_case_ : Optional[int] = True def UpperCAmelCase__ ( self : List[Any] ) -> int: '''simple docstring''' pass class snake_case__ ( _UpperCamelCase ): def __init__( self : List[Any] , A__ : Optional[int] ) -> int: '''simple docstring''' super().__init__(A__ ) # use this to save your result snake_case_ : Tuple = -1 def UpperCAmelCase__ ( self : int ) -> Dict: '''simple docstring''' if not self.executed: raise Exception("You should execute algorithm before using its result!" ) return self.maximum_flow class snake_case__ ( _UpperCamelCase ): def __init__( self : List[str] , A__ : Optional[int] ) -> int: '''simple docstring''' super().__init__(A__ ) snake_case_ : Dict = [[0] * self.verticies_count for i in range(self.verticies_count )] snake_case_ : Dict = [0] * self.verticies_count snake_case_ : str = [0] * self.verticies_count def UpperCAmelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' snake_case_ : Optional[int] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule snake_case_ : str = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list snake_case_ : Optional[Any] = 0 while i < len(A__ ): snake_case_ : List[Any] = vertices_list[i] snake_case_ : Any = self.heights[vertex_index] self.process_vertex(A__ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(A__ ) ) snake_case_ : int = 0 else: i += 1 snake_case_ : Dict = sum(self.preflow[self.source_index] ) def UpperCAmelCase__ ( self : str , A__ : Union[str, Any] ) -> str: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(A__ , A__ ) self.relabel(A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , A__ : Any , A__ : Any ) -> Tuple: '''simple docstring''' snake_case_ : List[Any] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase__ ( self : List[Any] , A__ : int ) -> Any: '''simple docstring''' snake_case_ : Tuple = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): snake_case_ : int = self.heights[to_index] if min_height is not None: snake_case_ : Union[str, Any] = min_height + 1 if __name__ == "__main__": UpperCAmelCase = [0] UpperCAmelCase = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCAmelCase = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCAmelCase = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCAmelCase = flow_network.find_maximum_flow() print(F"maximum flow is {maximum_flow}")
666
from ...configuration_utils import PretrainedConfig UpperCAmelCase = { "google/tapas-base-finetuned-sqa": ( "https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json" ), "google/tapas-base-finetuned-wtq": ( "https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json" ), "google/tapas-base-finetuned-wikisql-supervised": ( "https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json" ), "google/tapas-base-finetuned-tabfact": ( "https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json" ), } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "tapas" def __init__( self : List[Any] , A__ : str=3_05_22 , A__ : Tuple=7_68 , A__ : List[Any]=12 , A__ : Optional[Any]=12 , A__ : Union[str, Any]=30_72 , A__ : Dict="gelu" , A__ : List[Any]=0.1 , A__ : str=0.1 , A__ : List[Any]=10_24 , A__ : Optional[int]=[3, 2_56, 2_56, 2, 2_56, 2_56, 10] , A__ : Union[str, Any]=0.02 , A__ : Tuple=1E-12 , A__ : Tuple=0 , A__ : Any=10.0 , A__ : List[str]=0 , A__ : List[str]=1.0 , A__ : Optional[Any]=None , A__ : Tuple=1.0 , A__ : Union[str, Any]=False , A__ : Any=None , A__ : Union[str, Any]=1.0 , A__ : int=1.0 , A__ : str=False , A__ : int=False , A__ : Optional[Any]="ratio" , A__ : str=None , A__ : int=None , A__ : Dict=64 , A__ : int=32 , A__ : Optional[Any]=False , A__ : List[str]=True , A__ : List[Any]=False , A__ : str=False , A__ : Any=True , A__ : Tuple=False , A__ : str=None , A__ : str=None , **A__ : List[str] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=A__ , **A__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) snake_case_ : int = vocab_size snake_case_ : int = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Optional[int] = hidden_act snake_case_ : Optional[int] = intermediate_size snake_case_ : str = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : Any = max_position_embeddings snake_case_ : List[Any] = type_vocab_sizes snake_case_ : str = initializer_range snake_case_ : Optional[Any] = layer_norm_eps # Fine-tuning task hyperparameters snake_case_ : Optional[int] = positive_label_weight snake_case_ : Dict = num_aggregation_labels snake_case_ : List[str] = aggregation_loss_weight snake_case_ : str = use_answer_as_supervision snake_case_ : int = answer_loss_importance snake_case_ : Any = use_normalized_answer_loss snake_case_ : int = huber_loss_delta snake_case_ : List[Any] = temperature snake_case_ : str = aggregation_temperature snake_case_ : List[str] = use_gumbel_for_cells snake_case_ : List[str] = use_gumbel_for_aggregation snake_case_ : Dict = average_approximation_function snake_case_ : List[str] = cell_selection_preference snake_case_ : Dict = answer_loss_cutoff snake_case_ : List[str] = max_num_rows snake_case_ : Union[str, Any] = max_num_columns snake_case_ : str = average_logits_per_cell snake_case_ : Union[str, Any] = select_one_column snake_case_ : Dict = allow_empty_column_selection snake_case_ : List[Any] = init_cell_selection_weights_to_zero snake_case_ : str = reset_position_index_per_cell snake_case_ : List[Any] = disable_per_token_loss # Aggregation hyperparameters snake_case_ : List[str] = aggregation_labels snake_case_ : Union[str, Any] = no_aggregation_label_index if isinstance(self.aggregation_labels , A__ ): snake_case_ : Optional[int] = {int(A__ ): v for k, v in aggregation_labels.items()}
666
1
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging UpperCAmelCase = logging.get_logger(__name__) class snake_case__ : _SCREAMING_SNAKE_CASE : str _SCREAMING_SNAKE_CASE : str = None @staticmethod def UpperCAmelCase__ ( ) -> Optional[int]: '''simple docstring''' raise NotImplementedError def UpperCAmelCase__ ( self : List[str] , A__ : Union[str, Any] , A__ : int , A__ : str , **A__ : Any ) -> Tuple: '''simple docstring''' raise NotImplementedError def UpperCAmelCase__ ( self : Union[str, Any] , A__ : Optional[int] ) -> Any: '''simple docstring''' raise NotImplementedError def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' if not self.is_available(): raise RuntimeError( f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}." ) @classmethod def UpperCAmelCase__ ( cls : Dict ) -> Any: '''simple docstring''' return f"`pip install {cls.pip_package or cls.name}`" class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : int = "optuna" @staticmethod def UpperCAmelCase__ ( ) -> List[str]: '''simple docstring''' return is_optuna_available() def UpperCAmelCase__ ( self : Tuple , A__ : List[Any] , A__ : int , A__ : str , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return run_hp_search_optuna(A__ , A__ , A__ , **A__ ) def UpperCAmelCase__ ( self : Optional[int] , A__ : Optional[Any] ) -> Any: '''simple docstring''' return default_hp_space_optuna(A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = "ray" _SCREAMING_SNAKE_CASE : Dict = "'ray[tune]'" @staticmethod def UpperCAmelCase__ ( ) -> Any: '''simple docstring''' return is_ray_available() def UpperCAmelCase__ ( self : List[Any] , A__ : List[str] , A__ : int , A__ : str , **A__ : List[str] ) -> int: '''simple docstring''' return run_hp_search_ray(A__ , A__ , A__ , **A__ ) def UpperCAmelCase__ ( self : List[Any] , A__ : List[Any] ) -> str: '''simple docstring''' return default_hp_space_ray(A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = "sigopt" @staticmethod def UpperCAmelCase__ ( ) -> Tuple: '''simple docstring''' return is_sigopt_available() def UpperCAmelCase__ ( self : Any , A__ : Any , A__ : int , A__ : str , **A__ : List[Any] ) -> str: '''simple docstring''' return run_hp_search_sigopt(A__ , A__ , A__ , **A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , A__ : Optional[int] ) -> Any: '''simple docstring''' return default_hp_space_sigopt(A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : int = "wandb" @staticmethod def UpperCAmelCase__ ( ) -> int: '''simple docstring''' return is_wandb_available() def UpperCAmelCase__ ( self : Optional[Any] , A__ : Any , A__ : int , A__ : str , **A__ : str ) -> str: '''simple docstring''' return run_hp_search_wandb(A__ , A__ , A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : Optional[int] ) -> str: '''simple docstring''' return default_hp_space_wandb(A__ ) UpperCAmelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def SCREAMING_SNAKE_CASE_ ( ): snake_case_ : Any = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCAmelCase_ ) > 0: snake_case_ : Optional[Any] = available_backends[0].name if len(lowerCAmelCase_ ) > 1: logger.info( f"{len(lowerCAmelCase_ )} hyperparameter search backends available. Using {name} as the default." ) return name raise RuntimeError( "No hyperparameter search backend available.\n" + "\n".join( f" - To install {backend.name} run {backend.pip_install()}" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
666
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class snake_case__ ( datasets.BeamBasedBuilder ): def UpperCAmelCase__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"content": datasets.Value("string" )} ) , supervised_keys=A__ , ) def UpperCAmelCase__ ( self : Optional[Any] , A__ : str , A__ : str ) -> Optional[int]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_dummy_examples()} )] def UpperCAmelCase__ ( self : int , A__ : Optional[int] , A__ : Dict ) -> Optional[Any]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) class snake_case__ ( datasets.BeamBasedBuilder ): def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) , supervised_keys=A__ , ) def UpperCAmelCase__ ( self : Any , A__ : List[str] , A__ : str ) -> Optional[int]: '''simple docstring''' return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_nested_examples()} ) ] def UpperCAmelCase__ ( self : List[Any] , A__ : List[str] , A__ : Optional[int] ) -> List[str]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(A__ ) def SCREAMING_SNAKE_CASE_ ( ): return [(i, {"content": content}) for i, content in enumerate(["foo", "bar", "foobar"] )] def SCREAMING_SNAKE_CASE_ ( ): return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["foo", "bar", "foobar"] )] class snake_case__ ( _UpperCamelCase ): @require_beam def UpperCAmelCase__ ( self : str ) -> List[str]: '''simple docstring''' snake_case_ : Union[str, Any] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : Dict = DummyBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) snake_case_ : Optional[int] = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) self.assertDictEqual(dset["train"][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def UpperCAmelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' import apache_beam as beam snake_case_ : Tuple = beam.io.parquetio.WriteToParquet snake_case_ : Union[str, Any] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : List[Any] = DummyBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) with patch("apache_beam.io.parquetio.WriteToParquet" ) as write_parquet_mock: snake_case_ : int = partial(A__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertTrue( os.path.exists( os.path.join( A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) snake_case_ : Optional[Any] = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["train"]["content"] ) , sorted(["foo", "bar", "foobar"] ) ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : Tuple = DummyBeamDataset(cache_dir=A__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case_ : List[str] = NestedBeamDataset(cache_dir=A__ , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(A__ , builder.name , "default" , "0.0.0" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) ) snake_case_ : int = builder.as_dataset() self.assertEqual(dset["train"].num_rows , A__ ) self.assertEqual(dset["train"].info.splits["train"].num_examples , A__ ) self.assertDictEqual(dset["train"][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(A__ , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset
666
1
UpperCAmelCase = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, } UpperCAmelCase = { "km/h": 1.0, "m/s": 0.277777778, "mph": 0.621371192, "knot": 0.539956803, } def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: float , lowerCAmelCase_: str , lowerCAmelCase_: str ): if unit_to not in speed_chart or unit_from not in speed_chart_inverse: snake_case_ : Union[str, Any] = ( f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" f"Valid values are: {', '.join(lowerCAmelCase_ )}" ) raise ValueError(lowerCAmelCase_ ) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to] , 3 ) if __name__ == "__main__": import doctest doctest.testmod()
666
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple ): class snake_case__ : def __init__( self : Any , A__ : List[str] ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = metric_id class snake_case__ : _SCREAMING_SNAKE_CASE : List[str] = [MetricMock(_UpperCamelCase ) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: '''simple docstring''' return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple , lowerCAmelCase_: int , lowerCAmelCase_: List[Any] , lowerCAmelCase_: Any , lowerCAmelCase_: List[str] ): if "tmp_path" in args: snake_case_ : List[Any] = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase_ , match="https://huggingface.co/docs/evaluate" ): func(*lowerCAmelCase_ )
666
1
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] ): # This function is recursive snake_case_ : int = len(lowerCAmelCase_ ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else snake_case_ : Any = array[0] snake_case_ : List[str] = False snake_case_ : Union[str, Any] = 1 snake_case_ : list[int] = [] while not is_found and i < array_length: if array[i] < pivot: snake_case_ : Tuple = True snake_case_ : Dict = [element for element in array[i:] if element >= array[i]] snake_case_ : Any = longest_subsequence(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > len(lowerCAmelCase_ ): snake_case_ : Optional[int] = temp_array else: i += 1 snake_case_ : Any = [element for element in array[1:] if element >= pivot] snake_case_ : Dict = [pivot, *longest_subsequence(lowerCAmelCase_ )] if len(lowerCAmelCase_ ) > len(lowerCAmelCase_ ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
666
from __future__ import annotations import bisect def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): if hi < 0: snake_case_ : Any = len(lowerCAmelCase_ ) while lo < hi: snake_case_ : List[Any] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: snake_case_ : Tuple = mid + 1 else: snake_case_ : Dict = mid return lo def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): if hi < 0: snake_case_ : Optional[Any] = len(lowerCAmelCase_ ) while lo < hi: snake_case_ : Union[str, Any] = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: snake_case_ : Optional[Any] = mid + 1 else: snake_case_ : Tuple = mid return lo def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): sorted_collection.insert(bisect_left(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int = 0 , lowerCAmelCase_: int = -1 ): sorted_collection.insert(bisect_right(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int ): snake_case_ : Dict = 0 snake_case_ : Tuple = len(lowerCAmelCase_ ) - 1 while left <= right: snake_case_ : int = left + (right - left) // 2 snake_case_ : Optional[Any] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: snake_case_ : Optional[Any] = midpoint - 1 else: snake_case_ : Optional[int] = midpoint + 1 return None def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int ): snake_case_ : Optional[int] = bisect.bisect_left(lowerCAmelCase_ , lowerCAmelCase_ ) if index != len(lowerCAmelCase_ ) and sorted_collection[index] == item: return index return None def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int] , lowerCAmelCase_: int , lowerCAmelCase_: int , lowerCAmelCase_: int ): if right < left: return None snake_case_ : List[Any] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , midpoint - 1 ) else: return binary_search_by_recursion(lowerCAmelCase_ , lowerCAmelCase_ , midpoint + 1 , lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = input("Enter numbers separated by comma:\n").strip() UpperCAmelCase = sorted(int(item) for item in user_input.split(",")) UpperCAmelCase = int(input("Enter a single number to be found in the list:\n")) UpperCAmelCase = binary_search(collection, target) if result is None: print(F"{target} was not found in {collection}.") else: print(F"{target} was found at position {result} in {collection}.")
666
1
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) set_seed(7_7_0) UpperCAmelCase = { "c_attn": "att_proj", "c_proj": "out_proj", "c_fc": "in_proj", "transformer.": "", "h.": "layers.", "ln_1": "layernorm_1", "ln_2": "layernorm_2", "ln_f": "layernorm_final", "wpe": "position_embeds_layer", "wte": "input_embeds_layer", } UpperCAmelCase = { "text_small": { "repo_id": "suno/bark", "file_name": "text.pt", }, "coarse_small": { "repo_id": "suno/bark", "file_name": "coarse.pt", }, "fine_small": { "repo_id": "suno/bark", "file_name": "fine.pt", }, "text": { "repo_id": "suno/bark", "file_name": "text_2.pt", }, "coarse": { "repo_id": "suno/bark", "file_name": "coarse_2.pt", }, "fine": { "repo_id": "suno/bark", "file_name": "fine_2.pt", }, } UpperCAmelCase = os.path.dirname(os.path.abspath(__file__)) UpperCAmelCase = os.path.join(os.path.expanduser("~"), ".cache") UpperCAmelCase = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: List[str]=False ): snake_case_ : Union[str, Any] = model_type if use_small: key += "_small" return os.path.join(lowerCAmelCase_ , REMOTE_MODEL_PATHS[key]["file_name"] ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: List[str] ): os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) hf_hub_download(repo_id=lowerCAmelCase_ , filename=lowerCAmelCase_ , local_dir=lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: Dict , lowerCAmelCase_: List[str]=False , lowerCAmelCase_: Dict="text" ): if model_type == "text": snake_case_ : int = BarkSemanticModel snake_case_ : str = BarkSemanticConfig snake_case_ : Optional[Any] = BarkSemanticGenerationConfig elif model_type == "coarse": snake_case_ : str = BarkCoarseModel snake_case_ : Optional[int] = BarkCoarseConfig snake_case_ : Any = BarkCoarseGenerationConfig elif model_type == "fine": snake_case_ : Optional[int] = BarkFineModel snake_case_ : Tuple = BarkFineConfig snake_case_ : List[str] = BarkFineGenerationConfig else: raise NotImplementedError() snake_case_ : Optional[Any] = f"{model_type}_small" if use_small else model_type snake_case_ : Any = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(lowerCAmelCase_ ): logger.info(f"{model_type} model not found, downloading into `{CACHE_DIR}`." ) _download(model_info["repo_id"] , model_info["file_name"] ) snake_case_ : Any = torch.load(lowerCAmelCase_ , map_location=lowerCAmelCase_ ) # this is a hack snake_case_ : Union[str, Any] = checkpoint["model_args"] if "input_vocab_size" not in model_args: snake_case_ : str = model_args["vocab_size"] snake_case_ : Union[str, Any] = model_args["vocab_size"] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments snake_case_ : Union[str, Any] = model_args.pop("n_head" ) snake_case_ : int = model_args.pop("n_embd" ) snake_case_ : Any = model_args.pop("n_layer" ) snake_case_ : List[str] = ConfigClass(**checkpoint["model_args"] ) snake_case_ : Optional[Any] = ModelClass(config=lowerCAmelCase_ ) snake_case_ : Tuple = GenerationConfigClass() snake_case_ : List[str] = model_generation_config snake_case_ : Optional[int] = checkpoint["model"] # fixup checkpoint snake_case_ : Optional[int] = "_orig_mod." for k, v in list(state_dict.items() ): if k.startswith(lowerCAmelCase_ ): # replace part of the key with corresponding layer name in HF implementation snake_case_ : Tuple = k[len(lowerCAmelCase_ ) :] for old_layer_name in new_layer_name_dict: snake_case_ : int = new_k.replace(lowerCAmelCase_ , new_layer_name_dict[old_layer_name] ) snake_case_ : int = state_dict.pop(lowerCAmelCase_ ) snake_case_ : Optional[int] = set(state_dict.keys() ) - set(model.state_dict().keys() ) snake_case_ : str = {k for k in extra_keys if not k.endswith(".attn.bias" )} snake_case_ : Any = set(model.state_dict().keys() ) - set(state_dict.keys() ) snake_case_ : List[Any] = {k for k in missing_keys if not k.endswith(".attn.bias" )} if len(lowerCAmelCase_ ) != 0: raise ValueError(f"extra keys found: {extra_keys}" ) if len(lowerCAmelCase_ ) != 0: raise ValueError(f"missing keys: {missing_keys}" ) model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) snake_case_ : str = model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) snake_case_ : Union[str, Any] = checkpoint["best_val_loss"].item() logger.info(f"model loaded: {round(n_params/1e6 , 1 )}M params, {round(lowerCAmelCase_ , 3 )} loss" ) model.eval() model.to(lowerCAmelCase_ ) del checkpoint, state_dict return model def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] , lowerCAmelCase_: str=False , lowerCAmelCase_: int="text" ): if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() snake_case_ : int = "cpu" # do conversion on cpu snake_case_ : Optional[Any] = _get_ckpt_path(lowerCAmelCase_ , use_small=lowerCAmelCase_ ) snake_case_ : Tuple = _load_model(lowerCAmelCase_ , lowerCAmelCase_ , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) # load bark initial model snake_case_ : int = _bark_load_model(lowerCAmelCase_ , "cpu" , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) if model_type == "text": snake_case_ : Union[str, Any] = bark_model["model"] if model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) != bark_model.get_num_params(): raise ValueError("initial and new models don't have the same number of parameters" ) # check if same output as the bark model snake_case_ : Optional[Any] = 5 snake_case_ : Optional[int] = 1_0 if model_type in ["text", "coarse"]: snake_case_ : Optional[Any] = torch.randint(2_5_6 , (batch_size, sequence_length) , dtype=torch.int ) snake_case_ : str = bark_model(lowerCAmelCase_ )[0] snake_case_ : Tuple = model(lowerCAmelCase_ ) # take last logits snake_case_ : List[str] = output_new_model_total.logits[:, [-1], :] else: snake_case_ : Optional[int] = 3 snake_case_ : str = 8 snake_case_ : List[str] = torch.randint(2_5_6 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) snake_case_ : Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Union[str, Any] = bark_model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("initial and new outputs don't have the same shape" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("initial and new outputs are not equal" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple , lowerCAmelCase_: List[str] , lowerCAmelCase_: Any , lowerCAmelCase_: List[Any] , lowerCAmelCase_: int , lowerCAmelCase_: Optional[Any] , ): snake_case_ : Optional[Any] = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkSemanticConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = BarkCoarseConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[str] = BarkFineConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = EncodecConfig.from_pretrained("facebook/encodec_24khz" ) snake_case_ : List[str] = BarkSemanticModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkCoarseModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Tuple = BarkFineModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_24khz" ) snake_case_ : Tuple = BarkConfig.from_sub_model_configs( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : List[Any] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) snake_case_ : Optional[int] = BarkModel(lowerCAmelCase_ ) snake_case_ : int = semantic snake_case_ : List[str] = coarseAcoustic snake_case_ : str = fineAcoustic snake_case_ : Optional[Any] = codec snake_case_ : Any = bark_generation_config Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) bark.save_pretrained(lowerCAmelCase_ , repo_id=lowerCAmelCase_ , push_to_hub=lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") UpperCAmelCase = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
666
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( _UpperCamelCase ): def __init__( self : Union[str, Any] , A__ : VQModel , A__ : UNetaDModel , A__ : DDIMScheduler ) -> List[Any]: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : str , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : float = 0.0 , A__ : int = 50 , A__ : Optional[str] = "pil" , A__ : bool = True , **A__ : Optional[Any] , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' snake_case_ : Optional[int] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=A__ , ) snake_case_ : List[Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ : Any = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(A__ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature snake_case_ : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ : List[Any] = {} if accepts_eta: snake_case_ : int = eta for t in self.progress_bar(self.scheduler.timesteps ): snake_case_ : Union[str, Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual snake_case_ : Dict = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case_ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VAE snake_case_ : int = self.vqvae.decode(A__ ).sample snake_case_ : Dict = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ : Optional[int] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
666
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase = { "configuration_clipseg": [ "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig", ], "processing_clipseg": ["CLIPSegProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPSegModel", "CLIPSegPreTrainedModel", "CLIPSegTextModel", "CLIPSegVisionModel", "CLIPSegForImageSegmentation", ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
from decimal import Decimal, getcontext from math import ceil, factorial def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) snake_case_ : List[str] = precision snake_case_ : Union[str, Any] = ceil(precision / 1_4 ) snake_case_ : List[str] = 4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt() snake_case_ : str = 1 snake_case_ : List[str] = 1_3_5_9_1_4_0_9 snake_case_ : str = Decimal(lowerCAmelCase_ ) for k in range(1 , lowerCAmelCase_ ): snake_case_ : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(lowerCAmelCase_ ) ** 3) linear_term += 5_4_5_1_4_0_1_3_4 exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": UpperCAmelCase = 5_0 print(F"The first {n} digits of pi is: {pi(n)}")
666
1
from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class snake_case__ ( _UpperCamelCase ): def __init__( self : int , A__ : Optional[NestedDataStructureLike[PathLike]] = None , A__ : Optional[NamedSplit] = None , A__ : Optional[Features] = None , A__ : str = None , A__ : bool = False , A__ : bool = False , A__ : Optional[int] = None , **A__ : Optional[Any] , ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = path_or_paths snake_case_ : Any = split if split or isinstance(A__ , A__ ) else "train" snake_case_ : List[str] = features snake_case_ : Optional[int] = cache_dir snake_case_ : Optional[int] = keep_in_memory snake_case_ : Any = streaming snake_case_ : Any = num_proc snake_case_ : List[str] = kwargs @abstractmethod def UpperCAmelCase__ ( self : int ) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]: '''simple docstring''' pass class snake_case__ ( _UpperCamelCase ): def __init__( self : Optional[int] , A__ : Optional[Features] = None , A__ : str = None , A__ : bool = False , A__ : bool = False , A__ : Optional[int] = None , **A__ : Optional[Any] , ) -> Any: '''simple docstring''' snake_case_ : Any = features snake_case_ : str = cache_dir snake_case_ : Any = keep_in_memory snake_case_ : int = streaming snake_case_ : Union[str, Any] = num_proc snake_case_ : Any = kwargs @abstractmethod def UpperCAmelCase__ ( self : Optional[int] ) -> Union[Dataset, IterableDataset]: '''simple docstring''' pass
666
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int = 1_0_0_0 ): snake_case_ ,snake_case_ : List[str] = 1, 1 snake_case_ : List[str] = 2 while True: snake_case_ : Tuple = 0 snake_case_ : Union[str, Any] = fa + fa snake_case_ ,snake_case_ : str = fa, f index += 1 for _ in str(lowerCAmelCase_ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
666
1
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: str ): def get_matched_characters(lowerCAmelCase_: str , lowerCAmelCase_: str ) -> str: snake_case_ : Tuple = [] snake_case_ : Tuple = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): snake_case_ : str = int(max(0 , i - limit ) ) snake_case_ : Optional[int] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCAmelCase_ ) snake_case_ : List[Any] = f"{_stra[0:_stra.index(lowerCAmelCase_ )]} {_stra[_stra.index(lowerCAmelCase_ ) + 1:]}" return "".join(lowerCAmelCase_ ) # matching characters snake_case_ : List[Any] = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : int = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = len(lowerCAmelCase_ ) # transposition snake_case_ : List[str] = ( len([(ca, ca) for ca, ca in zip(lowerCAmelCase_ , lowerCAmelCase_ ) if ca != ca] ) // 2 ) if not match_count: snake_case_ : str = 0.0 else: snake_case_ : Optional[Any] = ( 1 / 3 * ( match_count / len(lowerCAmelCase_ ) + match_count / len(lowerCAmelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters snake_case_ : Optional[Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
666
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[int | float] , lowerCAmelCase_: int , lowerCAmelCase_: int ): if len(lowerCAmelCase_ ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(lowerCAmelCase_ ) or left < -len(lowerCAmelCase_ ) or right >= len(lowerCAmelCase_ ) or right < -len(lowerCAmelCase_ ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] snake_case_ : List[Any] = (left + right) >> 1 # the middle snake_case_ : Dict = find_max(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # find max in range[left, mid] snake_case_ : int = find_max(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
666
1
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging UpperCAmelCase = logging.get_logger(__name__) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = ["input_features", "attention_mask"] def __init__( self : Optional[int] , A__ : List[Any]=80 , A__ : List[str]=1_60_00 , A__ : Any=0.0 , A__ : str=10 , A__ : Any=25 , A__ : str="hamming_window" , A__ : List[str]=3_2768.0 , A__ : Any=0.97 , A__ : Dict=1.0 , A__ : int=True , A__ : int=True , A__ : List[Any]=False , **A__ : int , ) -> Tuple: '''simple docstring''' super().__init__(feature_size=A__ , sampling_rate=A__ , padding_value=A__ , **A__ ) snake_case_ : List[Any] = feature_size snake_case_ : Optional[Any] = sampling_rate snake_case_ : List[Any] = padding_value snake_case_ : Tuple = hop_length snake_case_ : str = win_length snake_case_ : Optional[int] = frame_signal_scale snake_case_ : List[Any] = preemphasis_coeff snake_case_ : Union[str, Any] = mel_floor snake_case_ : Optional[int] = normalize_means snake_case_ : Optional[Any] = normalize_vars snake_case_ : str = win_function snake_case_ : List[str] = return_attention_mask snake_case_ : Optional[int] = win_length * sampling_rate // 10_00 snake_case_ : Optional[Any] = hop_length * sampling_rate // 10_00 snake_case_ : Optional[Any] = optimal_fft_length(self.sample_size ) snake_case_ : Union[str, Any] = (self.n_fft // 2) + 1 def UpperCAmelCase__ ( self : Any , A__ : np.array ) -> np.ndarray: '''simple docstring''' if self.win_function == "hamming_window": snake_case_ : str = window_function(window_length=self.sample_size , name=self.win_function , periodic=A__ ) else: snake_case_ : str = window_function(window_length=self.sample_size , name=self.win_function ) snake_case_ : str = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) snake_case_ : Union[str, Any] = spectrogram( one_waveform * self.frame_signal_scale , window=A__ , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=A__ , preemphasis=self.preemphasis_coeff , mel_filters=A__ , mel_floor=self.mel_floor , log_mel="log" , ) return msfc_features.T def UpperCAmelCase__ ( self : Any , A__ : Union[str, Any] , A__ : Optional[int] , A__ : Optional[int] ) -> Dict: '''simple docstring''' if self.normalize_means: snake_case_ : Any = x[:input_length].mean(axis=0 ) snake_case_ : List[str] = np.subtract(A__ , A__ ) if self.normalize_vars: snake_case_ : Tuple = x[:input_length].std(axis=0 ) snake_case_ : Optional[Any] = np.divide(A__ , A__ ) if input_length < x.shape[0]: snake_case_ : List[str] = padding_value # make sure array is in float32 snake_case_ : Optional[int] = x.astype(np.floataa ) return x def UpperCAmelCase__ ( self : str , A__ : List[np.ndarray] , A__ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' snake_case_ : Dict = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(A__ , A__ , self.padding_value ) for x, n in zip(A__ , A__ )] def __call__( self : Optional[Any] , A__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , A__ : Union[bool, str, PaddingStrategy] = False , A__ : Optional[int] = None , A__ : bool = False , A__ : Optional[int] = None , A__ : Optional[bool] = None , A__ : Optional[Union[str, TensorType]] = None , A__ : Optional[int] = None , **A__ : Union[str, Any] , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with" f" {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." ) snake_case_ : Optional[int] = isinstance(A__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"Only mono-channel audio is supported for input to {self}" ) snake_case_ : Optional[int] = is_batched_numpy or ( isinstance(A__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: snake_case_ : Union[str, Any] = [np.asarray(A__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(A__ , np.ndarray ): snake_case_ : Any = np.asarray(A__ , dtype=np.floataa ) elif isinstance(A__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): snake_case_ : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: snake_case_ : List[Any] = [raw_speech] # extract fbank features snake_case_ : Dict = [self._extract_mfsc_features(A__ ) for one_waveform in raw_speech] # convert into correct format for padding snake_case_ : Any = BatchFeature({"input_features": features} ) snake_case_ : Optional[int] = self.pad( A__ , padding=A__ , max_length=A__ , truncation=A__ , pad_to_multiple_of=A__ , return_attention_mask=A__ , **A__ , ) # make sure list is in array format snake_case_ : int = padded_inputs.get("input_features" ) if isinstance(input_features[0] , A__ ): snake_case_ : Optional[int] = [np.asarray(A__ , dtype=np.floataa ) for feature in input_features] snake_case_ : Union[str, Any] = padded_inputs.get("attention_mask" ) if attention_mask is not None: snake_case_ : Tuple = [np.asarray(A__ , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: snake_case_ : List[str] = ( np.array(A__ , dtype=np.intaa ) if self._get_padding_strategies(A__ , max_length=A__ ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) snake_case_ : int = self.normalize( padded_inputs["input_features"] , attention_mask=A__ ) if return_tensors is not None: snake_case_ : Optional[Any] = padded_inputs.convert_to_tensors(A__ ) return padded_inputs
666
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase = { "vocab_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/vocab.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/vocab.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/vocab.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json" ), }, "merges_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/merges.txt", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/merges.txt", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/merges.txt", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt" ), }, "tokenizer_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/tokenizer.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/tokenizer.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json", "roberta-base-openai-detector": ( "https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json" ), "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json" ), }, } UpperCAmelCase = { "roberta-base": 5_1_2, "roberta-large": 5_1_2, "roberta-large-mnli": 5_1_2, "distilroberta-base": 5_1_2, "roberta-base-openai-detector": 5_1_2, "roberta-large-openai-detector": 5_1_2, } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : int = ["input_ids", "attention_mask"] _SCREAMING_SNAKE_CASE : List[str] = RobertaTokenizer def __init__( self : Optional[int] , A__ : List[Any]=None , A__ : Optional[int]=None , A__ : List[str]=None , A__ : Dict="replace" , A__ : List[str]="<s>" , A__ : Optional[Any]="</s>" , A__ : List[str]="</s>" , A__ : List[Any]="<s>" , A__ : int="<unk>" , A__ : int="<pad>" , A__ : List[Any]="<mask>" , A__ : Any=False , A__ : Optional[int]=True , **A__ : Union[str, Any] , ) -> int: '''simple docstring''' super().__init__( A__ , A__ , tokenizer_file=A__ , errors=A__ , bos_token=A__ , eos_token=A__ , sep_token=A__ , cls_token=A__ , unk_token=A__ , pad_token=A__ , mask_token=A__ , add_prefix_space=A__ , trim_offsets=A__ , **A__ , ) snake_case_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , A__ ) != add_prefix_space: snake_case_ : List[Any] = getattr(A__ , pre_tok_state.pop("type" ) ) snake_case_ : Any = add_prefix_space snake_case_ : List[Any] = pre_tok_class(**A__ ) snake_case_ : Optional[int] = add_prefix_space snake_case_ : List[str] = "post_processor" snake_case_ : Tuple = getattr(self.backend_tokenizer , A__ , A__ ) if tokenizer_component_instance: snake_case_ : List[str] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: snake_case_ : str = tuple(state["sep"] ) if "cls" in state: snake_case_ : Tuple = tuple(state["cls"] ) snake_case_ : Tuple = False if state.get("add_prefix_space" , A__ ) != add_prefix_space: snake_case_ : Optional[Any] = add_prefix_space snake_case_ : str = True if state.get("trim_offsets" , A__ ) != trim_offsets: snake_case_ : Optional[int] = trim_offsets snake_case_ : List[Any] = True if changes_to_apply: snake_case_ : int = getattr(A__ , state.pop("type" ) ) snake_case_ : List[Any] = component_class(**A__ ) setattr(self.backend_tokenizer , A__ , A__ ) @property def UpperCAmelCase__ ( self : Optional[Any] ) -> str: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def UpperCAmelCase__ ( self : Tuple , A__ : Dict ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else value snake_case_ : Any = value def UpperCAmelCase__ ( self : int , *A__ : Optional[Any] , **A__ : int ) -> BatchEncoding: '''simple docstring''' snake_case_ : Optional[Any] = kwargs.get("is_split_into_words" , A__ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*A__ , **A__ ) def UpperCAmelCase__ ( self : Union[str, Any] , *A__ : Any , **A__ : List[Any] ) -> BatchEncoding: '''simple docstring''' snake_case_ : Optional[int] = kwargs.get("is_split_into_words" , A__ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' snake_case_ : Optional[Any] = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ ) def UpperCAmelCase__ ( self : int , A__ : List[str] , A__ : Union[str, Any]=None ) -> Any: '''simple docstring''' snake_case_ : List[str] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCAmelCase__ ( self : Dict , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' snake_case_ : str = [self.sep_token_id] snake_case_ : 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 + sep + token_ids_a + sep ) * [0]
666
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class snake_case__ : def __init__( self : Union[str, Any] , A__ : Dict , A__ : Optional[int]=13 , A__ : Optional[int]=7 , A__ : Optional[Any]=True , A__ : Any=True , A__ : int=True , A__ : List[Any]=True , A__ : List[Any]=99 , A__ : Dict=32 , A__ : Tuple=2 , A__ : Optional[int]=4 , A__ : str=37 , A__ : Tuple="gelu" , A__ : Optional[int]=0.1 , A__ : int=0.1 , A__ : int=5_12 , A__ : int=16 , A__ : Union[str, Any]=2 , A__ : Optional[Any]=0.02 , A__ : List[str]=3 , A__ : str=4 , A__ : Union[str, Any]=None , A__ : int=0 , ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = parent snake_case_ : Optional[int] = batch_size snake_case_ : Union[str, Any] = seq_length snake_case_ : List[str] = is_training snake_case_ : Optional[Any] = use_input_mask snake_case_ : List[Any] = use_token_type_ids snake_case_ : Optional[int] = use_labels snake_case_ : Tuple = vocab_size snake_case_ : Optional[int] = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Any = num_attention_heads snake_case_ : Any = intermediate_size snake_case_ : Any = hidden_act snake_case_ : Dict = hidden_dropout_prob snake_case_ : List[Any] = attention_probs_dropout_prob snake_case_ : Optional[int] = max_position_embeddings snake_case_ : int = type_vocab_size snake_case_ : Dict = type_sequence_label_size snake_case_ : List[str] = initializer_range snake_case_ : Union[str, Any] = num_labels snake_case_ : List[Any] = num_choices snake_case_ : str = scope snake_case_ : Dict = projection_dim def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: '''simple docstring''' snake_case_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ : Optional[Any] = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py snake_case_ : Dict = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ : Tuple = None if self.use_token_type_ids: snake_case_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ : str = None snake_case_ : Dict = None snake_case_ : List[Any] = None if self.use_labels: snake_case_ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A__ , initializer_range=self.initializer_range , ) snake_case_ : List[Any] = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : List[Any] , A__ : Union[str, Any] , A__ : Dict , A__ : List[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] , A__ : int ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[Any] = TFDPRContextEncoder(config=A__ ) snake_case_ : Dict = model(A__ , attention_mask=A__ , token_type_ids=A__ ) snake_case_ : Union[str, Any] = model(A__ , token_type_ids=A__ ) snake_case_ : Optional[Any] = model(A__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def UpperCAmelCase__ ( self : Any , A__ : Union[str, Any] , A__ : Union[str, Any] , A__ : Dict , A__ : int , A__ : str , A__ : Optional[Any] , A__ : List[Any] ) -> Dict: '''simple docstring''' snake_case_ : Union[str, Any] = TFDPRQuestionEncoder(config=A__ ) snake_case_ : Union[str, Any] = model(A__ , attention_mask=A__ , token_type_ids=A__ ) snake_case_ : List[Any] = model(A__ , token_type_ids=A__ ) snake_case_ : Optional[Any] = model(A__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def UpperCAmelCase__ ( self : Any , A__ : Union[str, Any] , A__ : str , A__ : Optional[Any] , A__ : List[str] , A__ : List[Any] , A__ : Optional[Any] , A__ : List[str] ) -> Any: '''simple docstring''' snake_case_ : List[Any] = TFDPRReader(config=A__ ) snake_case_ : Dict = model(A__ , attention_mask=A__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def UpperCAmelCase__ ( self : int ) -> Optional[int]: '''simple docstring''' snake_case_ : Dict = self.prepare_config_and_inputs() ( ( snake_case_ ) ,( snake_case_ ) ,( snake_case_ ) ,( snake_case_ ) ,( snake_case_ ) ,( snake_case_ ) ,( snake_case_ ) , ) : Optional[Any] = config_and_inputs snake_case_ : Optional[Any] = {"input_ids": input_ids} return config, inputs_dict @require_tf class snake_case__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE : str = False _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: '''simple docstring''' snake_case_ : Any = TFDPRModelTester(self ) snake_case_ : Optional[Any] = ConfigTester(self , config_class=A__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Any ) -> Any: '''simple docstring''' snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*A__ ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*A__ ) def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*A__ ) @slow def UpperCAmelCase__ ( self : str ) -> Dict: '''simple docstring''' for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : Union[str, Any] = TFDPRContextEncoder.from_pretrained(A__ ) self.assertIsNotNone(A__ ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : Union[str, Any] = TFDPRContextEncoder.from_pretrained(A__ ) self.assertIsNotNone(A__ ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained(A__ ) self.assertIsNotNone(A__ ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : List[str] = TFDPRReader.from_pretrained(A__ ) self.assertIsNotNone(A__ ) @require_tf class snake_case__ ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' snake_case_ : List[str] = TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base" ) snake_case_ : List[Any] = tf.constant( [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]] ) # [CLS] hello, is my dog cute? [SEP] snake_case_ : Tuple = model(A__ )[0] # embedding shape = (1, 768) # compare the actual values for a slice. snake_case_ : List[str] = tf.constant( [ [ 0.0323_6253, 0.1275_3335, 0.1681_8509, 0.0027_9786, 0.389_6933, 0.2426_4945, 0.217_8971, -0.0233_5227, -0.0848_1959, -0.1432_4117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
666
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = TFXLMRobertaModel.from_pretrained("jplu/tf-xlm-roberta-base" ) snake_case_ : Any = { "input_ids": tf.convert_to_tensor([[0, 26_46, 1_02_69, 83, 9_99_42, 2]] , dtype=tf.intaa ), # "My dog is cute" "attention_mask": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } snake_case_ : List[str] = model(A__ )["last_hidden_state"] snake_case_ : str = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , A__ ) # compare the actual values for a slice. snake_case_ : List[str] = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
666
1
import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] , lowerCAmelCase_: List[str] , lowerCAmelCase_: str , lowerCAmelCase_: Optional[int] ): # Initialise PyTorch model snake_case_ : List[str] = FunnelConfig.from_json_file(lowerCAmelCase_ ) print(f"Building PyTorch model from configuration: {config}" ) snake_case_ : Tuple = FunnelBaseModel(lowerCAmelCase_ ) if base_model else FunnelModel(lowerCAmelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_funnel(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not." ) UpperCAmelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
666
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging UpperCAmelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = ["pixel_values"] def __init__( self : Union[str, Any] , A__ : bool = True , A__ : Dict[str, int] = None , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : bool = True , A__ : Dict[str, int] = None , A__ : bool = True , A__ : Union[int, float] = 1 / 2_55 , A__ : bool = True , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : bool = True , **A__ : Optional[int] , ) -> None: '''simple docstring''' super().__init__(**A__ ) snake_case_ : str = size if size is not None else {"shortest_edge": 2_24} snake_case_ : Union[str, Any] = get_size_dict(A__ , default_to_square=A__ ) snake_case_ : List[Any] = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} snake_case_ : Dict = get_size_dict(A__ , default_to_square=A__ , param_name="crop_size" ) snake_case_ : str = do_resize snake_case_ : str = size snake_case_ : Optional[Any] = resample snake_case_ : Any = do_center_crop snake_case_ : Any = crop_size snake_case_ : str = do_rescale snake_case_ : Optional[Any] = rescale_factor snake_case_ : int = do_normalize snake_case_ : Optional[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN snake_case_ : List[str] = image_std if image_std is not None else OPENAI_CLIP_STD snake_case_ : int = do_convert_rgb def UpperCAmelCase__ ( self : Optional[int] , A__ : np.ndarray , A__ : Dict[str, int] , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[str] , ) -> np.ndarray: '''simple docstring''' snake_case_ : str = get_size_dict(A__ , default_to_square=A__ ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) snake_case_ : str = get_resize_output_image_size(A__ , size=size["shortest_edge"] , default_to_square=A__ ) return resize(A__ , size=A__ , resample=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Tuple , A__ : np.ndarray , A__ : Dict[str, int] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[Any] , ) -> np.ndarray: '''simple docstring''' snake_case_ : Optional[int] = get_size_dict(A__ ) if "height" not in size or "width" not in size: raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(A__ , size=(size["height"], size["width"]) , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Optional[Any] , A__ : np.ndarray , A__ : Union[int, float] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[str] , ) -> str: '''simple docstring''' return rescale(A__ , scale=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : Any , A__ : np.ndarray , A__ : Union[float, List[float]] , A__ : Union[float, List[float]] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Any , ) -> np.ndarray: '''simple docstring''' return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ ) def UpperCAmelCase__ ( self : List[Any] , A__ : ImageInput , A__ : bool = None , A__ : Dict[str, int] = None , A__ : PILImageResampling = None , A__ : bool = None , A__ : int = None , A__ : bool = None , A__ : float = None , A__ : bool = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : bool = None , A__ : Optional[Union[str, TensorType]] = None , A__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **A__ : Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' snake_case_ : List[Any] = do_resize if do_resize is not None else self.do_resize snake_case_ : Union[str, Any] = size if size is not None else self.size snake_case_ : Any = get_size_dict(A__ , param_name="size" , default_to_square=A__ ) snake_case_ : Optional[int] = resample if resample is not None else self.resample snake_case_ : int = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ : List[str] = crop_size if crop_size is not None else self.crop_size snake_case_ : Tuple = get_size_dict(A__ , param_name="crop_size" , default_to_square=A__ ) snake_case_ : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale snake_case_ : str = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ : List[Any] = do_normalize if do_normalize is not None else self.do_normalize snake_case_ : Any = image_mean if image_mean is not None else self.image_mean snake_case_ : List[str] = image_std if image_std is not None else self.image_std snake_case_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case_ : List[Any] = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: snake_case_ : Dict = [convert_to_rgb(A__ ) for image in images] # All transformations expect numpy arrays. snake_case_ : Dict = [to_numpy_array(A__ ) for image in images] if do_resize: snake_case_ : Dict = [self.resize(image=A__ , size=A__ , resample=A__ ) for image in images] if do_center_crop: snake_case_ : Tuple = [self.center_crop(image=A__ , size=A__ ) for image in images] if do_rescale: snake_case_ : str = [self.rescale(image=A__ , scale=A__ ) for image in images] if do_normalize: snake_case_ : int = [self.normalize(image=A__ , mean=A__ , std=A__ ) for image in images] snake_case_ : List[Any] = [to_channel_dimension_format(A__ , A__ ) for image in images] snake_case_ : Tuple = {"pixel_values": images} return BatchFeature(data=A__ , tensor_type=A__ )
666
1
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class snake_case__ ( _UpperCamelCase ): def __init__( self : Dict , A__ : Optional[int]=None , A__ : str=None , *A__ : Tuple , **A__ : int ) -> Union[str, Any]: '''simple docstring''' super().__init__(*A__ , **A__ ) if config is None: assert isinstance(self.model , A__ ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f" {self.model.__class__}" ) snake_case_ : Tuple = self.model.config else: snake_case_ : Optional[int] = config snake_case_ : Optional[Any] = data_args snake_case_ : Any = self.config.tgt_vocab_size if isinstance(self.config , A__ ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f"The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for" " padding.." ) if self.args.label_smoothing == 0: snake_case_ : Tuple = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss snake_case_ : Tuple = label_smoothed_nll_loss def UpperCAmelCase__ ( self : Optional[int] , A__ : int ) -> Tuple: '''simple docstring''' if self.optimizer is None: snake_case_ : Dict = ["bias", "LayerNorm.weight"] snake_case_ : Any = [ { "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], "weight_decay": self.args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], "weight_decay": 0.0, }, ] snake_case_ : List[Any] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: snake_case_ : Dict = Adafactor snake_case_ : List[Any] = {"scale_parameter": False, "relative_step": False} else: snake_case_ : Union[str, Any] = AdamW snake_case_ : List[str] = { "betas": (self.args.adam_betaa, self.args.adam_betaa), "eps": self.args.adam_epsilon, } snake_case_ : List[str] = self.args.learning_rate if self.sharded_ddp: snake_case_ : List[str] = OSS( params=A__ , optim=A__ , **A__ , ) else: snake_case_ : Any = optimizer_cls(A__ , **A__ ) if self.lr_scheduler is None: snake_case_ : List[str] = self._get_lr_scheduler(A__ ) else: # ignoring --lr_scheduler logger.warning("scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored." ) def UpperCAmelCase__ ( self : Dict , A__ : Dict ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": snake_case_ : Optional[Any] = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": snake_case_ : Optional[int] = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: snake_case_ : str = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=A__ ) return scheduler def UpperCAmelCase__ ( self : List[str] ) -> Optional[torch.utils.data.Sampler]: '''simple docstring''' if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def UpperCAmelCase__ ( self : Optional[int] , A__ : Optional[Any] , A__ : Optional[Any] , A__ : Optional[Any] ) -> Dict: '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token snake_case_ : Dict = model(**A__ , use_cache=A__ )[0] snake_case_ : int = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models snake_case_ ,snake_case_ : List[str] = model(**A__ , labels=A__ , use_cache=A__ )[:2] else: # compute label smoothed loss snake_case_ : List[str] = model(**A__ , use_cache=A__ )[0] snake_case_ : List[str] = torch.nn.functional.log_softmax(A__ , dim=-1 ) snake_case_ ,snake_case_ : str = self.loss_fn(A__ , A__ , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def UpperCAmelCase__ ( self : Any , A__ : List[str] , A__ : List[str] ) -> str: '''simple docstring''' snake_case_ : Dict = inputs.pop("labels" ) snake_case_ ,snake_case_ : Tuple = self._compute_loss(A__ , A__ , A__ ) return loss def UpperCAmelCase__ ( self : int , A__ : nn.Module , A__ : Dict[str, Union[torch.Tensor, Any]] , A__ : bool , A__ : Optional[List[str]] = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: '''simple docstring''' snake_case_ : Any = self._prepare_inputs(A__ ) snake_case_ : Optional[Any] = { "max_length": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, "num_beams": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: snake_case_ : Optional[Any] = self.model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , **A__ , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: snake_case_ : Any = self._pad_tensors_to_max_len(A__ , gen_kwargs["max_length"] ) snake_case_ : Dict = inputs.pop("labels" ) with torch.no_grad(): # compute loss on predict data snake_case_ ,snake_case_ : Optional[int] = self._compute_loss(A__ , A__ , A__ ) snake_case_ : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) snake_case_ : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: snake_case_ : str = self._pad_tensors_to_max_len(A__ , gen_kwargs["max_length"] ) return (loss, logits, labels) def UpperCAmelCase__ ( self : Tuple , A__ : Any , A__ : Optional[Any] ) -> int: '''simple docstring''' snake_case_ : int = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( "Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be" f" padded to `max_length`={max_length}" ) snake_case_ : List[str] = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) snake_case_ : str = tensor return padded_tensor
666
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: tuple[int, int] , lowerCAmelCase_: int ): snake_case_ ,snake_case_ : Dict = position snake_case_ : int = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] snake_case_ : Union[str, Any] = [] for position in positions: snake_case_ ,snake_case_ : Union[str, Any] = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(lowerCAmelCase_ ) return permissible_positions def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: list[list[int]] , lowerCAmelCase_: tuple[int, int] , lowerCAmelCase_: int ): if is_complete(lowerCAmelCase_ ): return True for position in get_valid_pos(lowerCAmelCase_ , len(lowerCAmelCase_ ) ): snake_case_ ,snake_case_ : Dict = position if board[y][x] == 0: snake_case_ : List[str] = curr + 1 if open_knight_tour_helper(lowerCAmelCase_ , lowerCAmelCase_ , curr + 1 ): return True snake_case_ : Dict = 0 return False def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Any = [[0 for i in range(lowerCAmelCase_ )] for j in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): snake_case_ : Optional[Any] = 1 if open_knight_tour_helper(lowerCAmelCase_ , (i, j) , 1 ): return board snake_case_ : Dict = 0 snake_case_ : str = f"Open Kight Tour cannot be performed on a board of size {n}" raise ValueError(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
666
1
UpperCAmelCase = "\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" UpperCAmelCase = [{"type": "code", "content": INSTALL_CONTENT}] UpperCAmelCase = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
666
from ...configuration_utils import PretrainedConfig class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = "bert-generation" def __init__( self : Optional[int] , A__ : List[Any]=5_03_58 , A__ : Any=10_24 , A__ : Any=24 , A__ : List[Any]=16 , A__ : List[Any]=40_96 , A__ : int="gelu" , A__ : List[str]=0.1 , A__ : List[str]=0.1 , A__ : str=5_12 , A__ : int=0.02 , A__ : Any=1E-12 , A__ : Optional[Any]=0 , A__ : List[str]=2 , A__ : Optional[int]=1 , A__ : str="absolute" , A__ : Any=True , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , **A__ ) snake_case_ : str = vocab_size snake_case_ : int = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = hidden_act snake_case_ : Tuple = intermediate_size snake_case_ : str = hidden_dropout_prob snake_case_ : Optional[Any] = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Optional[Any] = initializer_range snake_case_ : Optional[int] = layer_norm_eps snake_case_ : str = position_embedding_type snake_case_ : Dict = use_cache
666
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = 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") UpperCAmelCase = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) UpperCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str ): with open(lowerCAmelCase_ , "rb" ) as f: snake_case_ : Optional[Any] = Image.open(lowerCAmelCase_ ) return im.convert("RGB" ) @dataclass class snake_case__ : _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={ "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)." } , ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) _SCREAMING_SNAKE_CASE : Optional[str] = field(default=_UpperCamelCase , metadata={"help": "A folder containing the training data."} ) _SCREAMING_SNAKE_CASE : Optional[str] = field(default=_UpperCamelCase , metadata={"help": "A folder containing the validation data."} ) _SCREAMING_SNAKE_CASE : Optional[float] = field( default=0.1_5 , metadata={"help": "Percent to split off of train for validation."} ) _SCREAMING_SNAKE_CASE : Optional[int] = field( default=_UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) _SCREAMING_SNAKE_CASE : Optional[int] = field( default=_UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase__ ( self : Optional[Any] ) -> 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 snake_case__ : _SCREAMING_SNAKE_CASE : str = field( default="google/vit-base-patch16-224-in21k" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_UpperCamelCase )} , ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) _SCREAMING_SNAKE_CASE : Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} ) _SCREAMING_SNAKE_CASE : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) _SCREAMING_SNAKE_CASE : str = field(default=_UpperCamelCase , metadata={"help": "Name or path of preprocessor config."} ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Union[str, Any] ): snake_case_ : Any = torch.stack([example["pixel_values"] for example in examples] ) snake_case_ : List[Any] = torch.tensor([example["labels"] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def SCREAMING_SNAKE_CASE_ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. snake_case_ : str = 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. snake_case_ ,snake_case_ ,snake_case_ : Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case_ ,snake_case_ ,snake_case_ : str = 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" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() snake_case_ : Dict = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. snake_case_ : Union[str, Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case_ : Dict = 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: snake_case_ : Tuple = 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: snake_case_ : List[str] = {} if data_args.train_dir is not None: snake_case_ : Union[str, Any] = os.path.join(data_args.train_dir , "**" ) if data_args.validation_dir is not None: snake_case_ : int = os.path.join(data_args.validation_dir , "**" ) snake_case_ : Union[str, Any] = load_dataset( "imagefolder" , data_files=lowerCAmelCase_ , 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. snake_case_ : Tuple = None if "validation" in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , lowerCAmelCase_ ) and data_args.train_val_split > 0.0: snake_case_ : Union[str, Any] = dataset["train"].train_test_split(data_args.train_val_split ) snake_case_ : List[str] = split["train"] snake_case_ : Tuple = split["test"] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. snake_case_ : Tuple = dataset["train"].features["labels"].names snake_case_ ,snake_case_ : Optional[int] = {}, {} for i, label in enumerate(lowerCAmelCase_ ): snake_case_ : str = str(lowerCAmelCase_ ) snake_case_ : Dict = label # Load the accuracy metric from the datasets package snake_case_ : Any = 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(lowerCAmelCase_: List[Any] ): return metric.compute(predictions=np.argmax(p.predictions , axis=1 ) , references=p.label_ids ) snake_case_ : str = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(lowerCAmelCase_ ) , labelaid=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , 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 , ) snake_case_ : Any = AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) snake_case_ : Optional[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: snake_case_ : Optional[Any] = image_processor.size["shortest_edge"] else: snake_case_ : int = (image_processor.size["height"], image_processor.size["width"]) snake_case_ : str = Normalize(mean=image_processor.image_mean , std=image_processor.image_std ) snake_case_ : Optional[int] = Compose( [ RandomResizedCrop(lowerCAmelCase_ ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) snake_case_ : str = Compose( [ Resize(lowerCAmelCase_ ), CenterCrop(lowerCAmelCase_ ), ToTensor(), normalize, ] ) def train_transforms(lowerCAmelCase_: Optional[int] ): snake_case_ : Optional[int] = [ _train_transforms(pil_img.convert("RGB" ) ) for pil_img in example_batch["image"] ] return example_batch def val_transforms(lowerCAmelCase_: Optional[Any] ): snake_case_ : List[Any] = [_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: snake_case_ : List[str] = ( dataset["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(lowerCAmelCase_ ) 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: snake_case_ : List[Any] = ( dataset["validation"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(lowerCAmelCase_ ) # Initalize our trainer snake_case_ : Dict = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=dataset["train"] if training_args.do_train else None , eval_dataset=dataset["validation"] if training_args.do_eval else None , compute_metrics=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: snake_case_ : Any = None if training_args.resume_from_checkpoint is not None: snake_case_ : Dict = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case_ : List[Any] = last_checkpoint snake_case_ : Optional[int] = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() trainer.log_metrics("train" , train_result.metrics ) trainer.save_metrics("train" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: snake_case_ : Any = trainer.evaluate() trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) # Write model card and (optionally) push to hub snake_case_ : Optional[int] = { "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(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) if __name__ == "__main__": main()
666
import math def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Any = [] snake_case_ : List[str] = 2 snake_case_ : Optional[int] = int(math.sqrt(lowerCAmelCase_ ) ) # Size of every segment snake_case_ : str = [True] * (end + 1) snake_case_ : Any = [] while start <= end: if temp[start] is True: in_prime.append(lowerCAmelCase_ ) for i in range(start * start , end + 1 , lowerCAmelCase_ ): snake_case_ : Union[str, Any] = False start += 1 prime += in_prime snake_case_ : Dict = end + 1 snake_case_ : Dict = min(2 * end , lowerCAmelCase_ ) while low <= n: snake_case_ : Any = [True] * (high - low + 1) for each in in_prime: snake_case_ : Optional[Any] = math.floor(low / each ) * each if t < low: t += each for j in range(lowerCAmelCase_ , high + 1 , lowerCAmelCase_ ): snake_case_ : List[Any] = False for j in range(len(lowerCAmelCase_ ) ): if temp[j] is True: prime.append(j + low ) snake_case_ : int = high + 1 snake_case_ : Union[str, Any] = min(high + end , lowerCAmelCase_ ) return prime print(sieve(1_0**6))
666
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase = {"configuration_mra": ["MRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MraConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "MRA_PRETRAINED_MODEL_ARCHIVE_LIST", "MraForMaskedLM", "MraForMultipleChoice", "MraForQuestionAnswering", "MraForSequenceClassification", "MraForTokenClassification", "MraLayer", "MraModel", "MraPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure)
666
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self : List[str] , A__ : List[Any] , A__ : int=7 , A__ : Union[str, Any]=3 , A__ : List[str]=30 , A__ : Optional[int]=4_00 , A__ : Optional[Any]=True , A__ : Optional[int]=None , A__ : Optional[Any]=True , A__ : Any=[0.5, 0.5, 0.5] , A__ : int=[0.5, 0.5, 0.5] , A__ : Any=True , A__ : int=1 / 2_55 , A__ : List[str]=True , ) -> Dict: '''simple docstring''' snake_case_ : int = size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33} snake_case_ : Any = parent snake_case_ : Optional[int] = batch_size snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = min_resolution snake_case_ : List[Any] = max_resolution snake_case_ : Tuple = do_resize snake_case_ : Dict = size snake_case_ : Optional[Any] = do_normalize snake_case_ : int = image_mean snake_case_ : List[Any] = image_std snake_case_ : Tuple = do_rescale snake_case_ : Any = rescale_factor snake_case_ : Optional[int] = do_pad def UpperCAmelCase__ ( self : int ) -> List[str]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self : Optional[int] , A__ : Optional[int] , A__ : Any=False ) -> Optional[Any]: '''simple docstring''' if not batched: snake_case_ : Any = image_inputs[0] if isinstance(A__ , Image.Image ): snake_case_ ,snake_case_ : Dict = image.size else: snake_case_ ,snake_case_ : int = image.shape[1], image.shape[2] if w < h: snake_case_ : Dict = int(self.size["shortest_edge"] * h / w ) snake_case_ : Optional[int] = self.size["shortest_edge"] elif w > h: snake_case_ : Optional[int] = self.size["shortest_edge"] snake_case_ : str = int(self.size["shortest_edge"] * w / h ) else: snake_case_ : Optional[int] = self.size["shortest_edge"] snake_case_ : List[Any] = self.size["shortest_edge"] else: snake_case_ : str = [] for image in image_inputs: snake_case_ ,snake_case_ : Tuple = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) snake_case_ : List[Any] = max(A__ , key=lambda A__ : item[0] )[0] snake_case_ : int = max(A__ , key=lambda A__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = ConditionalDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Tuple ) -> Dict: '''simple docstring''' snake_case_ : List[str] = ConditionalDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Any ) -> Tuple: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , "image_mean" ) ) self.assertTrue(hasattr(A__ , "image_std" ) ) self.assertTrue(hasattr(A__ , "do_normalize" ) ) self.assertTrue(hasattr(A__ , "do_resize" ) ) self.assertTrue(hasattr(A__ , "size" ) ) def UpperCAmelCase__ ( self : List[str] ) -> Tuple: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 13_33} ) self.assertEqual(image_processor.do_pad , A__ ) snake_case_ : Optional[int] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A__ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , A__ ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: '''simple docstring''' pass def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : Optional[Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ ,snake_case_ : List[Any] = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) snake_case_ : int = image_processing(A__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : int ) -> Any: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , numpify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , np.ndarray ) # Test not batched input snake_case_ : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : List[str] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Optional[int] = image_processing(A__ , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : Dict = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : Tuple ) -> str: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , torchify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , torch.Tensor ) # Test not batched input snake_case_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : List[Any] = self.image_processor_tester.get_expected_values(A__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case_ : Any = image_processing(A__ , return_tensors="pt" ).pixel_values snake_case_ ,snake_case_ : int = self.image_processor_tester.get_expected_values(A__ , batched=A__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: snake_case_ : Optional[Any] = json.loads(f.read() ) snake_case_ : int = {"image_id": 3_97_69, "annotations": target} # encode them snake_case_ : Optional[int] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) snake_case_ : Any = image_processing(images=A__ , annotations=A__ , return_tensors="pt" ) # verify pixel values snake_case_ : List[Any] = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , A__ ) snake_case_ : List[str] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Tuple = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A__ ) ) # verify boxes snake_case_ : Any = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A__ ) snake_case_ : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : List[Any] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A__ ) ) # verify is_crowd snake_case_ : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A__ ) ) # verify class_labels snake_case_ : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A__ ) ) # verify orig_size snake_case_ : Any = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A__ ) ) # verify size snake_case_ : List[str] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A__ ) ) @slow def UpperCAmelCase__ ( self : int ) -> str: '''simple docstring''' snake_case_ : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: snake_case_ : Any = json.loads(f.read() ) snake_case_ : Optional[Any] = {"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target} snake_case_ : int = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them snake_case_ : Union[str, Any] = ConditionalDetrImageProcessor(format="coco_panoptic" ) snake_case_ : str = image_processing(images=A__ , annotations=A__ , masks_path=A__ , return_tensors="pt" ) # verify pixel values snake_case_ : int = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , A__ ) snake_case_ : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A__ , atol=1E-4 ) ) # verify area snake_case_ : Optional[int] = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A__ ) ) # verify boxes snake_case_ : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A__ ) snake_case_ : str = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A__ , atol=1E-3 ) ) # verify image_id snake_case_ : List[str] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A__ ) ) # verify is_crowd snake_case_ : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A__ ) ) # verify class_labels snake_case_ : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A__ ) ) # verify masks snake_case_ : Union[str, Any] = 82_28_73 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , A__ ) # verify orig_size snake_case_ : Dict = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A__ ) ) # verify size snake_case_ : str = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A__ ) )
666
1
from ...configuration_utils import PretrainedConfig class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = "bert-generation" def __init__( self : Optional[int] , A__ : List[Any]=5_03_58 , A__ : Any=10_24 , A__ : Any=24 , A__ : List[Any]=16 , A__ : List[Any]=40_96 , A__ : int="gelu" , A__ : List[str]=0.1 , A__ : List[str]=0.1 , A__ : str=5_12 , A__ : int=0.02 , A__ : Any=1E-12 , A__ : Optional[Any]=0 , A__ : List[str]=2 , A__ : Optional[int]=1 , A__ : str="absolute" , A__ : Any=True , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , **A__ ) snake_case_ : str = vocab_size snake_case_ : int = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = hidden_act snake_case_ : Tuple = intermediate_size snake_case_ : str = hidden_dropout_prob snake_case_ : Optional[Any] = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Optional[Any] = initializer_range snake_case_ : Optional[int] = layer_norm_eps snake_case_ : str = position_embedding_type snake_case_ : Dict = use_cache
666
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) UpperCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class snake_case__ : _SCREAMING_SNAKE_CASE : str = field( default=_UpperCamelCase , metadata={"help": "Model type selected in the list: " + ", ".join(_UpperCamelCase )} ) _SCREAMING_SNAKE_CASE : str = field( default=_UpperCamelCase , metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} ) _SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) _SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."} , ) _SCREAMING_SNAKE_CASE : int = field( default=6_4 , metadata={ "help": ( "The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length." ) } , ) _SCREAMING_SNAKE_CASE : int = field( default=3_0 , metadata={ "help": ( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ) } , ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"} ) _SCREAMING_SNAKE_CASE : bool = field( default=_UpperCamelCase , metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} ) _SCREAMING_SNAKE_CASE : float = field( default=0.0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) _SCREAMING_SNAKE_CASE : int = field( default=2_0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) _SCREAMING_SNAKE_CASE : int = field( default=0 , metadata={ "help": ( "language id of input for language-specific xlm models (see" " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)" ) } , ) _SCREAMING_SNAKE_CASE : int = field(default=1 , metadata={"help": "multiple threads for converting example to features"} ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = "train" _SCREAMING_SNAKE_CASE : Any = "dev" class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : SquadDataTrainingArguments _SCREAMING_SNAKE_CASE : List[SquadFeatures] _SCREAMING_SNAKE_CASE : Split _SCREAMING_SNAKE_CASE : bool def __init__( self : str , A__ : SquadDataTrainingArguments , A__ : PreTrainedTokenizer , A__ : Optional[int] = None , A__ : Union[str, Split] = Split.train , A__ : Optional[bool] = False , A__ : Optional[str] = None , A__ : Optional[str] = "pt" , ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = args snake_case_ : int = is_language_sensitive snake_case_ : int = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(A__ , A__ ): try: snake_case_ : List[str] = Split[mode] except KeyError: raise KeyError("mode is not a valid split name" ) snake_case_ : Tuple = mode # Load data features from cache or dataset file snake_case_ : Dict = "v2" if args.version_2_with_negative else "v1" snake_case_ : List[Any] = os.path.join( cache_dir if cache_dir is not None else args.data_dir , f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : List[Any] = cached_features_file + ".lock" with FileLock(A__ ): if os.path.exists(A__ ) and not args.overwrite_cache: snake_case_ : int = time.time() snake_case_ : List[Any] = torch.load(A__ ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. snake_case_ : Tuple = self.old_features["features"] snake_case_ : List[str] = self.old_features.get("dataset" , A__ ) snake_case_ : Tuple = self.old_features.get("examples" , A__ ) logger.info( f"Loading features from cached file {cached_features_file} [took %.3f s]" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in" " future run" ) else: if mode == Split.dev: snake_case_ : Tuple = self.processor.get_dev_examples(args.data_dir ) else: snake_case_ : Tuple = self.processor.get_train_examples(args.data_dir ) snake_case_ ,snake_case_ : Optional[Any] = squad_convert_examples_to_features( examples=self.examples , tokenizer=A__ , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=A__ , ) snake_case_ : Any = time.time() torch.save( {"features": self.features, "dataset": self.dataset, "examples": self.examples} , A__ , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" ) def __len__( self : str ) -> Dict: '''simple docstring''' return len(self.features ) def __getitem__( self : Optional[int] , A__ : Optional[int] ) -> Dict[str, torch.Tensor]: '''simple docstring''' snake_case_ : Any = self.features[i] snake_case_ : Optional[int] = torch.tensor(feature.input_ids , dtype=torch.long ) snake_case_ : Union[str, Any] = torch.tensor(feature.attention_mask , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.token_type_ids , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.cls_index , dtype=torch.long ) snake_case_ : str = torch.tensor(feature.p_mask , dtype=torch.float ) snake_case_ : str = torch.tensor(feature.is_impossible , dtype=torch.float ) snake_case_ : Optional[int] = { "input_ids": input_ids, "attention_mask": attention_mask, "token_type_ids": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"cls_index": cls_index, "p_mask": p_mask} ) if self.args.version_2_with_negative: inputs.update({"is_impossible": is_impossible} ) if self.is_language_sensitive: inputs.update({"langs": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: snake_case_ : Any = torch.tensor(feature.start_position , dtype=torch.long ) snake_case_ : List[Any] = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({"start_positions": start_positions, "end_positions": end_positions} ) return inputs
666
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "git_vision_model" def __init__( self : int , A__ : Union[str, Any]=7_68 , A__ : List[Any]=30_72 , A__ : Tuple=12 , A__ : Optional[Any]=12 , A__ : Optional[int]=3 , A__ : List[str]=2_24 , A__ : Dict=16 , A__ : int="quick_gelu" , A__ : Any=1E-5 , A__ : Tuple=0.0 , A__ : Optional[int]=0.02 , **A__ : List[str] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : str = intermediate_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Optional[int] = num_channels snake_case_ : Union[str, Any] = patch_size snake_case_ : List[str] = image_size snake_case_ : List[Any] = initializer_range snake_case_ : Any = attention_dropout snake_case_ : Any = layer_norm_eps snake_case_ : int = hidden_act @classmethod def UpperCAmelCase__ ( cls : List[Any] , A__ : Union[str, os.PathLike] , **A__ : Optional[int] ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(A__ ) snake_case_ ,snake_case_ : Tuple = cls.get_config_dict(A__ , **A__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("model_type" ) == "git": snake_case_ : 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(A__ , **A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = "git" def __init__( self : Any , A__ : List[str]=None , A__ : List[str]=3_05_22 , A__ : Tuple=7_68 , A__ : Tuple=6 , A__ : str=12 , A__ : Any=30_72 , A__ : List[str]="gelu" , A__ : int=0.1 , A__ : Dict=0.1 , A__ : Any=10_24 , A__ : Optional[Any]=0.02 , A__ : Optional[Any]=1E-12 , A__ : Dict=0 , A__ : Any="absolute" , A__ : Tuple=True , A__ : Any=False , A__ : Tuple=1_01 , A__ : Tuple=1_02 , A__ : List[Any]=None , **A__ : List[str] , ) -> int: '''simple docstring''' super().__init__(bos_token_id=A__ , eos_token_id=A__ , pad_token_id=A__ , **A__ ) if vision_config is None: snake_case_ : int = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values." ) snake_case_ : str = GitVisionConfig(**A__ ) snake_case_ : int = vocab_size snake_case_ : List[Any] = hidden_size snake_case_ : Tuple = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Any = hidden_act snake_case_ : Dict = intermediate_size snake_case_ : Any = hidden_dropout_prob snake_case_ : Any = attention_probs_dropout_prob snake_case_ : Union[str, Any] = max_position_embeddings snake_case_ : List[str] = initializer_range snake_case_ : List[str] = layer_norm_eps snake_case_ : Any = position_embedding_type snake_case_ : Union[str, Any] = use_cache snake_case_ : str = tie_word_embeddings snake_case_ : List[Any] = num_image_with_embedding snake_case_ : Dict = bos_token_id snake_case_ : int = eos_token_id def UpperCAmelCase__ ( self : Any ) -> int: '''simple docstring''' snake_case_ : Tuple = copy.deepcopy(self.__dict__ ) snake_case_ : Optional[int] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output
666
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "git_vision_model" def __init__( self : int , A__ : Union[str, Any]=7_68 , A__ : List[Any]=30_72 , A__ : Tuple=12 , A__ : Optional[Any]=12 , A__ : Optional[int]=3 , A__ : List[str]=2_24 , A__ : Dict=16 , A__ : int="quick_gelu" , A__ : Any=1E-5 , A__ : Tuple=0.0 , A__ : Optional[int]=0.02 , **A__ : List[str] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : str = intermediate_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Optional[int] = num_channels snake_case_ : Union[str, Any] = patch_size snake_case_ : List[str] = image_size snake_case_ : List[Any] = initializer_range snake_case_ : Any = attention_dropout snake_case_ : Any = layer_norm_eps snake_case_ : int = hidden_act @classmethod def UpperCAmelCase__ ( cls : List[Any] , A__ : Union[str, os.PathLike] , **A__ : Optional[int] ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(A__ ) snake_case_ ,snake_case_ : Tuple = cls.get_config_dict(A__ , **A__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("model_type" ) == "git": snake_case_ : 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(A__ , **A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = "git" def __init__( self : Any , A__ : List[str]=None , A__ : List[str]=3_05_22 , A__ : Tuple=7_68 , A__ : Tuple=6 , A__ : str=12 , A__ : Any=30_72 , A__ : List[str]="gelu" , A__ : int=0.1 , A__ : Dict=0.1 , A__ : Any=10_24 , A__ : Optional[Any]=0.02 , A__ : Optional[Any]=1E-12 , A__ : Dict=0 , A__ : Any="absolute" , A__ : Tuple=True , A__ : Any=False , A__ : Tuple=1_01 , A__ : Tuple=1_02 , A__ : List[Any]=None , **A__ : List[str] , ) -> int: '''simple docstring''' super().__init__(bos_token_id=A__ , eos_token_id=A__ , pad_token_id=A__ , **A__ ) if vision_config is None: snake_case_ : int = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values." ) snake_case_ : str = GitVisionConfig(**A__ ) snake_case_ : int = vocab_size snake_case_ : List[Any] = hidden_size snake_case_ : Tuple = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Any = hidden_act snake_case_ : Dict = intermediate_size snake_case_ : Any = hidden_dropout_prob snake_case_ : Any = attention_probs_dropout_prob snake_case_ : Union[str, Any] = max_position_embeddings snake_case_ : List[str] = initializer_range snake_case_ : List[str] = layer_norm_eps snake_case_ : Any = position_embedding_type snake_case_ : Union[str, Any] = use_cache snake_case_ : str = tie_word_embeddings snake_case_ : List[Any] = num_image_with_embedding snake_case_ : Dict = bos_token_id snake_case_ : int = eos_token_id def UpperCAmelCase__ ( self : Any ) -> int: '''simple docstring''' snake_case_ : Tuple = copy.deepcopy(self.__dict__ ) snake_case_ : Optional[int] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output
666
1
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( _UpperCamelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = DDIMPipeline _SCREAMING_SNAKE_CASE : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _SCREAMING_SNAKE_CASE : List[str] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } _SCREAMING_SNAKE_CASE : List[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS _SCREAMING_SNAKE_CASE : List[str] = False def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) snake_case_ : Dict = DDIMScheduler() snake_case_ : Optional[Any] = {"unet": unet, "scheduler": scheduler} return components def UpperCAmelCase__ ( self : Optional[int] , A__ : Any , A__ : List[Any]=0 ) -> List[str]: '''simple docstring''' if str(A__ ).startswith("mps" ): snake_case_ : Optional[int] = torch.manual_seed(A__ ) else: snake_case_ : Tuple = torch.Generator(device=A__ ).manual_seed(A__ ) snake_case_ : Dict = { "batch_size": 1, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' snake_case_ : Union[str, Any] = "cpu" snake_case_ : Tuple = self.get_dummy_components() snake_case_ : List[Any] = self.pipeline_class(**A__ ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) snake_case_ : Any = self.get_dummy_inputs(A__ ) snake_case_ : List[Any] = pipe(**A__ ).images snake_case_ : Dict = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) snake_case_ : List[str] = np.array( [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04] ) snake_case_ : Tuple = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(A__ , 1E-3 ) def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def UpperCAmelCase__ ( self : str ) -> List[Any]: '''simple docstring''' super().test_save_load_local(expected_max_difference=3E-3 ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=3E-3 ) def UpperCAmelCase__ ( self : str ) -> int: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = "google/ddpm-cifar10-32" snake_case_ : str = UNetaDModel.from_pretrained(A__ ) snake_case_ : str = DDIMScheduler() snake_case_ : Optional[Any] = DDIMPipeline(unet=A__ , scheduler=A__ ) ddim.to(A__ ) ddim.set_progress_bar_config(disable=A__ ) snake_case_ : Optional[Any] = torch.manual_seed(0 ) snake_case_ : str = ddim(generator=A__ , eta=0.0 , output_type="numpy" ).images snake_case_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case_ : List[Any] = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' snake_case_ : Optional[Any] = "google/ddpm-ema-bedroom-256" snake_case_ : Optional[Any] = UNetaDModel.from_pretrained(A__ ) snake_case_ : Optional[Any] = DDIMScheduler.from_pretrained(A__ ) snake_case_ : Dict = DDIMPipeline(unet=A__ , scheduler=A__ ) ddpm.to(A__ ) ddpm.set_progress_bar_config(disable=A__ ) snake_case_ : Any = torch.manual_seed(0 ) snake_case_ : List[str] = ddpm(generator=A__ , output_type="numpy" ).images snake_case_ : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) snake_case_ : Union[str, Any] = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
666
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: str ): def get_matched_characters(lowerCAmelCase_: str , lowerCAmelCase_: str ) -> str: snake_case_ : Tuple = [] snake_case_ : Tuple = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): snake_case_ : str = int(max(0 , i - limit ) ) snake_case_ : Optional[int] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCAmelCase_ ) snake_case_ : List[Any] = f"{_stra[0:_stra.index(lowerCAmelCase_ )]} {_stra[_stra.index(lowerCAmelCase_ ) + 1:]}" return "".join(lowerCAmelCase_ ) # matching characters snake_case_ : List[Any] = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : int = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = len(lowerCAmelCase_ ) # transposition snake_case_ : List[str] = ( len([(ca, ca) for ca, ca in zip(lowerCAmelCase_ , lowerCAmelCase_ ) if ca != ca] ) // 2 ) if not match_count: snake_case_ : str = 0.0 else: snake_case_ : Optional[Any] = ( 1 / 3 * ( match_count / len(lowerCAmelCase_ ) + match_count / len(lowerCAmelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters snake_case_ : Optional[Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
666
1
from __future__ import annotations class snake_case__ : def __init__( self : Union[str, Any] , A__ : int = 0 ) -> List[Any]: '''simple docstring''' snake_case_ : str = key def UpperCAmelCase__ ( self : Optional[int] , A__ : str , A__ : int ) -> list[str]: '''simple docstring''' assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) snake_case_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 2_55 return [chr(ord(A__ ) ^ key ) for ch in content] def UpperCAmelCase__ ( self : Union[str, Any] , A__ : str , A__ : int ) -> list[str]: '''simple docstring''' assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) snake_case_ : str = key or self.__key or 1 # make sure key is an appropriate size key %= 2_55 return [chr(ord(A__ ) ^ key ) for ch in content] def UpperCAmelCase__ ( self : str , A__ : str , A__ : int = 0 ) -> str: '''simple docstring''' assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) snake_case_ : Optional[int] = key or self.__key or 1 # make sure key can be any size while key > 2_55: key -= 2_55 # This will be returned snake_case_ : List[Any] = "" for ch in content: ans += chr(ord(A__ ) ^ key ) return ans def UpperCAmelCase__ ( self : Dict , A__ : str , A__ : int = 0 ) -> str: '''simple docstring''' assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) snake_case_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 2_55: key -= 2_55 # This will be returned snake_case_ : Dict = "" for ch in content: ans += chr(ord(A__ ) ^ key ) return ans def UpperCAmelCase__ ( self : Any , A__ : str , A__ : int = 0 ) -> bool: '''simple docstring''' assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) try: with open(A__ ) as fin, open("encrypt.out" , "w+" ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(A__ , A__ ) ) except OSError: return False return True def UpperCAmelCase__ ( self : Optional[int] , A__ : str , A__ : int ) -> bool: '''simple docstring''' assert isinstance(A__ , A__ ) and isinstance(A__ , A__ ) try: with open(A__ ) as fin, open("decrypt.out" , "w+" ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(A__ , A__ ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
666
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) set_seed(7_7_0) UpperCAmelCase = { "c_attn": "att_proj", "c_proj": "out_proj", "c_fc": "in_proj", "transformer.": "", "h.": "layers.", "ln_1": "layernorm_1", "ln_2": "layernorm_2", "ln_f": "layernorm_final", "wpe": "position_embeds_layer", "wte": "input_embeds_layer", } UpperCAmelCase = { "text_small": { "repo_id": "suno/bark", "file_name": "text.pt", }, "coarse_small": { "repo_id": "suno/bark", "file_name": "coarse.pt", }, "fine_small": { "repo_id": "suno/bark", "file_name": "fine.pt", }, "text": { "repo_id": "suno/bark", "file_name": "text_2.pt", }, "coarse": { "repo_id": "suno/bark", "file_name": "coarse_2.pt", }, "fine": { "repo_id": "suno/bark", "file_name": "fine_2.pt", }, } UpperCAmelCase = os.path.dirname(os.path.abspath(__file__)) UpperCAmelCase = os.path.join(os.path.expanduser("~"), ".cache") UpperCAmelCase = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int , lowerCAmelCase_: List[str]=False ): snake_case_ : Union[str, Any] = model_type if use_small: key += "_small" return os.path.join(lowerCAmelCase_ , REMOTE_MODEL_PATHS[key]["file_name"] ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: str , lowerCAmelCase_: List[str] ): os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) hf_hub_download(repo_id=lowerCAmelCase_ , filename=lowerCAmelCase_ , local_dir=lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Any , lowerCAmelCase_: Dict , lowerCAmelCase_: List[str]=False , lowerCAmelCase_: Dict="text" ): if model_type == "text": snake_case_ : int = BarkSemanticModel snake_case_ : str = BarkSemanticConfig snake_case_ : Optional[Any] = BarkSemanticGenerationConfig elif model_type == "coarse": snake_case_ : str = BarkCoarseModel snake_case_ : Optional[int] = BarkCoarseConfig snake_case_ : Any = BarkCoarseGenerationConfig elif model_type == "fine": snake_case_ : Optional[int] = BarkFineModel snake_case_ : Tuple = BarkFineConfig snake_case_ : List[str] = BarkFineGenerationConfig else: raise NotImplementedError() snake_case_ : Optional[Any] = f"{model_type}_small" if use_small else model_type snake_case_ : Any = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(lowerCAmelCase_ ): logger.info(f"{model_type} model not found, downloading into `{CACHE_DIR}`." ) _download(model_info["repo_id"] , model_info["file_name"] ) snake_case_ : Any = torch.load(lowerCAmelCase_ , map_location=lowerCAmelCase_ ) # this is a hack snake_case_ : Union[str, Any] = checkpoint["model_args"] if "input_vocab_size" not in model_args: snake_case_ : str = model_args["vocab_size"] snake_case_ : Union[str, Any] = model_args["vocab_size"] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments snake_case_ : Union[str, Any] = model_args.pop("n_head" ) snake_case_ : int = model_args.pop("n_embd" ) snake_case_ : Any = model_args.pop("n_layer" ) snake_case_ : List[str] = ConfigClass(**checkpoint["model_args"] ) snake_case_ : Optional[Any] = ModelClass(config=lowerCAmelCase_ ) snake_case_ : Tuple = GenerationConfigClass() snake_case_ : List[str] = model_generation_config snake_case_ : Optional[int] = checkpoint["model"] # fixup checkpoint snake_case_ : Optional[int] = "_orig_mod." for k, v in list(state_dict.items() ): if k.startswith(lowerCAmelCase_ ): # replace part of the key with corresponding layer name in HF implementation snake_case_ : Tuple = k[len(lowerCAmelCase_ ) :] for old_layer_name in new_layer_name_dict: snake_case_ : int = new_k.replace(lowerCAmelCase_ , new_layer_name_dict[old_layer_name] ) snake_case_ : int = state_dict.pop(lowerCAmelCase_ ) snake_case_ : Optional[int] = set(state_dict.keys() ) - set(model.state_dict().keys() ) snake_case_ : str = {k for k in extra_keys if not k.endswith(".attn.bias" )} snake_case_ : Any = set(model.state_dict().keys() ) - set(state_dict.keys() ) snake_case_ : List[Any] = {k for k in missing_keys if not k.endswith(".attn.bias" )} if len(lowerCAmelCase_ ) != 0: raise ValueError(f"extra keys found: {extra_keys}" ) if len(lowerCAmelCase_ ) != 0: raise ValueError(f"missing keys: {missing_keys}" ) model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) snake_case_ : str = model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) snake_case_ : Union[str, Any] = checkpoint["best_val_loss"].item() logger.info(f"model loaded: {round(n_params/1e6 , 1 )}M params, {round(lowerCAmelCase_ , 3 )} loss" ) model.eval() model.to(lowerCAmelCase_ ) del checkpoint, state_dict return model def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: List[Any] , lowerCAmelCase_: str=False , lowerCAmelCase_: int="text" ): if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() snake_case_ : int = "cpu" # do conversion on cpu snake_case_ : Optional[Any] = _get_ckpt_path(lowerCAmelCase_ , use_small=lowerCAmelCase_ ) snake_case_ : Tuple = _load_model(lowerCAmelCase_ , lowerCAmelCase_ , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) # load bark initial model snake_case_ : int = _bark_load_model(lowerCAmelCase_ , "cpu" , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) if model_type == "text": snake_case_ : Union[str, Any] = bark_model["model"] if model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) != bark_model.get_num_params(): raise ValueError("initial and new models don't have the same number of parameters" ) # check if same output as the bark model snake_case_ : Optional[Any] = 5 snake_case_ : Optional[int] = 1_0 if model_type in ["text", "coarse"]: snake_case_ : Optional[Any] = torch.randint(2_5_6 , (batch_size, sequence_length) , dtype=torch.int ) snake_case_ : str = bark_model(lowerCAmelCase_ )[0] snake_case_ : Tuple = model(lowerCAmelCase_ ) # take last logits snake_case_ : List[str] = output_new_model_total.logits[:, [-1], :] else: snake_case_ : Optional[int] = 3 snake_case_ : str = 8 snake_case_ : List[str] = torch.randint(2_5_6 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) snake_case_ : Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Union[str, Any] = bark_model(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[int] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("initial and new outputs don't have the same shape" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("initial and new outputs are not equal" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: Tuple , lowerCAmelCase_: List[str] , lowerCAmelCase_: Any , lowerCAmelCase_: List[Any] , lowerCAmelCase_: int , lowerCAmelCase_: Optional[Any] , ): snake_case_ : Optional[Any] = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkSemanticConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = BarkCoarseConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[str] = BarkFineConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "config.json" ) ) snake_case_ : List[Any] = EncodecConfig.from_pretrained("facebook/encodec_24khz" ) snake_case_ : List[str] = BarkSemanticModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Optional[Any] = BarkCoarseModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Tuple = BarkFineModel.from_pretrained(lowerCAmelCase_ ) snake_case_ : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_24khz" ) snake_case_ : Tuple = BarkConfig.from_sub_model_configs( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) snake_case_ : List[Any] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) snake_case_ : Optional[int] = BarkModel(lowerCAmelCase_ ) snake_case_ : int = semantic snake_case_ : List[str] = coarseAcoustic snake_case_ : str = fineAcoustic snake_case_ : Optional[Any] = codec snake_case_ : Any = bark_generation_config Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) bark.save_pretrained(lowerCAmelCase_ , repo_id=lowerCAmelCase_ , push_to_hub=lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") UpperCAmelCase = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
666
1
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ), f"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: snake_case_ : str = f"The input value of [n={number}] has to be > 0" raise ValueError(lowerCAmelCase_ ) else: snake_case_ : List[Any] = sylvester(number - 1 ) snake_case_ : List[str] = num - 1 snake_case_ : Tuple = num return lower * upper + 1 if __name__ == "__main__": print(F"The 8th number in Sylvester's sequence: {sylvester(8)}")
666
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase = { "configuration_upernet": ["UperNetConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "UperNetForSemanticSegmentation", "UperNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
666
1