code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: SCREAMING_SNAKE_CASE : List[str] = mf_knapsack(i - 1 , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE : Dict = max( mf_knapsack(i - 1 , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) , mf_knapsack(i - 1 , lowerCamelCase_ , lowerCamelCase_ , j - wt[i - 1] ) + val[i - 1] , ) SCREAMING_SNAKE_CASE : str = val return f[i][j] def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: SCREAMING_SNAKE_CASE : Any = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = dp[i - 1][w_] return dp[n][w_], dp def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if not (isinstance(lowerCamelCase_ , (list, tuple) ) and isinstance(lowerCamelCase_ , (list, tuple) )): raise ValueError( """Both the weights and values vectors must be either lists or tuples""" ) SCREAMING_SNAKE_CASE : str = len(lowerCamelCase_ ) if num_items != len(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : str = ( """The number of weights must be the same as the number of values.\n""" f'''But got {num_items} weights and {len(lowerCamelCase_ )} values''' ) raise ValueError(lowerCamelCase_ ) for i in range(lowerCamelCase_ ): if not isinstance(wt[i] , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = ( """All weights must be integers but got weight of """ f'''type {type(wt[i] )} at index {i}''' ) raise TypeError(lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = knapsack(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : set = set() _construct_solution(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return optimal_val, example_optional_set def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(lowerCamelCase_ , lowerCamelCase_ , i - 1 , lowerCamelCase_ , lowerCamelCase_ ) else: optimal_set.add(lowerCamelCase_ ) _construct_solution(lowerCamelCase_ , lowerCamelCase_ , i - 1 , j - wt[i - 1] , lowerCamelCase_ ) if __name__ == "__main__": __UpperCAmelCase = [3, 2, 4, 4] __UpperCAmelCase = [4, 3, 2, 3] __UpperCAmelCase = 4 __UpperCAmelCase = 6 __UpperCAmelCase = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] __UpperCAmelCase , __UpperCAmelCase = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 __UpperCAmelCase , __UpperCAmelCase = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("""optimal_value = """, optimal_solution) print("""An optimal subset corresponding to the optimal value""", optimal_subset)
79
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """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""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = BigBirdTokenizer SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] SCREAMING_SNAKE_CASE__ = [] def __init__( self : Any , lowerCamelCase_ : str=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict="<unk>" , lowerCamelCase_ : int="<s>" , lowerCamelCase_ : Optional[Any]="</s>" , lowerCamelCase_ : Dict="<pad>" , lowerCamelCase_ : Tuple="[SEP]" , lowerCamelCase_ : Dict="[MASK]" , lowerCamelCase_ : Union[str, Any]="[CLS]" , **lowerCamelCase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else bos_token SCREAMING_SNAKE_CASE : Dict = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else eos_token SCREAMING_SNAKE_CASE : Optional[Any] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else unk_token SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else pad_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else cls_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Optional[Any] = False if not self.vocab_file else True def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : 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] def lowerCamelCase_ ( self : str , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' 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(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Tuple = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ): copyfile(self.vocab_file , lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''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 # ######################################################################## __UpperCAmelCase = 16 __UpperCAmelCase = 32 def __A ( lowerCamelCase_ , lowerCamelCase_ = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(lowerCamelCase_ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE : 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(): SCREAMING_SNAKE_CASE : Optional[int] = 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 SCREAMING_SNAKE_CASE : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(lowerCamelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE : Any = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE : int = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE : int = 8 else: SCREAMING_SNAKE_CASE : str = None return tokenizer.pad( lowerCamelCase_ , padding="""longest""" , max_length=lowerCamelCase_ , pad_to_multiple_of=lowerCamelCase_ , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE : List[Any] = DataLoader( tokenized_datasets["""train"""] , shuffle=lowerCamelCase_ , collate_fn=lowerCamelCase_ , batch_size=lowerCamelCase_ , drop_last=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowerCamelCase_ , collate_fn=lowerCamelCase_ , batch_size=lowerCamelCase_ , drop_last=(accelerator.mixed_precision == """fp8""") , ) return train_dataloader, eval_dataloader def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE : List[str] = config["""lr"""] SCREAMING_SNAKE_CASE : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE : Any = int(config["""seed"""] ) SCREAMING_SNAKE_CASE : Any = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE : Any = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE : Dict = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE : List[Any] = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE : Tuple = MAX_GPU_BATCH_SIZE set_seed(lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = get_dataloaders(lowerCamelCase_ , lowerCamelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE : Dict = 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). SCREAMING_SNAKE_CASE : List[Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE : str = AdamW(params=model.parameters() , lr=lowerCamelCase_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE : str = get_linear_schedule_with_warmup( optimizer=lowerCamelCase_ , num_warmup_steps=1_00 , 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. SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = 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 ) SCREAMING_SNAKE_CASE : List[str] = model(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = outputs.loss SCREAMING_SNAKE_CASE : int = 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(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=lowerCamelCase_ , references=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCamelCase_ ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : 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.""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE : Optional[Any] = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": main()
79
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""swish""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = get_activation("""silu""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""mish""" ) self.assertIsInstance(lowerCamelCase_ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = get_activation("""gelu""" ) self.assertIsInstance(lowerCamelCase_ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
79
1
'''simple docstring''' from math import factorial def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if n < k or k < 0: raise ValueError("""Please enter positive integers for n and k where n >= k""" ) return factorial(lowerCamelCase_ ) // (factorial(lowerCamelCase_ ) * factorial(n - k )) if __name__ == "__main__": print( """The number of five-card hands possible from a standard""", f'''fifty-two card deck is: {combinations(52, 5)}\n''', ) print( """If a class of 40 students must be arranged into groups of""", f'''4 for group projects, there are {combinations(40, 4)} ways''', """to arrange them.\n""", ) print( """If 10 teams are competing in a Formula One race, there""", f'''are {combinations(10, 3)} ways that first, second and''', """third place can be awarded.""", )
79
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''deberta-v2''' def __init__( self : int , lowerCamelCase_ : Optional[Any]=12_81_00 , lowerCamelCase_ : str=15_36 , lowerCamelCase_ : int=24 , lowerCamelCase_ : List[str]=24 , lowerCamelCase_ : List[Any]=61_44 , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : str=0 , lowerCamelCase_ : Union[str, Any]=0.02 , lowerCamelCase_ : Dict=1e-7 , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : Optional[int]=-1 , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : Dict="gelu" , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : List[Any] = relative_attention SCREAMING_SNAKE_CASE : str = max_relative_positions SCREAMING_SNAKE_CASE : int = pad_token_id SCREAMING_SNAKE_CASE : List[str] = position_biased_input # Backwards compatibility if type(lowerCamelCase_ ) == str: SCREAMING_SNAKE_CASE : Dict = [x.strip() for x in pos_att_type.lower().split("""|""" )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = kwargs.get("""pooler_hidden_size""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = pooler_dropout SCREAMING_SNAKE_CASE : Any = pooler_hidden_act class UpperCamelCase__ ( lowercase_ ): """simple docstring""" @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE : Union[str, Any] = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return 12 def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional["TensorType"] = None , lowerCamelCase_ : int = 3 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = super().generate_dummy_inputs(preprocessor=lowerCamelCase_ , framework=lowerCamelCase_ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
79
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 3_84 if "tiny" in model_name: SCREAMING_SNAKE_CASE : Dict = [3, 3, 9, 3] SCREAMING_SNAKE_CASE : Union[str, Any] = [96, 1_92, 3_84, 7_68] if "small" in model_name: SCREAMING_SNAKE_CASE : Dict = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : Tuple = [96, 1_92, 3_84, 7_68] if "base" in model_name: SCREAMING_SNAKE_CASE : List[str] = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : List[Any] = [1_28, 2_56, 5_12, 10_24] SCREAMING_SNAKE_CASE : int = 5_12 if "large" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : Dict = [1_92, 3_84, 7_68, 15_36] SCREAMING_SNAKE_CASE : str = 7_68 if "xlarge" in model_name: SCREAMING_SNAKE_CASE : Optional[int] = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : Union[str, Any] = [2_56, 5_12, 10_24, 20_48] SCREAMING_SNAKE_CASE : Tuple = 10_24 # set label information SCREAMING_SNAKE_CASE : str = 1_50 SCREAMING_SNAKE_CASE : Any = """huggingface/label-files""" SCREAMING_SNAKE_CASE : Any = """ade20k-id2label.json""" SCREAMING_SNAKE_CASE : str = json.load(open(hf_hub_download(lowerCamelCase_ , lowerCamelCase_ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE : int = {int(lowerCamelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Any = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Dict = ConvNextConfig( depths=lowerCamelCase_ , hidden_sizes=lowerCamelCase_ , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) SCREAMING_SNAKE_CASE : Dict = UperNetConfig( backbone_config=lowerCamelCase_ , auxiliary_in_channels=lowerCamelCase_ , num_labels=lowerCamelCase_ , idalabel=lowerCamelCase_ , labelaid=lowerCamelCase_ , ) return config def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [] # fmt: off # stem rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""") ) rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.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.stages.{i}.{j}.gamma''', f'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((f'''backbone.downsample_layers.{i}.0.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.0.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = dct.pop(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = val def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = { """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""", """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""", """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""", """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""", """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""", } SCREAMING_SNAKE_CASE : Tuple = model_name_to_url[model_name] SCREAMING_SNAKE_CASE : Optional[Any] = torch.hub.load_state_dict_from_url(lowerCamelCase_ , map_location="""cpu""" )["""state_dict"""] SCREAMING_SNAKE_CASE : Union[str, Any] = get_upernet_config(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = UperNetForSemanticSegmentation(lowerCamelCase_ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(lowerCamelCase_ ) if "bn" in key: SCREAMING_SNAKE_CASE : Optional[Any] = key.replace("""bn""" , """batch_norm""" ) SCREAMING_SNAKE_CASE : str = val # rename keys SCREAMING_SNAKE_CASE : List[Any] = create_rename_keys(lowerCamelCase_ ) for src, dest in rename_keys: rename_key(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) model.load_state_dict(lowerCamelCase_ ) # verify on image SCREAMING_SNAKE_CASE : Union[str, Any] = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(requests.get(lowerCamelCase_ , stream=lowerCamelCase_ ).raw ).convert("""RGB""" ) SCREAMING_SNAKE_CASE : Dict = SegformerImageProcessor() SCREAMING_SNAKE_CASE : Dict = processor(lowerCamelCase_ , return_tensors="""pt""" ).pixel_values with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(lowerCamelCase_ ) if model_name == "upernet-convnext-tiny": SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]] ) elif model_name == "upernet-convnext-small": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [[-8.8_236, -8.8_236, -8.6_771], [-8.8_236, -8.8_236, -8.6_771], [-8.7_638, -8.7_638, -8.6_240]] ) elif model_name == "upernet-convnext-base": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [[-8.8_558, -8.8_558, -8.6_905], [-8.8_558, -8.8_558, -8.6_905], [-8.7_669, -8.7_669, -8.6_021]] ) elif model_name == "upernet-convnext-large": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [[-8.6_660, -8.6_660, -8.6_210], [-8.6_660, -8.6_660, -8.6_210], [-8.6_310, -8.6_310, -8.5_964]] ) elif model_name == "upernet-convnext-xlarge": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-8.4_980, -8.4_980, -8.3_977], [-8.4_980, -8.4_980, -8.3_977], [-8.4_379, -8.4_379, -8.3_412]] ) print("""Logits:""" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , lowerCamelCase_ , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCamelCase_ ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(lowerCamelCase_ ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-convnext-tiny""", type=str, choices=[f'''upernet-convnext-{size}''' for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]], help="""Name of the ConvNext UperNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __UpperCAmelCase = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
79
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = {} def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: SCREAMING_SNAKE_CASE : str = [[w, v]] if not self.graph.get(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = [] def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : str ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[str, Any]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Tuple = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Any = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[int]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : str = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : Union[str, Any] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Any=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = deque() SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : int = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Optional[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Union[str, Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : List[str] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[Any] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : int = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return sorted_nodes def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : Union[str, Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Any = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : int = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = s SCREAMING_SNAKE_CASE : List[Any] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = -2 SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Tuple = s SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : str = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Dict = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[str] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = s SCREAMING_SNAKE_CASE : Optional[int] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str=-2 , lowerCamelCase_ : int=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin def lowerCamelCase_ ( self : int , lowerCamelCase_ : Tuple=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, v]] # add the other way if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, u]] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) # the other way round if self.graph.get(lowerCamelCase_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : str=-2 , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] if s == -2: SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : Any = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : List[str] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = deque() SCREAMING_SNAKE_CASE : Tuple = [] if s == -2: SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : List[Any] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = -2 SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Optional[Any] = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : str = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Optional[int] = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Union[str, Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s SCREAMING_SNAKE_CASE : str = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = s SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Any = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : str = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Optional[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Tuple = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[str]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = time() return end - begin def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Dict=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = time() return end - begin
79
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""", } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''blip_2_vision_model''' def __init__( self : Dict , lowerCamelCase_ : Optional[Any]=14_08 , lowerCamelCase_ : Optional[int]=61_44 , lowerCamelCase_ : str=39 , lowerCamelCase_ : Union[str, Any]=16 , lowerCamelCase_ : str=2_24 , lowerCamelCase_ : Dict=14 , lowerCamelCase_ : Union[str, Any]="gelu" , lowerCamelCase_ : List[str]=0.00_001 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : List[str]=1e-10 , lowerCamelCase_ : Dict=True , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : Dict = intermediate_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = patch_size SCREAMING_SNAKE_CASE : List[Any] = image_size SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE : List[Any] = attention_dropout SCREAMING_SNAKE_CASE : Any = layer_norm_eps SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : Tuple = qkv_bias @classmethod def lowerCamelCase_ ( cls : List[Any] , lowerCamelCase_ : Union[str, os.PathLike] , **lowerCamelCase_ : str ): '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = cls.get_config_dict(lowerCamelCase_ , **lowerCamelCase_ ) # get the vision config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": SCREAMING_SNAKE_CASE : str = 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(lowerCamelCase_ , **lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''blip_2_qformer''' def __init__( self : List[Any] , lowerCamelCase_ : str=3_05_22 , lowerCamelCase_ : Union[str, Any]=7_68 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : str=12 , lowerCamelCase_ : Union[str, Any]=30_72 , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Dict=0.1 , lowerCamelCase_ : Dict=0.1 , lowerCamelCase_ : Dict=5_12 , lowerCamelCase_ : Optional[Any]=0.02 , lowerCamelCase_ : str=1e-12 , lowerCamelCase_ : Dict=0 , lowerCamelCase_ : Optional[Any]="absolute" , lowerCamelCase_ : Tuple=2 , lowerCamelCase_ : Optional[Any]=14_08 , **lowerCamelCase_ : List[str] , ): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Any = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = position_embedding_type SCREAMING_SNAKE_CASE : Optional[Any] = cross_attention_frequency SCREAMING_SNAKE_CASE : List[str] = encoder_hidden_size @classmethod def lowerCamelCase_ ( cls : Union[str, Any] , lowerCamelCase_ : Union[str, os.PathLike] , **lowerCamelCase_ : Any ): '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = cls.get_config_dict(lowerCamelCase_ , **lowerCamelCase_ ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": SCREAMING_SNAKE_CASE : Optional[int] = config_dict["""qformer_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(lowerCamelCase_ , **lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''blip-2''' SCREAMING_SNAKE_CASE__ = True def __init__( self : List[Any] , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : Any=None , lowerCamelCase_ : Dict=None , lowerCamelCase_ : str=32 , **lowerCamelCase_ : Any ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) if vision_config is None: SCREAMING_SNAKE_CASE : Any = {} logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" ) if qformer_config is None: SCREAMING_SNAKE_CASE : str = {} logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" ) if text_config is None: SCREAMING_SNAKE_CASE : Optional[int] = {} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) SCREAMING_SNAKE_CASE : List[str] = BlipaVisionConfig(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = BlipaQFormerConfig(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = text_config["""model_type"""] if """model_type""" in text_config else """opt""" SCREAMING_SNAKE_CASE : Union[str, Any] = CONFIG_MAPPING[text_model_type](**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE : Dict = self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE : Union[str, Any] = num_query_tokens SCREAMING_SNAKE_CASE : List[str] = self.vision_config.hidden_size SCREAMING_SNAKE_CASE : List[Any] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE : List[str] = 1.0 SCREAMING_SNAKE_CASE : str = 0.02 @classmethod def lowerCamelCase_ ( cls : int , lowerCamelCase_ : BlipaVisionConfig , lowerCamelCase_ : BlipaQFormerConfig , lowerCamelCase_ : PretrainedConfig , **lowerCamelCase_ : Tuple , ): '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **lowerCamelCase_ , ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.vision_config.to_dict() SCREAMING_SNAKE_CASE : List[str] = self.qformer_config.to_dict() SCREAMING_SNAKE_CASE : Optional[Any] = self.text_config.to_dict() SCREAMING_SNAKE_CASE : int = self.__class__.model_type return output
79
'''simple docstring''' import os 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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} __UpperCAmelCase = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } __UpperCAmelCase = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple="<s>" , lowerCamelCase_ : Union[str, Any]="</s>" , lowerCamelCase_ : Tuple="</s>" , lowerCamelCase_ : str="<s>" , lowerCamelCase_ : Optional[int]="<unk>" , lowerCamelCase_ : List[Any]="<pad>" , lowerCamelCase_ : Optional[Any]="<mask>" , lowerCamelCase_ : Optional[Dict[str, Any]] = None , **lowerCamelCase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Dict = vocab_file SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} SCREAMING_SNAKE_CASE : str = len(self.sp_model ) - 1 SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1, 1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [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] @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return len(self.sp_model ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = {self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str ): '''simple docstring''' return self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.PieceToId(lowerCamelCase_ ) return spm_id if spm_id else self.unk_token_id def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[str] ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Tuple = """""" SCREAMING_SNAKE_CASE : Dict = 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(lowerCamelCase_ ) + token SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(lowerCamelCase_ ) return out_string.strip() def __getstate__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE : List[Any] = None return state def __setstate__( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Dict = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCamelCase_ , """wb""" ) as fi: SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class UpperCamelCase__ ( lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = [R'''h\.\d+\.attn\.bias''', R'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self : Any , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] = None , lowerCamelCase_ : int = 5_02_57 , lowerCamelCase_ : int = 10_24 , lowerCamelCase_ : int = 7_68 , lowerCamelCase_ : int = 12 , lowerCamelCase_ : int = 12 , lowerCamelCase_ : Optional[int] = None , lowerCamelCase_ : str = "gelu_new" , lowerCamelCase_ : float = 0.1 , lowerCamelCase_ : float = 0.1 , lowerCamelCase_ : float = 0.1 , lowerCamelCase_ : float = 1e-5 , lowerCamelCase_ : float = 0.02 , lowerCamelCase_ : bool = True , lowerCamelCase_ : bool = True , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = False , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : str = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and''' f''' `n_embd`: {n_embd} are not equal.''' ) SCREAMING_SNAKE_CASE : Optional[int] = prefix_inner_dim SCREAMING_SNAKE_CASE : Union[str, Any] = prefix_hidden_dim SCREAMING_SNAKE_CASE : List[Any] = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE : Any = ( nn.Linear(self.prefix_hidden_dim , lowerCamelCase_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE : Any = GPTaConfig( vocab_size=lowerCamelCase_ , n_positions=lowerCamelCase_ , n_embd=lowerCamelCase_ , n_layer=lowerCamelCase_ , n_head=lowerCamelCase_ , n_inner=lowerCamelCase_ , activation_function=lowerCamelCase_ , resid_pdrop=lowerCamelCase_ , embd_pdrop=lowerCamelCase_ , attn_pdrop=lowerCamelCase_ , layer_norm_epsilon=lowerCamelCase_ , initializer_range=lowerCamelCase_ , scale_attn_weights=lowerCamelCase_ , use_cache=lowerCamelCase_ , scale_attn_by_inverse_layer_idx=lowerCamelCase_ , reorder_and_upcast_attn=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : int = GPTaLMHeadModel(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : torch.Tensor , lowerCamelCase_ : torch.Tensor , lowerCamelCase_ : Optional[torch.Tensor] = None , lowerCamelCase_ : Optional[torch.Tensor] = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.transformer.transformer.wte(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = self.encode_prefix(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.decode_prefix(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) SCREAMING_SNAKE_CASE : str = torch.cat((dummy_token, input_ids) , dim=1 ) SCREAMING_SNAKE_CASE : int = self.transformer(inputs_embeds=lowerCamelCase_ , labels=lowerCamelCase_ , attention_mask=lowerCamelCase_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : torch.device ): '''simple docstring''' return torch.zeros(lowerCamelCase_ , self.prefix_length , dtype=torch.intaa , device=lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.encode_prefix(lowerCamelCase_ ) @torch.no_grad() def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = torch.split(lowerCamelCase_ , 1 , dim=0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = [] SCREAMING_SNAKE_CASE : int = [] for feature in features: SCREAMING_SNAKE_CASE : int = self.decode_prefix(feature.to(lowerCamelCase_ ) ) # back to the clip feature # Only support beam search for now SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self.generate_beam( input_embeds=lowerCamelCase_ , device=lowerCamelCase_ , eos_token_id=lowerCamelCase_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) SCREAMING_SNAKE_CASE : Dict = torch.stack(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = torch.stack(lowerCamelCase_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : int = 5 , lowerCamelCase_ : int = 67 , lowerCamelCase_ : float = 1.0 , lowerCamelCase_ : Optional[int] = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = eos_token_id SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Tuple = torch.ones(lowerCamelCase_ , device=lowerCamelCase_ , dtype=torch.int ) SCREAMING_SNAKE_CASE : Tuple = torch.zeros(lowerCamelCase_ , device=lowerCamelCase_ , dtype=torch.bool ) if input_embeds is not None: SCREAMING_SNAKE_CASE : Any = input_embeds else: SCREAMING_SNAKE_CASE : Optional[int] = self.transformer.transformer.wte(lowerCamelCase_ ) for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.transformer(inputs_embeds=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = outputs.logits SCREAMING_SNAKE_CASE : Tuple = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) SCREAMING_SNAKE_CASE : Union[str, Any] = logits.softmax(-1 ).log() if scores is None: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = logits.topk(lowerCamelCase_ , -1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = generated.expand(lowerCamelCase_ , *generated.shape[1:] ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: SCREAMING_SNAKE_CASE : Tuple = next_tokens else: SCREAMING_SNAKE_CASE : Optional[int] = tokens.expand(lowerCamelCase_ , *tokens.shape[1:] ) SCREAMING_SNAKE_CASE : Tuple = torch.cat((tokens, next_tokens) , dim=1 ) else: SCREAMING_SNAKE_CASE : Optional[int] = -float(np.inf ) SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : List[Any] = scores[:, None] + logits seq_lengths[~is_stopped] += 1 SCREAMING_SNAKE_CASE : Dict = scores_sum / seq_lengths[:, None] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = scores_sum_average.view(-1 ).topk(lowerCamelCase_ , -1 ) SCREAMING_SNAKE_CASE : Dict = next_tokens // scores_sum.shape[1] SCREAMING_SNAKE_CASE : Tuple = seq_lengths[next_tokens_source] SCREAMING_SNAKE_CASE : Tuple = next_tokens % scores_sum.shape[1] SCREAMING_SNAKE_CASE : Tuple = next_tokens.unsqueeze(1 ) SCREAMING_SNAKE_CASE : Tuple = tokens[next_tokens_source] SCREAMING_SNAKE_CASE : int = torch.cat((tokens, next_tokens) , dim=1 ) SCREAMING_SNAKE_CASE : Optional[int] = generated[next_tokens_source] SCREAMING_SNAKE_CASE : Optional[int] = scores_sum_average * seq_lengths SCREAMING_SNAKE_CASE : str = is_stopped[next_tokens_source] SCREAMING_SNAKE_CASE : List[str] = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) SCREAMING_SNAKE_CASE : Tuple = torch.cat((generated, next_token_embed) , dim=1 ) SCREAMING_SNAKE_CASE : Tuple = is_stopped + next_tokens.eq(lowerCamelCase_ ).squeeze() if is_stopped.all(): break SCREAMING_SNAKE_CASE : Any = scores / seq_lengths SCREAMING_SNAKE_CASE : Dict = scores.argsort(descending=lowerCamelCase_ ) # tokens tensors are already padded to max_seq_length SCREAMING_SNAKE_CASE : List[str] = [tokens[i] for i in order] SCREAMING_SNAKE_CASE : Optional[Any] = torch.stack(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : str = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
79
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) SCREAMING_SNAKE_CASE : Dict = { """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 ), } SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , lowerCamelCase_ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
79
1
'''simple docstring''' from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''''' SCREAMING_SNAKE_CASE__ = '''hf-legacy''' # "hf://"" is reserved for hffs def __init__( self : List[str] , lowerCamelCase_ : Optional[DatasetInfo] = None , lowerCamelCase_ : Optional[str] = None , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(self , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = repo_info SCREAMING_SNAKE_CASE : Any = token SCREAMING_SNAKE_CASE : Tuple = None def lowerCamelCase_ ( self : Dict ): '''simple docstring''' if self.dir_cache is None: SCREAMING_SNAKE_CASE : int = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE : Optional[Any] = { """name""": hf_file.rfilename, """size""": None, """type""": """file""", } self.dir_cache.update( { str(lowerCamelCase_ ): {"""name""": str(lowerCamelCase_ ), """size""": None, """type""": """directory"""} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : str , lowerCamelCase_ : str = "rb" , **lowerCamelCase_ : List[Any] , ): '''simple docstring''' if not isinstance(self.repo_info , lowerCamelCase_ ): raise NotImplementedError(f'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) SCREAMING_SNAKE_CASE : Dict = hf_hub_url(self.repo_info.id , lowerCamelCase_ , revision=self.repo_info.sha ) return fsspec.open( lowerCamelCase_ , mode=lowerCamelCase_ , headers=get_authentication_headers_for_url(lowerCamelCase_ , use_auth_token=self.token ) , client_kwargs={"""trust_env""": True} , ).open() def lowerCamelCase_ ( self : str , lowerCamelCase_ : int , **lowerCamelCase_ : List[str] ): '''simple docstring''' self._get_dirs() SCREAMING_SNAKE_CASE : Union[str, Any] = self._strip_protocol(lowerCamelCase_ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int=False , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' self._get_dirs() SCREAMING_SNAKE_CASE : str = PurePosixPath(path.strip("""/""" ) ) SCREAMING_SNAKE_CASE : Optional[int] = {} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE : List[Any] = PurePosixPath(p.strip("""/""" ) ) SCREAMING_SNAKE_CASE : List[str] = p.parent if root == path: SCREAMING_SNAKE_CASE : Dict = f SCREAMING_SNAKE_CASE : List[Any] = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
79
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''Translation''' , init=lowercase_ , repr=lowercase_ ) def __call__( self : int ): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''TranslationVariableLanguages''' , init=lowercase_ , repr=lowercase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = sorted(set(self.languages ) ) if self.languages else None SCREAMING_SNAKE_CASE : str = len(self.languages ) if self.languages else None def __call__( self : Tuple ): '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = set(self.languages ) if self.languages and set(lowerCamelCase_ ) - lang_set: raise ValueError( f'''Some languages in example ({", ".join(sorted(set(lowerCamelCase_ ) - lang_set ) )}) are not in valid set ({", ".join(lowerCamelCase_ )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE : List[Any] = [] for lang, text in translation_dict.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = zip(*sorted(lowerCamelCase_ ) ) return {"language": languages, "translation": translations} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
79
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer __UpperCAmelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """vocab_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt""" ), """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""", """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json""" ), """google/electra-base-generator""": ( """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json""" ), """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """google/electra-small-generator""": 512, """google/electra-base-generator""": 512, """google/electra-large-generator""": 512, """google/electra-small-discriminator""": 512, """google/electra-base-discriminator""": 512, """google/electra-large-discriminator""": 512, } __UpperCAmelCase = { """google/electra-small-generator""": {"""do_lower_case""": True}, """google/electra-base-generator""": {"""do_lower_case""": True}, """google/electra-large-generator""": {"""do_lower_case""": True}, """google/electra-small-discriminator""": {"""do_lower_case""": True}, """google/electra-base-discriminator""": {"""do_lower_case""": True}, """google/electra-large-discriminator""": {"""do_lower_case""": True}, } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ElectraTokenizer def __init__( self : int , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Union[str, Any]=None , lowerCamelCase_ : Optional[int]=True , lowerCamelCase_ : List[str]="[UNK]" , lowerCamelCase_ : int="[SEP]" , lowerCamelCase_ : List[Any]="[PAD]" , lowerCamelCase_ : Union[str, Any]="[CLS]" , lowerCamelCase_ : Union[str, Any]="[MASK]" , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Any=None , **lowerCamelCase_ : Union[str, Any] , ): '''simple docstring''' super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , do_lower_case=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , tokenize_chinese_chars=lowerCamelCase_ , strip_accents=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowerCamelCase_ ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowerCamelCase_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowerCamelCase_ ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : int = getattr(lowerCamelCase_ , normalizer_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE : List[Any] = do_lower_case SCREAMING_SNAKE_CASE : int = strip_accents SCREAMING_SNAKE_CASE : Dict = tokenize_chinese_chars SCREAMING_SNAKE_CASE : Optional[Any] = normalizer_class(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : Dict=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase_ ( self : int , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self._tokenizer.model.save(lowerCamelCase_ , name=lowerCamelCase_ ) return tuple(lowerCamelCase_ )
79
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , *lowerCamelCase_ : List[str] , **lowerCamelCase_ : Dict ): '''simple docstring''' warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , lowerCamelCase_ , ) super().__init__(*lowerCamelCase_ , **lowerCamelCase_ )
79
1
'''simple docstring''' 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 UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = 0 @slow def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(lowerCamelCase_ ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(lowerCamelCase_ ) , 0 ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) # Check that tokenizer_type ≠ model_type SCREAMING_SNAKE_CASE : str = AutoTokenizer.from_pretrained(lowerCamelCase_ , config=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(lowerCamelCase_ , """vocab.txt""" ) ) SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""bert""" , use_fast=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(lowerCamelCase_ , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(lowerCamelCase_ , """merges.txt""" ) ) SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""gpt2""" , use_fast=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) @require_tokenizers def lowerCamelCase_ ( self : str ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(lowerCamelCase_ , """vocab.txt""" ) ) SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""bert""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(lowerCamelCase_ , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(lowerCamelCase_ , """merges.txt""" ) ) SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""gpt2""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' with pytest.raises(lowerCamelCase_ ): AutoTokenizer.from_pretrained("""./""" , tokenizer_type="""xxx""" ) @require_tokenizers def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: SCREAMING_SNAKE_CASE : str = tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased""" ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , lowerCamelCase_ ) else: self.assertEqual(tokenizer.do_lower_case , lowerCamelCase_ ) self.assertEqual(tokenizer.model_max_length , 5_12 ) @require_tokenizers def lowerCamelCase_ ( self : Dict ): '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( lowerCamelCase_ , """julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier""" , ): SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists""" ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = TOKENIZER_MAPPING.values() SCREAMING_SNAKE_CASE : List[str] = [] 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(lowerCamelCase_ ) @require_tokenizers def lowerCamelCase_ ( self : int ): '''simple docstring''' self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=lowerCamelCase_ ) , lowerCamelCase_ ) self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" ) , lowerCamelCase_ ) @require_tokenizers def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = AutoTokenizer.from_pretrained("""distilbert-base-uncased""" , do_lower_case=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = """Hello, world. How are you?""" SCREAMING_SNAKE_CASE : int = tokenizer.tokenize(lowerCamelCase_ ) self.assertEqual("""[UNK]""" , tokens[0] ) SCREAMING_SNAKE_CASE : Tuple = AutoTokenizer.from_pretrained("""microsoft/mpnet-base""" , do_lower_case=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize(lowerCamelCase_ ) self.assertEqual("""[UNK]""" , tokens[0] ) @require_tokenizers def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config""" ) self.assertEqual(type(lowerCamelCase_ ) , lowerCamelCase_ ) 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 lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""ctrl""" ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = get_tokenizer_config("""bert-base-cased""" ) SCREAMING_SNAKE_CASE : Any = config.pop("""_commit_hash""" , lowerCamelCase_ ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(lowerCamelCase_ , {"""do_lower_case""": False} ) # This model does not have a tokenizer_config so we get back an empty dict. SCREAMING_SNAKE_CASE : int = get_tokenizer_config(lowerCamelCase_ ) self.assertDictEqual(lowerCamelCase_ , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = get_tokenizer_config(lowerCamelCase_ ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config["""tokenizer_class"""] , """BertTokenizer""" ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' try: AutoConfig.register("""custom""" , lowerCamelCase_ ) AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase_ ): AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = CustomTokenizer.from_pretrained(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) 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 lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' try: AutoConfig.register("""custom""" , lowerCamelCase_ ) # Can register in two steps AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase_ ): AutoTokenizer.register(lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) # 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: SCREAMING_SNAKE_CASE : Any = BertTokenizerFast.from_pretrained(lowerCamelCase_ ) bert_tokenizer.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = CustomTokenizerFast.from_pretrained(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained(lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) 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 lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' with self.assertRaises(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained(lowerCamelCase_ , trust_remote_code=lowerCamelCase_ ) 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 SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) 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(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained(lowerCamelCase_ , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) 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 lowerCamelCase_ ( self : List[str] ): '''simple docstring''' class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = False class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = NewTokenizer SCREAMING_SNAKE_CASE__ = False try: AutoConfig.register("""custom""" , lowerCamelCase_ ) AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) AutoTokenizer.register(lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , use_fast=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertTrue(tokenizer.special_attribute_present ) SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) 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 lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=lowerCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase_ , """bert-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained("""bert-base""" ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase_ , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained(lowerCamelCase_ , revision="""aaaaaa""" ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: SCREAMING_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 )
79
'''simple docstring''' 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 UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : str ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : int , lowerCamelCase_ : Dict ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Optional[int] ): '''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 lowerCamelCase_ ( cls : Any ): '''simple docstring''' return f'''`pip install {cls.pip_package or cls.name}`''' class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''optuna''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Dict ): '''simple docstring''' return run_hp_search_optuna(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Any ): '''simple docstring''' return default_hp_space_optuna(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''ray''' SCREAMING_SNAKE_CASE__ = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_ray_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_ray(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' return default_hp_space_ray(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''sigopt''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_sigopt(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return default_hp_space_sigopt(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''wandb''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return run_hp_search_wandb(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return default_hp_space_wandb(lowerCamelCase_ ) __UpperCAmelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCamelCase_ ) > 0: SCREAMING_SNAKE_CASE : List[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() ) )
79
1
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ['''image_processor''', '''tokenizer'''] SCREAMING_SNAKE_CASE__ = '''ViltImageProcessor''' SCREAMING_SNAKE_CASE__ = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : List[str] , lowerCamelCase_ : Dict=None , lowerCamelCase_ : Optional[int]=None , **lowerCamelCase_ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.image_processor def __call__( self : List[str] , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCamelCase_ : bool = True , lowerCamelCase_ : Union[bool, str, PaddingStrategy] = False , lowerCamelCase_ : Union[bool, str, TruncationStrategy] = None , lowerCamelCase_ : Optional[int] = None , lowerCamelCase_ : int = 0 , lowerCamelCase_ : Optional[int] = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = True , lowerCamelCase_ : Optional[Union[str, TensorType]] = None , **lowerCamelCase_ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.tokenizer( text=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , max_length=lowerCamelCase_ , stride=lowerCamelCase_ , pad_to_multiple_of=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , return_overflowing_tokens=lowerCamelCase_ , return_special_tokens_mask=lowerCamelCase_ , return_offsets_mapping=lowerCamelCase_ , return_length=lowerCamelCase_ , verbose=lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ , ) # add pixel_values + pixel_mask SCREAMING_SNAKE_CASE : Dict = self.image_processor(lowerCamelCase_ , return_tensors=lowerCamelCase_ ) encoding.update(lowerCamelCase_ ) return encoding def lowerCamelCase_ ( self : Optional[Any] , *lowerCamelCase_ : Any , **lowerCamelCase_ : Optional[int] ): '''simple docstring''' return self.tokenizer.batch_decode(*lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : str , *lowerCamelCase_ : int , **lowerCamelCase_ : Any ): '''simple docstring''' return self.tokenizer.decode(*lowerCamelCase_ , **lowerCamelCase_ ) @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCamelCase_ ( self : Any ): '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , lowerCamelCase_ , ) return self.image_processor_class @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , lowerCamelCase_ , ) return self.image_processor
79
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = 1 # (0 is vertical, 1 is horizontal) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = get_dataset(lowerCamelCase_ , lowerCamelCase_ ) print("""Processing...""" ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = update_image_and_anno(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for index, image in enumerate(lowerCamelCase_ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Optional[int] = random_chars(32 ) SCREAMING_SNAKE_CASE : Optional[Any] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE : Dict = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , lowerCamelCase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(lowerCamelCase_ )} with {file_name}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE : Optional[Any] = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(lowerCamelCase_ ) with open(f'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Any = [] for label_file in glob.glob(os.path.join(lowerCamelCase_ , """*.txt""" ) ): SCREAMING_SNAKE_CASE : str = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(lowerCamelCase_ ) as in_file: SCREAMING_SNAKE_CASE : Any = in_file.readlines() SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowerCamelCase_ , f'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE : Tuple = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : Union[str, Any] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(lowerCamelCase_ ) labels.append(lowerCamelCase_ ) return img_paths, labels def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [] for idx in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Dict = img_list[idx] path_list.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = anno_list[idx] SCREAMING_SNAKE_CASE : Optional[Any] = cva.imread(lowerCamelCase_ ) if flip_type == 1: SCREAMING_SNAKE_CASE : List[str] = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE : Any = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(lowerCamelCase_ ) new_imgs_list.append(lowerCamelCase_ ) return new_imgs_list, new_annos_lists, path_list def __A ( lowerCamelCase_ = 32 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : Dict = ascii_lowercase + digits return "".join(random.choice(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
79
1
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __UpperCAmelCase = { """configuration_cpmant""": ["""CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CpmAntConfig"""], """tokenization_cpmant""": ["""CpmAntTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST""", """CpmAntForCausalLM""", """CpmAntModel""", """CpmAntPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''vivit''' def __init__( self : Tuple , lowerCamelCase_ : str=2_24 , lowerCamelCase_ : List[Any]=32 , lowerCamelCase_ : Tuple=[2, 16, 16] , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Dict=12 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : List[Any]=30_72 , lowerCamelCase_ : List[str]="gelu_fast" , lowerCamelCase_ : str=0.0 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : List[Any]=1e-06 , lowerCamelCase_ : Tuple=True , **lowerCamelCase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Dict = num_frames SCREAMING_SNAKE_CASE : Optional[Any] = tubelet_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : int = qkv_bias super().__init__(**lowerCamelCase_ )
79
1
'''simple docstring''' import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def __A ( lowerCamelCase_ ): """simple docstring""" def wrapper(*lowerCamelCase_ , **lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = timeit.default_timer() SCREAMING_SNAKE_CASE : List[Any] = func(*lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = timeit.default_timer() - starttime return delta SCREAMING_SNAKE_CASE : Dict = func.__name__ return wrapper def __A ( lowerCamelCase_ , lowerCamelCase_=1_00 , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[Any] = seq_shapes or {} for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(lowerCamelCase_ , _ArrayXD ): SCREAMING_SNAKE_CASE : int = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(lowerCamelCase_ , datasets.Value ): if v.dtype == "string": SCREAMING_SNAKE_CASE : Dict = """The small grey turtle was surprisingly fast when challenged.""" else: SCREAMING_SNAKE_CASE : str = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(lowerCamelCase_ , datasets.Sequence ): while isinstance(lowerCamelCase_ , datasets.Sequence ): SCREAMING_SNAKE_CASE : Optional[Any] = v.feature SCREAMING_SNAKE_CASE : Dict = seq_shapes[k] SCREAMING_SNAKE_CASE : List[str] = np.random.rand(*lowerCamelCase_ ).astype(v.dtype ) SCREAMING_SNAKE_CASE : Any = data dummy_data.append((i, example) ) return dummy_data def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=1_00 , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = generate_examples(lowerCamelCase_ , num_examples=lowerCamelCase_ , seq_shapes=lowerCamelCase_ ) with ArrowWriter(features=lowerCamelCase_ , path=lowerCamelCase_ ) as writer: for key, record in dummy_data: SCREAMING_SNAKE_CASE : Tuple = features.encode_example(lowerCamelCase_ ) writer.write(lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f'''Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.''' ) SCREAMING_SNAKE_CASE : Optional[int] = datasets.Dataset.from_file(filename=lowerCamelCase_ , info=datasets.DatasetInfo(features=lowerCamelCase_ ) ) return dataset
79
'''simple docstring''' import math class UpperCamelCase__ : """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Tuple=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' SCREAMING_SNAKE_CASE : Any = n SCREAMING_SNAKE_CASE : Optional[int] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # adjacency matrix for weight SCREAMING_SNAKE_CASE : Union[str, Any] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # dp[i][j] stores minimum distance from i to j def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = w def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): SCREAMING_SNAKE_CASE : Union[str, Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": __UpperCAmelCase = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
79
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = BlenderbotConfig SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = '''gelu''' def __init__( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[str]=13 , lowerCamelCase_ : Optional[Any]=7 , lowerCamelCase_ : List[Any]=True , lowerCamelCase_ : Any=False , lowerCamelCase_ : Optional[int]=99 , lowerCamelCase_ : Optional[int]=32 , lowerCamelCase_ : Tuple=2 , lowerCamelCase_ : Optional[Any]=4 , lowerCamelCase_ : Tuple=37 , lowerCamelCase_ : Optional[int]=0.1 , lowerCamelCase_ : Dict=0.1 , lowerCamelCase_ : Optional[int]=20 , lowerCamelCase_ : List[Any]=2 , lowerCamelCase_ : List[str]=1 , lowerCamelCase_ : str=0 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : List[Any] = seq_length SCREAMING_SNAKE_CASE : Optional[int] = is_training SCREAMING_SNAKE_CASE : Optional[int] = use_labels SCREAMING_SNAKE_CASE : Optional[int] = vocab_size SCREAMING_SNAKE_CASE : Tuple = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Any = num_attention_heads SCREAMING_SNAKE_CASE : Tuple = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : int = eos_token_id SCREAMING_SNAKE_CASE : Union[str, Any] = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = bos_token_id def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) SCREAMING_SNAKE_CASE : Tuple = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) SCREAMING_SNAKE_CASE : Dict = tf.concat([input_ids, eos_tensor] , axis=1 ) SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) SCREAMING_SNAKE_CASE : List[Any] = prepare_blenderbot_inputs_dict(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return config, inputs_dict def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = TFBlenderbotModel(config=lowerCamelCase_ ).get_decoder() SCREAMING_SNAKE_CASE : List[Any] = inputs_dict["""input_ids"""] SCREAMING_SNAKE_CASE : List[Any] = input_ids[:1, :] SCREAMING_SNAKE_CASE : Tuple = inputs_dict["""attention_mask"""][:1, :] SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict["""head_mask"""] SCREAMING_SNAKE_CASE : List[str] = 1 # first forward pass SCREAMING_SNAKE_CASE : Optional[Any] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , head_mask=lowerCamelCase_ , use_cache=lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE : Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) SCREAMING_SNAKE_CASE : Any = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[int] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE : Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowerCamelCase_ , lowerCamelCase_ , rtol=1e-3 ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , ): """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE : Tuple = tf.cast(tf.math.not_equal(lowerCamelCase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE : Tuple = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE : Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCamelCase__ ( lowercase_ , lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ = ( { '''conversational''': TFBlenderbotForConditionalGeneration, '''feature-extraction''': TFBlenderbotModel, '''summarization''': TFBlenderbotForConditionalGeneration, '''text2text-generation''': TFBlenderbotForConditionalGeneration, '''translation''': TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = TFBlenderbotModelTester(self ) SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=lowerCamelCase_ ) def lowerCamelCase_ ( self : str ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCamelCase_ ) @require_tokenizers @require_tf class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ['''My friends are cool but they eat too many carbs.'''] SCREAMING_SNAKE_CASE__ = '''facebook/blenderbot-400M-distill''' @cached_property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(self.src_text , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.model.generate( model_inputs.input_ids , ) SCREAMING_SNAKE_CASE : Dict = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowerCamelCase_ )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
79
'''simple docstring''' import math def __A ( lowerCamelCase_ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __A ( lowerCamelCase_ = 1_00_01 ): """simple docstring""" try: SCREAMING_SNAKE_CASE : Tuple = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError("""Parameter nth must be int or castable to int.""" ) from None if nth <= 0: raise ValueError("""Parameter nth must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE : list[int] = [] SCREAMING_SNAKE_CASE : Dict = 2 while len(lowerCamelCase_ ) < nth: if is_prime(lowerCamelCase_ ): primes.append(lowerCamelCase_ ) num += 1 else: num += 1 return primes[len(lowerCamelCase_ ) - 1] if __name__ == "__main__": print(f'''{solution() = }''')
79
1
'''simple docstring''' import baseaa def __A ( lowerCamelCase_ ): """simple docstring""" return baseaa.baaencode(string.encode("""utf-8""" ) ) def __A ( lowerCamelCase_ ): """simple docstring""" return baseaa.baadecode(lowerCamelCase_ ).decode("""utf-8""" ) if __name__ == "__main__": __UpperCAmelCase = """Hello World!""" __UpperCAmelCase = baseaa_encode(test) print(encoded) __UpperCAmelCase = baseaa_decode(encoded) print(decoded)
79
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __UpperCAmelCase = {"""UserAgent""": UserAgent().random} def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = script.contents[0] SCREAMING_SNAKE_CASE : int = json.loads(data[data.find("""{\"config\"""" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f'''https://www.instagram.com/{username}/''' SCREAMING_SNAKE_CASE : Any = self.get_json() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = requests.get(self.url , headers=lowerCamelCase_ ).text SCREAMING_SNAKE_CASE : List[Any] = BeautifulSoup(lowerCamelCase_ , """html.parser""" ).find_all("""script""" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Dict ): '''simple docstring''' return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self : int ): '''simple docstring''' return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return self.user_data["username"] @property def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return self.user_data["full_name"] @property def lowerCamelCase_ ( self : int ): '''simple docstring''' return self.user_data["biography"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["business_email"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["external_url"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return self.user_data["is_verified"] @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.user_data["is_private"] def __A ( lowerCamelCase_ = "github" ): """simple docstring""" import os if os.environ.get("""CI""" ): return # test failing on GitHub Actions SCREAMING_SNAKE_CASE : Any = InstagramUser(lowerCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , lowerCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("""https://instagram.""" ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = InstagramUser("""github""") print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
79
1
'''simple docstring''' import numpy as np from PIL import Image def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = np.array(lowerCamelCase_ ) if arr.shape[0] != arr.shape[1]: raise ValueError("""The input array is not a square matrix""" ) SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : str = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE : Any = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape SCREAMING_SNAKE_CASE : List[Any] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix SCREAMING_SNAKE_CASE : Optional[Any] = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE : List[str] = 0 SCREAMING_SNAKE_CASE : Optional[Any] = 0 return updated_arr def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = np.array(lowerCamelCase_ ) if arr.shape[0] != arr.shape[1]: raise ValueError("""The input array is not a square matrix""" ) SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE : Any = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape SCREAMING_SNAKE_CASE : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix SCREAMING_SNAKE_CASE : List[Any] = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Any = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="""avgpooling""", verbose=True) # Loading the image __UpperCAmelCase = Image.open("""path_to_image""") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
79
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __UpperCAmelCase = logging.getLogger(__name__) __UpperCAmelCase = """Hello world! cécé herlolip""" __UpperCAmelCase = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = BertAbsConfig( temp_dir=""".""" , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="""bert""" , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : int = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) SCREAMING_SNAKE_CASE : List[str] = AbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) , lowerCamelCase_ ) original.eval() SCREAMING_SNAKE_CASE : Optional[int] = BertAbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) SCREAMING_SNAKE_CASE : int = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE : Optional[int] = encoder_input_ids SCREAMING_SNAKE_CASE : Optional[Any] = decoder_input_ids SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE : str = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = original.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : str = new_model.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Any = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) __UpperCAmelCase = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
79
1
'''simple docstring''' import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html __UpperCAmelCase = """platform""" import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , ): """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE : List[str] = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE : Optional[int] = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: SCREAMING_SNAKE_CASE : Optional[Any] = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE : Optional[int] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE : str = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Tuple=13 , lowerCamelCase_ : List[Any]=7 , lowerCamelCase_ : List[str]=True , lowerCamelCase_ : Optional[Any]=False , lowerCamelCase_ : str=99 , lowerCamelCase_ : Optional[int]=16 , lowerCamelCase_ : Dict=2 , lowerCamelCase_ : int=4 , lowerCamelCase_ : Any=4 , lowerCamelCase_ : Union[str, Any]="gelu" , lowerCamelCase_ : Dict=0.1 , lowerCamelCase_ : Any=0.1 , lowerCamelCase_ : Dict=32 , lowerCamelCase_ : Tuple=2 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : Tuple=0 , lowerCamelCase_ : Optional[int]=0.02 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : List[Any] = batch_size SCREAMING_SNAKE_CASE : Any = seq_length SCREAMING_SNAKE_CASE : str = is_training SCREAMING_SNAKE_CASE : Any = use_labels SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : Tuple = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_act SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE : List[str] = eos_token_id SCREAMING_SNAKE_CASE : Dict = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = bos_token_id SCREAMING_SNAKE_CASE : Any = initializer_range def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) SCREAMING_SNAKE_CASE : Dict = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) SCREAMING_SNAKE_CASE : Any = shift_tokens_right(lowerCamelCase_ , 1 , 2 ) SCREAMING_SNAKE_CASE : Tuple = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = prepare_blenderbot_inputs_dict(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return config, inputs_dict def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = 20 SCREAMING_SNAKE_CASE : str = model_class_name(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = model.encode(inputs_dict["""input_ids"""] ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) SCREAMING_SNAKE_CASE : List[str] = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) SCREAMING_SNAKE_CASE : Any = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE : Tuple = model.decode( decoder_input_ids[:, :-1] , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ , decoder_position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Tuple = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE : Tuple = model.decode( decoder_input_ids[:, -1:] , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = model.decode(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = 20 SCREAMING_SNAKE_CASE : Union[str, Any] = model_class_name(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model.encode(inputs_dict["""input_ids"""] ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) SCREAMING_SNAKE_CASE : Optional[Any] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) SCREAMING_SNAKE_CASE : Dict = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE : str = model.decode( decoder_input_ids[:, :-1] , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ , decoder_position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[str] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE : Any = model.decode( decoder_input_ids[:, -1:] , lowerCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowerCamelCase_ , decoder_position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : str = model.decode(lowerCamelCase_ , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) @require_flax class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 99 def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) SCREAMING_SNAKE_CASE : Tuple = input_ids.shape[0] SCREAMING_SNAKE_CASE : int = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = self._get_config_and_data() SCREAMING_SNAKE_CASE : Any = FlaxBlenderbotForConditionalGeneration(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = lm_model(input_ids=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["""logits"""].shape , lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) SCREAMING_SNAKE_CASE : Tuple = FlaxBlenderbotForConditionalGeneration(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : str = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : List[str] = lm_model(input_ids=lowerCamelCase_ , decoder_input_ids=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = (*summary.shape, config.vocab_size) self.assertEqual(outputs["""logits"""].shape , lowerCamelCase_ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : List[Any] = shift_tokens_right(lowerCamelCase_ , 1 , 2 ) SCREAMING_SNAKE_CASE : Tuple = np.equal(lowerCamelCase_ , 1 ).astype(np.floataa ).sum() SCREAMING_SNAKE_CASE : Union[str, Any] = np.equal(lowerCamelCase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowerCamelCase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class UpperCamelCase__ ( lowercase_ , unittest.TestCase , lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) SCREAMING_SNAKE_CASE__ = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = FlaxBlenderbotModelTester(self ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE : Dict = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model_class(lowerCamelCase_ ) @jax.jit def encode_jitted(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[Any]=None , **lowerCamelCase_ : int ): return model.encode(input_ids=lowerCamelCase_ , attention_mask=lowerCamelCase_ ) with self.subTest("""JIT Enabled""" ): SCREAMING_SNAKE_CASE : Any = encode_jitted(**lowerCamelCase_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE : Dict = encode_jitted(**lowerCamelCase_ ).to_tuple() self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) for jitted_output, output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE : Optional[int] = model_class(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) SCREAMING_SNAKE_CASE : List[Any] = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(lowerCamelCase_ : str , lowerCamelCase_ : Any , lowerCamelCase_ : str ): return model.decode( decoder_input_ids=lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , encoder_outputs=lowerCamelCase_ , ) with self.subTest("""JIT Enabled""" ): SCREAMING_SNAKE_CASE : List[Any] = decode_jitted(**lowerCamelCase_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE : int = decode_jitted(**lowerCamelCase_ ).to_tuple() self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) for jitted_output, output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCamelCase_ ( self : int ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : str = model_class_name.from_pretrained("""facebook/blenderbot-400M-distill""" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids SCREAMING_SNAKE_CASE : Dict = np.ones((1, 1) ) * model.config.eos_token_id SCREAMING_SNAKE_CASE : Optional[Any] = model(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) @unittest.skipUnless(jax_device != """cpu""" , """3B test too slow on CPU.""" ) @slow def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = {"""num_beams""": 1, """early_stopping""": True, """min_length""": 15, """max_length""": 25} SCREAMING_SNAKE_CASE : Any = {"""skip_special_tokens""": True, """clean_up_tokenization_spaces""": True} SCREAMING_SNAKE_CASE : List[str] = FlaxBlenderbotForConditionalGeneration.from_pretrained("""facebook/blenderbot-3B""" , from_pt=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = BlenderbotTokenizer.from_pretrained("""facebook/blenderbot-3B""" ) SCREAMING_SNAKE_CASE : str = ["""Sam"""] SCREAMING_SNAKE_CASE : str = tokenizer(lowerCamelCase_ , return_tensors="""jax""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = model.generate(**lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = """Sam is a great name. It means \"sun\" in Gaelic.""" SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode(lowerCamelCase_ , **lowerCamelCase_ ) assert generated_txt[0].strip() == tgt_text
79
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=True , lowerCamelCase_="pt" ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {"""add_prefix_space""": True} if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and not line.startswith(""" """ ) else {} SCREAMING_SNAKE_CASE : Optional[Any] = padding_side return tokenizer( [line] , max_length=lowerCamelCase_ , padding="""max_length""" if pad_to_max_length else None , truncation=lowerCamelCase_ , return_tensors=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , **lowerCamelCase_ , ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , ): """simple docstring""" SCREAMING_SNAKE_CASE : int = input_ids.ne(lowerCamelCase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : str , lowerCamelCase_ : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str]="train" , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : int=None , lowerCamelCase_ : Union[str, Any]="" , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : str = Path(lowerCamelCase_ ).joinpath(type_path + """.source""" ) SCREAMING_SNAKE_CASE : Optional[Any] = Path(lowerCamelCase_ ).joinpath(type_path + """.target""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_char_lens(self.src_file ) SCREAMING_SNAKE_CASE : int = max_source_length SCREAMING_SNAKE_CASE : str = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' SCREAMING_SNAKE_CASE : List[str] = tokenizer SCREAMING_SNAKE_CASE : Dict = prefix if n_obs is not None: SCREAMING_SNAKE_CASE : List[Any] = self.src_lens[:n_obs] SCREAMING_SNAKE_CASE : int = src_lang SCREAMING_SNAKE_CASE : Optional[int] = tgt_lang def __len__( self : List[Any] ): '''simple docstring''' return len(self.src_lens ) def __getitem__( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = index + 1 # linecache starts at 1 SCREAMING_SNAKE_CASE : Dict = self.prefix + linecache.getline(str(self.src_file ) , lowerCamelCase_ ).rstrip("""\n""" ) SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , lowerCamelCase_ ).rstrip("""\n""" ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , lowerCamelCase_ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer ) SCREAMING_SNAKE_CASE : Any = self.tokenizer.generator if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer SCREAMING_SNAKE_CASE : Optional[int] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_source_length , """right""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_target_length , """right""" ) SCREAMING_SNAKE_CASE : Tuple = source_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : Tuple = target_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : List[str] = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : Dict ): '''simple docstring''' return [len(lowerCamelCase_ ) for x in Path(lowerCamelCase_ ).open().readlines()] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = torch.stack([x["""input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""attention_mask"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""decoder_input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ , attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch __UpperCAmelCase = getLogger(__name__) def __A ( lowerCamelCase_ ): """simple docstring""" return list(itertools.chain.from_iterable(lowerCamelCase_ ) ) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = get_git_info() save_json(lowerCamelCase_ , os.path.join(lowerCamelCase_ , """git_log.json""" ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=4 , **lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """w""" ) as f: json.dump(lowerCamelCase_ , lowerCamelCase_ , indent=lowerCamelCase_ , **lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ ) as f: return json.load(lowerCamelCase_ ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = git.Repo(search_parent_directories=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { """repo_id""": str(lowerCamelCase_ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return list(map(lowerCamelCase_ , lowerCamelCase_ ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """wb""" ) as f: return pickle.dump(lowerCamelCase_ , lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" def remove_articles(lowerCamelCase_ ): return re.sub(R"""\b(a|an|the)\b""" , """ """ , lowerCamelCase_ ) def white_space_fix(lowerCamelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_ ) ) ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Optional[int] = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Tuple = Counter(lowerCamelCase_ ) & Counter(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = sum(common.values() ) if num_same == 0: return 0 SCREAMING_SNAKE_CASE : Optional[int] = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = (2 * precision * recall) / (precision + recall) return fa def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return normalize_answer(lowerCamelCase_ ) == normalize_answer(lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert len(lowerCamelCase_ ) == len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowerCamelCase_ , lowerCamelCase_ ): em += exact_match_score(lowerCamelCase_ , lowerCamelCase_ ) if len(lowerCamelCase_ ) > 0: em /= len(lowerCamelCase_ ) return {"em": em} def __A ( lowerCamelCase_ ): """simple docstring""" return model_prefix.startswith("""rag""" ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead SCREAMING_SNAKE_CASE : Dict = """dropout_rate""" for p in extra_params: if getattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): if not hasattr(lowerCamelCase_ , lowerCamelCase_ ) and not hasattr(lowerCamelCase_ , equivalent_param[p] ): logger.info("""config doesn't have a `{}` attribute""".format(lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) continue SCREAMING_SNAKE_CASE : Dict = p if hasattr(lowerCamelCase_ , lowerCamelCase_ ) else equivalent_param[p] setattr(lowerCamelCase_ , lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) return hparams, config
79
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available __UpperCAmelCase = { """configuration_audio_spectrogram_transformer""": [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ASTConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ASTForAudioClassification""", """ASTModel""", """ASTPreTrainedModel""", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""ASTFeatureExtractor"""] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' def __A ( lowerCamelCase_ ): """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : List[str] = number while duplicate > 0: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = divmod(lowerCamelCase_ , 10 ) fact_sum += factorial(lowerCamelCase_ ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") __UpperCAmelCase = int(input("""Enter number: """).strip()) print( f'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
79
1
'''simple docstring''' def __A ( lowerCamelCase_ ): """simple docstring""" if any(not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or x < 0 for x in sequence ): raise TypeError("""Sequence must be list of non-negative integers""" ) for _ in range(len(lowerCamelCase_ ) ): for i, (rod_upper, rod_lower) in enumerate(zip(lowerCamelCase_ , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
79
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class UpperCamelCase__ ( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase_ : str=None , **lowerCamelCase_ : Dict ): '''simple docstring''' super().__init__(features=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch_tensor_kwargs import torch # noqa import torch at initialization def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and column: if all( isinstance(lowerCamelCase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : int ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , (str, bytes, type(lowerCamelCase_ )) ): return value elif isinstance(lowerCamelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE : str = {} if isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): SCREAMING_SNAKE_CASE : Any = {"""dtype""": torch.intaa} elif isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE : int = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowerCamelCase_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(lowerCamelCase_ ) return torch.tensor(lowerCamelCase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(lowerCamelCase_ , """__array__""" ) and not isinstance(lowerCamelCase_ , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowerCamelCase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) elif isinstance(lowerCamelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) return self._tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : dict ): '''simple docstring''' return map_nested(self._recursive_tensorize , lowerCamelCase_ , map_list=lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.numpy_arrow_extractor().extract_row(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_row(lowerCamelCase_ ) return self.recursive_tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.numpy_arrow_extractor().extract_column(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.python_features_decoder.decode_column(lowerCamelCase_ , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE : List[str] = self.recursive_tensorize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self._consolidate(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.numpy_arrow_extractor().extract_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.recursive_tensorize(lowerCamelCase_ ) for column_name in batch: SCREAMING_SNAKE_CASE : Tuple = self._consolidate(batch[column_name] ) return batch
79
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """Visual-Attention-Network/van-base""": ( """https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json""" ), } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''van''' def __init__( self : Union[str, Any] , lowerCamelCase_ : List[Any]=2_24 , lowerCamelCase_ : int=3 , lowerCamelCase_ : Tuple=[7, 3, 3, 3] , lowerCamelCase_ : Dict=[4, 2, 2, 2] , lowerCamelCase_ : Optional[int]=[64, 1_28, 3_20, 5_12] , lowerCamelCase_ : Dict=[3, 3, 12, 3] , lowerCamelCase_ : List[Any]=[8, 8, 4, 4] , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : Union[str, Any]=1e-6 , lowerCamelCase_ : Dict=1e-2 , lowerCamelCase_ : int=0.0 , lowerCamelCase_ : Optional[Any]=0.0 , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = image_size SCREAMING_SNAKE_CASE : List[Any] = num_channels SCREAMING_SNAKE_CASE : str = patch_sizes SCREAMING_SNAKE_CASE : Optional[int] = strides SCREAMING_SNAKE_CASE : Dict = hidden_sizes SCREAMING_SNAKE_CASE : str = depths SCREAMING_SNAKE_CASE : Optional[Any] = mlp_ratios SCREAMING_SNAKE_CASE : Optional[int] = hidden_act SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE : Any = layer_scale_init_value SCREAMING_SNAKE_CASE : int = drop_path_rate SCREAMING_SNAKE_CASE : Union[str, Any] = dropout_rate
79
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCAmelCase = random.Random() def __A ( lowerCamelCase_ , lowerCamelCase_=1.0 , lowerCamelCase_=None , lowerCamelCase_=None ): """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE : Optional[Any] = global_rng SCREAMING_SNAKE_CASE : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int]=7 , lowerCamelCase_ : Optional[int]=4_00 , lowerCamelCase_ : int=20_00 , lowerCamelCase_ : List[str]=20_48 , lowerCamelCase_ : Optional[Any]=1_28 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : Dict=30 , lowerCamelCase_ : Dict=4_41_00 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = min_seq_length SCREAMING_SNAKE_CASE : Any = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : int = spectrogram_length SCREAMING_SNAKE_CASE : List[Any] = feature_size SCREAMING_SNAKE_CASE : Any = num_audio_channels SCREAMING_SNAKE_CASE : Tuple = hop_length SCREAMING_SNAKE_CASE : str = chunk_length SCREAMING_SNAKE_CASE : Dict = sampling_rate def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : Any=False ): '''simple docstring''' def _flatten(lowerCamelCase_ : Dict ): return list(itertools.chain(*lowerCamelCase_ ) ) if equal_length: SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(lowerCamelCase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = TvltFeatureExtractor def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TvltFeatureExtractionTester(self ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase_ , """spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """sampling_rate""" ) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Any = feat_extract_first.save_pretrained(lowerCamelCase_ )[0] check_json_file_has_correct_format(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : List[Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : int = os.path.join(lowerCamelCase_ , """feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class.from_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : int = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : List[str] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Optional[Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] SCREAMING_SNAKE_CASE : int = [np.asarray(lowerCamelCase_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 , mask_audio=lowerCamelCase_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] SCREAMING_SNAKE_CASE : int = np.asarray(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Union[str, Any] = ds.sort("""id""" ).select(range(lowerCamelCase_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : Tuple = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(lowerCamelCase_ , return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_92, 1_28) ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , lowerCamelCase_ , atol=1e-4 ) )
79
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCAmelCase = { """configuration_mobilenet_v2""": [ """MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileNetV2Config""", """MobileNetV2OnnxConfig""", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""MobileNetV2FeatureExtractor"""] __UpperCAmelCase = ["""MobileNetV2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileNetV2ForImageClassification""", """MobileNetV2ForSemanticSegmentation""", """MobileNetV2Model""", """MobileNetV2PreTrainedModel""", """load_tf_weights_in_mobilenet_v2""", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __UpperCAmelCase = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
1
'''simple docstring''' import argparse import hashlib # hashlib is only used inside the Test class import struct class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = data SCREAMING_SNAKE_CASE : Union[str, Any] = [0X67_452_301, 0Xef_cda_b89, 0X98_bad_cfe, 0X10_325_476, 0Xc3_d2e_1f0] @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : Tuple , lowerCamelCase_ : List[Any] ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xff_fff_fff def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = b"""\x80""" + b"""\x00""" * (63 - (len(self.data ) + 8) % 64) SCREAMING_SNAKE_CASE : Tuple = self.data + padding + struct.pack(""">Q""" , 8 * len(self.data ) ) return padded_data def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = list(struct.unpack(""">16L""" , lowerCamelCase_ ) ) + [0] * 64 for i in range(16 , 80 ): SCREAMING_SNAKE_CASE : List[Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.padding() SCREAMING_SNAKE_CASE : Union[str, Any] = self.split_blocks() for block in self.blocks: SCREAMING_SNAKE_CASE : int = self.expand_block(lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = self.h for i in range(0 , 80 ): if 0 <= i < 20: SCREAMING_SNAKE_CASE : Any = (b & c) | ((~b) & d) SCREAMING_SNAKE_CASE : List[str] = 0X5a_827_999 elif 20 <= i < 40: SCREAMING_SNAKE_CASE : str = b ^ c ^ d SCREAMING_SNAKE_CASE : Tuple = 0X6e_d9e_ba1 elif 40 <= i < 60: SCREAMING_SNAKE_CASE : Tuple = (b & c) | (b & d) | (c & d) SCREAMING_SNAKE_CASE : Optional[int] = 0X8f_1bb_cdc elif 60 <= i < 80: SCREAMING_SNAKE_CASE : Dict = b ^ c ^ d SCREAMING_SNAKE_CASE : List[str] = 0Xca_62c_1d6 SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = ( self.rotate(lowerCamelCase_ , 5 ) + f + e + k + expanded_block[i] & 0Xff_fff_fff, a, self.rotate(lowerCamelCase_ , 30 ), c, d, ) SCREAMING_SNAKE_CASE : Any = ( self.h[0] + a & 0Xff_fff_fff, self.h[1] + b & 0Xff_fff_fff, self.h[2] + c & 0Xff_fff_fff, self.h[3] + d & 0Xff_fff_fff, self.h[4] + e & 0Xff_fff_fff, ) return ("{:08x}" * 5).format(*self.h ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = B"""Test String""" assert SHAaHash(lowerCamelCase_ ).final_hash() == hashlib.shaa(lowerCamelCase_ ).hexdigest() # noqa: S324 def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) SCREAMING_SNAKE_CASE : Any = parser.parse_args() SCREAMING_SNAKE_CASE : Optional[int] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: SCREAMING_SNAKE_CASE : Optional[Any] = f.read() else: SCREAMING_SNAKE_CASE : List[str] = bytes(lowerCamelCase_ , """utf-8""" ) print(SHAaHash(lowerCamelCase_ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
79
'''simple docstring''' __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
79
1
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = filter(lambda lowerCamelCase_ : p.requires_grad , model.parameters() ) SCREAMING_SNAKE_CASE : List[str] = sum([np.prod(p.size() ) for p in model_parameters] ) return params __UpperCAmelCase = logging.getLogger(__name__) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if metric == "rouge2": SCREAMING_SNAKE_CASE : Union[str, Any] = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": SCREAMING_SNAKE_CASE : Optional[Any] = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": SCREAMING_SNAKE_CASE : List[Any] = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' """ function.""" ) SCREAMING_SNAKE_CASE : str = ModelCheckpoint( dirpath=lowerCamelCase_ , filename=lowerCamelCase_ , monitor=f'''val_{metric}''' , mode="""max""" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return EarlyStopping( monitor=f'''val_{metric}''' , mode="""min""" if """loss""" in metric else """max""" , patience=lowerCamelCase_ , verbose=lowerCamelCase_ , ) class UpperCamelCase__ ( pl.Callback ): """simple docstring""" def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {f'''lr_group_{i}''': param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(lowerCamelCase_ ) @rank_zero_only def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : pl.Trainer , lowerCamelCase_ : pl.LightningModule , lowerCamelCase_ : str , lowerCamelCase_ : List[str]=True ): '''simple docstring''' logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results SCREAMING_SNAKE_CASE : Union[str, Any] = Path(pl_module.hparams.output_dir ) if type_path == "test": SCREAMING_SNAKE_CASE : Optional[Any] = od / """test_results.txt""" SCREAMING_SNAKE_CASE : Tuple = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. SCREAMING_SNAKE_CASE : Optional[int] = od / f'''{type_path}_results/{trainer.global_step:05d}.txt''' SCREAMING_SNAKE_CASE : int = od / f'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=lowerCamelCase_ ) generations_file.parent.mkdir(exist_ok=lowerCamelCase_ ) with open(lowerCamelCase_ , """a+""" ) as writer: for key in sorted(lowerCamelCase_ ): if key in ["log", "progress_bar", "preds"]: continue SCREAMING_SNAKE_CASE : Any = metrics[key] if isinstance(lowerCamelCase_ , torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[int] = val.item() SCREAMING_SNAKE_CASE : Union[str, Any] = f'''{key}: {val:.6f}\n''' writer.write(lowerCamelCase_ ) if not save_generations: return if "preds" in metrics: SCREAMING_SNAKE_CASE : List[str] = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(lowerCamelCase_ ) @rank_zero_only def lowerCamelCase_ ( self : str , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any ): '''simple docstring''' try: SCREAMING_SNAKE_CASE : Any = pl_module.model.model.num_parameters() except AttributeError: SCREAMING_SNAKE_CASE : List[str] = pl_module.model.num_parameters() SCREAMING_SNAKE_CASE : str = count_trainable_parameters(lowerCamelCase_ ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6} ) @rank_zero_only def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : pl.Trainer , lowerCamelCase_ : pl.LightningModule ): '''simple docstring''' save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(lowerCamelCase_ , lowerCamelCase_ , """test""" ) @rank_zero_only def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : pl.Trainer , lowerCamelCase_ : Any ): '''simple docstring''' save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
79
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCAmelCase = """ Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)[\"depth\"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline(\"depth-estimation\") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to(\"cuda\") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to(\"cuda\") >>> img = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/cat.png\" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\") >>> prompt = \"A robot, 4k photo\" >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\" >>> generator = torch.Generator(device=\"cuda\").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save(\"robot_cat.png\") ``` """ def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=8 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Union[str, Any] , lowerCamelCase_ : UNetaDConditionModel , lowerCamelCase_ : DDPMScheduler , lowerCamelCase_ : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=lowerCamelCase_ , scheduler=lowerCamelCase_ , movq=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : str = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase_ ( self : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): '''simple docstring''' if latents is None: SCREAMING_SNAKE_CASE : Tuple = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ , device=lowerCamelCase_ , dtype=lowerCamelCase_ ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) SCREAMING_SNAKE_CASE : Dict = latents.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = latents * scheduler.init_noise_sigma return latents def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Dict=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE : List[Any] = torch.device(f'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple=0 ): '''simple docstring''' if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) SCREAMING_SNAKE_CASE : Any = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCamelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE : Union[str, Any] = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = cpu_offload_with_hook(lowerCamelCase_ , lowerCamelCase_ , prev_module_hook=lowerCamelCase_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE : str = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase_ ( self : str ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase_ , """_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() @replace_example_docstring(lowerCamelCase_ ) def __call__( self : Optional[Any] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : torch.FloatTensor , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 1_00 , lowerCamelCase_ : float = 4.0 , lowerCamelCase_ : int = 1 , lowerCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase_ : Optional[torch.FloatTensor] = None , lowerCamelCase_ : Optional[str] = "pil" , lowerCamelCase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._execution_device SCREAMING_SNAKE_CASE : Optional[int] = guidance_scale > 1.0 if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Any = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : List[Any] = image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Optional[int] = negative_image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Dict = hint.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) self.scheduler.set_timesteps(lowerCamelCase_ , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.timesteps SCREAMING_SNAKE_CASE : Any = self.movq.config.latent_channels SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = downscale_height_and_width(lowerCamelCase_ , lowerCamelCase_ , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCamelCase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Union[str, Any] = {"""image_embeds""": image_embeds, """hint""": hint} SCREAMING_SNAKE_CASE : Dict = self.unet( sample=lowerCamelCase_ , timestep=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , added_cond_kwargs=lowerCamelCase_ , return_dict=lowerCamelCase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE : str = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : str = self.scheduler.step( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ , )[0] # post-processing SCREAMING_SNAKE_CASE : List[str] = self.movq.decode(lowerCamelCase_ , force_not_quantize=lowerCamelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE : Optional[int] = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : List[Any] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Any = self.numpy_to_pil(lowerCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase_ )
79
1
'''simple docstring''' from importlib import import_module from .logging import get_logger __UpperCAmelCase = get_logger(__name__) class UpperCamelCase__ : """simple docstring""" def __init__( self : Any , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[Any]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Any = module._original_module if isinstance(lowerCamelCase_ , _PatchedModuleObj ) else module class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = [] def __init__( self : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : Any=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = obj SCREAMING_SNAKE_CASE : List[Any] = target SCREAMING_SNAKE_CASE : int = new SCREAMING_SNAKE_CASE : List[Any] = target.split(""".""" )[0] SCREAMING_SNAKE_CASE : Optional[Any] = {} SCREAMING_SNAKE_CASE : List[str] = attrs or [] def __enter__( self : int ): '''simple docstring''' *SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(lowerCamelCase_ ) ): try: SCREAMING_SNAKE_CASE : Optional[Any] = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(self.obj , lowerCamelCase_ ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(lowerCamelCase_ , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): SCREAMING_SNAKE_CASE : Optional[int] = obj_attr # patch at top level setattr(self.obj , lowerCamelCase_ , _PatchedModuleObj(lowerCamelCase_ , attrs=self.attrs ) ) SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.obj , lowerCamelCase_ ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(lowerCamelCase_ , lowerCamelCase_ , _PatchedModuleObj(getattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) , attrs=self.attrs ) ) SCREAMING_SNAKE_CASE : Optional[Any] = getattr(lowerCamelCase_ , lowerCamelCase_ ) # finally set the target attribute setattr(lowerCamelCase_ , lowerCamelCase_ , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: SCREAMING_SNAKE_CASE : str = getattr(import_module(""".""".join(lowerCamelCase_ ) ) , lowerCamelCase_ ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , lowerCamelCase_ ) is attr_value: SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.obj , lowerCamelCase_ ) setattr(self.obj , lowerCamelCase_ , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" SCREAMING_SNAKE_CASE : Union[str, Any] = globals()["""__builtins__"""][target_attr] setattr(self.obj , lowerCamelCase_ , self.new ) else: raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self : Dict , *lowerCamelCase_ : List[str] ): '''simple docstring''' for attr in list(self.original ): setattr(self.obj , lowerCamelCase_ , self.original.pop(lowerCamelCase_ ) ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' self.__enter__() self._active_patches.append(self ) def lowerCamelCase_ ( self : int ): '''simple docstring''' try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
79
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """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""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = BigBirdTokenizer SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] SCREAMING_SNAKE_CASE__ = [] def __init__( self : Any , lowerCamelCase_ : str=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict="<unk>" , lowerCamelCase_ : int="<s>" , lowerCamelCase_ : Optional[Any]="</s>" , lowerCamelCase_ : Dict="<pad>" , lowerCamelCase_ : Tuple="[SEP]" , lowerCamelCase_ : Dict="[MASK]" , lowerCamelCase_ : Union[str, Any]="[CLS]" , **lowerCamelCase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else bos_token SCREAMING_SNAKE_CASE : Dict = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else eos_token SCREAMING_SNAKE_CASE : Optional[Any] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else unk_token SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else pad_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else cls_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Optional[Any] = False if not self.vocab_file else True def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : 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] def lowerCamelCase_ ( self : str , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' 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(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Tuple = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ): copyfile(self.vocab_file , lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''vivit''' def __init__( self : Tuple , lowerCamelCase_ : str=2_24 , lowerCamelCase_ : List[Any]=32 , lowerCamelCase_ : Tuple=[2, 16, 16] , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Dict=12 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : List[Any]=30_72 , lowerCamelCase_ : List[str]="gelu_fast" , lowerCamelCase_ : str=0.0 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : List[Any]=1e-06 , lowerCamelCase_ : Tuple=True , **lowerCamelCase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Dict = num_frames SCREAMING_SNAKE_CASE : Optional[Any] = tubelet_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : int = qkv_bias super().__init__(**lowerCamelCase_ )
79
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""swish""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = get_activation("""silu""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""mish""" ) self.assertIsInstance(lowerCamelCase_ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = get_activation("""gelu""" ) self.assertIsInstance(lowerCamelCase_ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
79
1
'''simple docstring''' from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
79
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''deberta-v2''' def __init__( self : int , lowerCamelCase_ : Optional[Any]=12_81_00 , lowerCamelCase_ : str=15_36 , lowerCamelCase_ : int=24 , lowerCamelCase_ : List[str]=24 , lowerCamelCase_ : List[Any]=61_44 , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : str=0 , lowerCamelCase_ : Union[str, Any]=0.02 , lowerCamelCase_ : Dict=1e-7 , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : Optional[int]=-1 , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : Dict="gelu" , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : List[Any] = relative_attention SCREAMING_SNAKE_CASE : str = max_relative_positions SCREAMING_SNAKE_CASE : int = pad_token_id SCREAMING_SNAKE_CASE : List[str] = position_biased_input # Backwards compatibility if type(lowerCamelCase_ ) == str: SCREAMING_SNAKE_CASE : Dict = [x.strip() for x in pos_att_type.lower().split("""|""" )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = kwargs.get("""pooler_hidden_size""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = pooler_dropout SCREAMING_SNAKE_CASE : Any = pooler_hidden_act class UpperCamelCase__ ( lowercase_ ): """simple docstring""" @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE : Union[str, Any] = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return 12 def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional["TensorType"] = None , lowerCamelCase_ : int = 3 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = super().generate_dummy_inputs(preprocessor=lowerCamelCase_ , framework=lowerCamelCase_ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
79
1
'''simple docstring''' import os from typing import Dict, List, Tuple, TypeVar, Union __UpperCAmelCase = TypeVar("""T""") __UpperCAmelCase = Union[List[T], Tuple[T, ...]] __UpperCAmelCase = Union[T, List[T], Dict[str, T]] __UpperCAmelCase = Union[str, bytes, os.PathLike]
79
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = {} def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: SCREAMING_SNAKE_CASE : str = [[w, v]] if not self.graph.get(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = [] def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : str ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[str, Any]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Tuple = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Any = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[int]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : str = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : Union[str, Any] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Any=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = deque() SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : int = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Optional[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Union[str, Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : List[str] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[Any] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : int = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return sorted_nodes def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : Union[str, Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Any = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : int = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = s SCREAMING_SNAKE_CASE : List[Any] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = -2 SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Tuple = s SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : str = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Dict = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[str] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = s SCREAMING_SNAKE_CASE : Optional[int] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str=-2 , lowerCamelCase_ : int=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin def lowerCamelCase_ ( self : int , lowerCamelCase_ : Tuple=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, v]] # add the other way if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, u]] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) # the other way round if self.graph.get(lowerCamelCase_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : str=-2 , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] if s == -2: SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : Any = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : List[str] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = deque() SCREAMING_SNAKE_CASE : Tuple = [] if s == -2: SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : List[Any] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = -2 SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Optional[Any] = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : str = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Optional[int] = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Union[str, Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s SCREAMING_SNAKE_CASE : str = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = s SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Any = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : str = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Optional[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Tuple = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[str]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = time() return end - begin def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Dict=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = time() return end - begin
79
1
'''simple docstring''' from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = """T5Config""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''mt5''' SCREAMING_SNAKE_CASE__ = MTaConfig class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''mt5''' SCREAMING_SNAKE_CASE__ = MTaConfig class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''mt5''' SCREAMING_SNAKE_CASE__ = MTaConfig
79
'''simple docstring''' import os 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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} __UpperCAmelCase = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } __UpperCAmelCase = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple="<s>" , lowerCamelCase_ : Union[str, Any]="</s>" , lowerCamelCase_ : Tuple="</s>" , lowerCamelCase_ : str="<s>" , lowerCamelCase_ : Optional[int]="<unk>" , lowerCamelCase_ : List[Any]="<pad>" , lowerCamelCase_ : Optional[Any]="<mask>" , lowerCamelCase_ : Optional[Dict[str, Any]] = None , **lowerCamelCase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Dict = vocab_file SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} SCREAMING_SNAKE_CASE : str = len(self.sp_model ) - 1 SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1, 1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [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] @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return len(self.sp_model ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = {self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str ): '''simple docstring''' return self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.PieceToId(lowerCamelCase_ ) return spm_id if spm_id else self.unk_token_id def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[str] ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Tuple = """""" SCREAMING_SNAKE_CASE : Dict = 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(lowerCamelCase_ ) + token SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(lowerCamelCase_ ) return out_string.strip() def __getstate__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE : List[Any] = None return state def __setstate__( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Dict = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCamelCase_ , """wb""" ) as fi: SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = 1 # (0 is vertical, 1 is horizontal) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = get_dataset(lowerCamelCase_ , lowerCamelCase_ ) print("""Processing...""" ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = update_image_and_anno(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for index, image in enumerate(lowerCamelCase_ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Optional[int] = random_chars(32 ) SCREAMING_SNAKE_CASE : Optional[Any] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE : Dict = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , lowerCamelCase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(lowerCamelCase_ )} with {file_name}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE : Optional[Any] = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(lowerCamelCase_ ) with open(f'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Any = [] for label_file in glob.glob(os.path.join(lowerCamelCase_ , """*.txt""" ) ): SCREAMING_SNAKE_CASE : str = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(lowerCamelCase_ ) as in_file: SCREAMING_SNAKE_CASE : Any = in_file.readlines() SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowerCamelCase_ , f'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE : Tuple = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : Union[str, Any] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(lowerCamelCase_ ) labels.append(lowerCamelCase_ ) return img_paths, labels def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [] for idx in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Dict = img_list[idx] path_list.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = anno_list[idx] SCREAMING_SNAKE_CASE : Optional[Any] = cva.imread(lowerCamelCase_ ) if flip_type == 1: SCREAMING_SNAKE_CASE : List[str] = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE : Any = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(lowerCamelCase_ ) new_imgs_list.append(lowerCamelCase_ ) return new_imgs_list, new_annos_lists, path_list def __A ( lowerCamelCase_ = 32 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : Dict = ascii_lowercase + digits return "".join(random.choice(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
79
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) SCREAMING_SNAKE_CASE : Dict = { """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 ), } SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , lowerCamelCase_ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
79
1
'''simple docstring''' class UpperCamelCase__ : """simple docstring""" def __init__( self : Union[str, Any] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = arr.split(""",""" ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [int(self.array[0] )] * len(self.array ) SCREAMING_SNAKE_CASE : str = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): SCREAMING_SNAKE_CASE : Optional[Any] = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) SCREAMING_SNAKE_CASE : Tuple = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": __UpperCAmelCase = input("""please input some numbers:""") __UpperCAmelCase = SubArray(whole_array) __UpperCAmelCase = array.solve_sub_array() print(("""the results is:""", re))
79
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''Translation''' , init=lowercase_ , repr=lowercase_ ) def __call__( self : int ): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''TranslationVariableLanguages''' , init=lowercase_ , repr=lowercase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = sorted(set(self.languages ) ) if self.languages else None SCREAMING_SNAKE_CASE : str = len(self.languages ) if self.languages else None def __call__( self : Tuple ): '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = set(self.languages ) if self.languages and set(lowerCamelCase_ ) - lang_set: raise ValueError( f'''Some languages in example ({", ".join(sorted(set(lowerCamelCase_ ) - lang_set ) )}) are not in valid set ({", ".join(lowerCamelCase_ )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE : List[Any] = [] for lang, text in translation_dict.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = zip(*sorted(lowerCamelCase_ ) ) return {"language": languages, "translation": translations} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
79
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class UpperCamelCase__ ( lowercase_ , lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = IFInpaintingPipeline SCREAMING_SNAKE_CASE__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} SCREAMING_SNAKE_CASE__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS SCREAMING_SNAKE_CASE__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return self._get_dummy_components() def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any=0 ): '''simple docstring''' if str(lowerCamelCase_ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=lowerCamelCase_ ).manual_seed(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase_ ) ).to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase_ ) ).to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowerCamelCase_ ( self : int ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def lowerCamelCase_ ( self : str ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' self._test_save_load_local() def lowerCamelCase_ ( self : Any ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
79
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , *lowerCamelCase_ : List[str] , **lowerCamelCase_ : Dict ): '''simple docstring''' warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , lowerCamelCase_ , ) super().__init__(*lowerCamelCase_ , **lowerCamelCase_ )
79
1
'''simple docstring''' import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' super().tearDown() gc.collect() def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE : Optional[int] = """xvjiarui/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = FlaxStableDiffusionInpaintPipeline.from_pretrained(lowerCamelCase_ , safety_checker=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE : Optional[Any] = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = 50 SCREAMING_SNAKE_CASE : int = jax.device_count() SCREAMING_SNAKE_CASE : List[Any] = num_samples * [prompt] SCREAMING_SNAKE_CASE : str = num_samples * [init_image] SCREAMING_SNAKE_CASE : Optional[int] = num_samples * [mask_image] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = pipeline.prepare_inputs(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # shard inputs and rng SCREAMING_SNAKE_CASE : Optional[int] = replicate(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = jax.random.split(lowerCamelCase_ , jax.device_count() ) SCREAMING_SNAKE_CASE : Union[str, Any] = shard(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = shard(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = shard(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipeline( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , jit=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = output.images.reshape(lowerCamelCase_ , 5_12 , 5_12 , 3 ) SCREAMING_SNAKE_CASE : List[str] = images[0, 2_53:2_56, 2_53:2_56, -1] SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE : Optional[Any] = jnp.array( [0.3_611_307, 0.37_649_736, 0.3_757_408, 0.38_213_953, 0.39_295_167, 0.3_841_631, 0.41_554_978, 0.4_137_475, 0.4_217_084] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
79
'''simple docstring''' 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 UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : str ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : int , lowerCamelCase_ : Dict ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Optional[int] ): '''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 lowerCamelCase_ ( cls : Any ): '''simple docstring''' return f'''`pip install {cls.pip_package or cls.name}`''' class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''optuna''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Dict ): '''simple docstring''' return run_hp_search_optuna(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Any ): '''simple docstring''' return default_hp_space_optuna(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''ray''' SCREAMING_SNAKE_CASE__ = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_ray_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_ray(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' return default_hp_space_ray(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''sigopt''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_sigopt(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return default_hp_space_sigopt(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''wandb''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return run_hp_search_wandb(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return default_hp_space_wandb(lowerCamelCase_ ) __UpperCAmelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCamelCase_ ) > 0: SCREAMING_SNAKE_CASE : List[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() ) )
79
1
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class UpperCamelCase__ ( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase_ : str=None , **lowerCamelCase_ : Dict ): '''simple docstring''' super().__init__(features=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch_tensor_kwargs import torch # noqa import torch at initialization def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and column: if all( isinstance(lowerCamelCase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : int ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , (str, bytes, type(lowerCamelCase_ )) ): return value elif isinstance(lowerCamelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE : str = {} if isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): SCREAMING_SNAKE_CASE : Any = {"""dtype""": torch.intaa} elif isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE : int = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowerCamelCase_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(lowerCamelCase_ ) return torch.tensor(lowerCamelCase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(lowerCamelCase_ , """__array__""" ) and not isinstance(lowerCamelCase_ , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowerCamelCase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) elif isinstance(lowerCamelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) return self._tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : dict ): '''simple docstring''' return map_nested(self._recursive_tensorize , lowerCamelCase_ , map_list=lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.numpy_arrow_extractor().extract_row(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_row(lowerCamelCase_ ) return self.recursive_tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.numpy_arrow_extractor().extract_column(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.python_features_decoder.decode_column(lowerCamelCase_ , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE : List[str] = self.recursive_tensorize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self._consolidate(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.numpy_arrow_extractor().extract_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.recursive_tensorize(lowerCamelCase_ ) for column_name in batch: SCREAMING_SNAKE_CASE : Tuple = self._consolidate(batch[column_name] ) return batch
79
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = 1 # (0 is vertical, 1 is horizontal) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = get_dataset(lowerCamelCase_ , lowerCamelCase_ ) print("""Processing...""" ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = update_image_and_anno(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for index, image in enumerate(lowerCamelCase_ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Optional[int] = random_chars(32 ) SCREAMING_SNAKE_CASE : Optional[Any] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE : Dict = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , lowerCamelCase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(lowerCamelCase_ )} with {file_name}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE : Optional[Any] = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(lowerCamelCase_ ) with open(f'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Any = [] for label_file in glob.glob(os.path.join(lowerCamelCase_ , """*.txt""" ) ): SCREAMING_SNAKE_CASE : str = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(lowerCamelCase_ ) as in_file: SCREAMING_SNAKE_CASE : Any = in_file.readlines() SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowerCamelCase_ , f'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE : Tuple = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : Union[str, Any] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(lowerCamelCase_ ) labels.append(lowerCamelCase_ ) return img_paths, labels def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [] for idx in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Dict = img_list[idx] path_list.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = anno_list[idx] SCREAMING_SNAKE_CASE : Optional[Any] = cva.imread(lowerCamelCase_ ) if flip_type == 1: SCREAMING_SNAKE_CASE : List[str] = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE : Any = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(lowerCamelCase_ ) new_imgs_list.append(lowerCamelCase_ ) return new_imgs_list, new_annos_lists, path_list def __A ( lowerCamelCase_ = 32 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : Dict = ascii_lowercase + digits return "".join(random.choice(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
79
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __UpperCAmelCase = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''vivit''' def __init__( self : Tuple , lowerCamelCase_ : str=2_24 , lowerCamelCase_ : List[Any]=32 , lowerCamelCase_ : Tuple=[2, 16, 16] , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Dict=12 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : List[Any]=30_72 , lowerCamelCase_ : List[str]="gelu_fast" , lowerCamelCase_ : str=0.0 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : List[Any]=1e-06 , lowerCamelCase_ : Tuple=True , **lowerCamelCase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Dict = num_frames SCREAMING_SNAKE_CASE : Optional[Any] = tubelet_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : int = qkv_bias super().__init__(**lowerCamelCase_ )
79
1
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse("""0.8.3"""): raise Exception("""requires gluonnlp == 0.8.3""") if version.parse(mx.__version__) != version.parse("""1.5.0"""): raise Exception("""requires mxnet == 1.5.0""") logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = """The Nymphenburg Palace is a beautiful palace in Munich!""" def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = { """attention_cell""": """multi_head""", """num_layers""": 4, """units""": 10_24, """hidden_size""": 7_68, """max_length""": 5_12, """num_heads""": 8, """scaled""": True, """dropout""": 0.1, """use_residual""": True, """embed_size""": 10_24, """embed_dropout""": 0.1, """word_embed""": None, """layer_norm_eps""": 1E-5, """token_type_vocab_size""": 2, } SCREAMING_SNAKE_CASE : List[str] = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py SCREAMING_SNAKE_CASE : Union[str, Any] = BERTEncoder( attention_cell=predefined_args["""attention_cell"""] , num_layers=predefined_args["""num_layers"""] , units=predefined_args["""units"""] , hidden_size=predefined_args["""hidden_size"""] , max_length=predefined_args["""max_length"""] , num_heads=predefined_args["""num_heads"""] , scaled=predefined_args["""scaled"""] , dropout=predefined_args["""dropout"""] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["""use_residual"""] , activation=predefined_args.get("""activation""" , """gelu""" ) , layer_norm_eps=predefined_args.get("""layer_norm_eps""" , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later SCREAMING_SNAKE_CASE : Optional[Any] = """openwebtext_ccnews_stories_books_cased""" # Specify download folder to Gluonnlp's vocab SCREAMING_SNAKE_CASE : List[str] = os.path.join(get_home_dir() , """models""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["""units"""] , embed_size=predefined_args["""embed_size"""] , embed_dropout=predefined_args["""embed_dropout"""] , word_embed=predefined_args["""word_embed"""] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["""token_type_vocab_size"""] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = original_bort._collect_params_with_prefix() # Build our config 🤗 SCREAMING_SNAKE_CASE : Tuple = { """architectures""": ["""BertForMaskedLM"""], """attention_probs_dropout_prob""": predefined_args["""dropout"""], """hidden_act""": """gelu""", """hidden_dropout_prob""": predefined_args["""dropout"""], """hidden_size""": predefined_args["""embed_size"""], """initializer_range""": 0.02, """intermediate_size""": predefined_args["""hidden_size"""], """layer_norm_eps""": predefined_args["""layer_norm_eps"""], """max_position_embeddings""": predefined_args["""max_length"""], """model_type""": """bort""", """num_attention_heads""": predefined_args["""num_heads"""], """num_hidden_layers""": predefined_args["""num_layers"""], """pad_token_id""": 1, # 2 = BERT, 1 = RoBERTa """type_vocab_size""": 1, # 2 = BERT, 1 = RoBERTa """vocab_size""": len(lowerCamelCase_ ), } SCREAMING_SNAKE_CASE : Optional[Any] = BertConfig.from_dict(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Any = hf_param.shape SCREAMING_SNAKE_CASE : Optional[Any] = to_torch(params[gluon_param] ) SCREAMING_SNAKE_CASE : Any = gluon_param.shape assert ( shape_hf == shape_gluon ), f'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param SCREAMING_SNAKE_CASE : Dict = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , """word_embed.0.weight""" ) SCREAMING_SNAKE_CASE : str = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , """encoder.position_weight""" ) SCREAMING_SNAKE_CASE : Dict = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , """encoder.layer_norm.beta""" ) SCREAMING_SNAKE_CASE : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , """encoder.layer_norm.gamma""" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) SCREAMING_SNAKE_CASE : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): SCREAMING_SNAKE_CASE : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention SCREAMING_SNAKE_CASE : BertSelfAttention = layer.attention.self SCREAMING_SNAKE_CASE : int = check_and_map_params( self_attn.key.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) SCREAMING_SNAKE_CASE : Any = check_and_map_params( self_attn.key.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) SCREAMING_SNAKE_CASE : List[str] = check_and_map_params( self_attn.query.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) SCREAMING_SNAKE_CASE : Any = check_and_map_params( self_attn.query.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) SCREAMING_SNAKE_CASE : str = check_and_map_params( self_attn.value.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) SCREAMING_SNAKE_CASE : List[Any] = check_and_map_params( self_attn.value.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output SCREAMING_SNAKE_CASE : BertSelfOutput = layer.attention.output SCREAMING_SNAKE_CASE : Any = check_and_map_params( self_output.dense.bias , f'''encoder.transformer_cells.{i}.proj.bias''' ) SCREAMING_SNAKE_CASE : Optional[int] = check_and_map_params( self_output.dense.weight , f'''encoder.transformer_cells.{i}.proj.weight''' ) SCREAMING_SNAKE_CASE : Tuple = check_and_map_params( self_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.layer_norm.beta''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = check_and_map_params( self_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate SCREAMING_SNAKE_CASE : BertIntermediate = layer.intermediate SCREAMING_SNAKE_CASE : Optional[int] = check_and_map_params( intermediate.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) SCREAMING_SNAKE_CASE : Tuple = check_and_map_params( intermediate.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output SCREAMING_SNAKE_CASE : BertOutput = layer.output SCREAMING_SNAKE_CASE : Tuple = check_and_map_params( bert_output.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) SCREAMING_SNAKE_CASE : int = check_and_map_params( bert_output.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) SCREAMING_SNAKE_CASE : str = check_and_map_params( bert_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) SCREAMING_SNAKE_CASE : Optional[Any] = check_and_map_params( bert_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models SCREAMING_SNAKE_CASE : Tuple = RobertaTokenizer.from_pretrained("""roberta-base""" ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode_plus(lowerCamelCase_ )["""input_ids"""] # Get gluon output SCREAMING_SNAKE_CASE : Tuple = mx.nd.array([input_ids] ) SCREAMING_SNAKE_CASE : Optional[Any] = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() SCREAMING_SNAKE_CASE : Any = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE : Optional[Any] = hf_bort_model(**lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : List[Any] = output_gluon[0].asnumpy() SCREAMING_SNAKE_CASE : List[str] = output_hf[0].detach().numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.max(np.abs(hf_layer - gluon_layer ) ).item() SCREAMING_SNAKE_CASE : Dict = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-3 ) if success: print("""✔️ Both model do output the same tensors""" ) else: print("""❌ Both model do **NOT** output the same tensors""" ) print("""Absolute difference is:""" , lowerCamelCase_ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--bort_checkpoint_path""", default=None, type=str, required=True, help="""Path the official Bort params file.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __UpperCAmelCase = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
79
'''simple docstring''' import math class UpperCamelCase__ : """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Tuple=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' SCREAMING_SNAKE_CASE : Any = n SCREAMING_SNAKE_CASE : Optional[int] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # adjacency matrix for weight SCREAMING_SNAKE_CASE : Union[str, Any] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # dp[i][j] stores minimum distance from i to j def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = w def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): SCREAMING_SNAKE_CASE : Union[str, Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": __UpperCAmelCase = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
79
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __UpperCAmelCase = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ['''pixel_values'''] def __init__( self : int , lowerCamelCase_ : bool = True , lowerCamelCase_ : Optional[Dict[str, int]] = None , lowerCamelCase_ : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase_ : bool = True , lowerCamelCase_ : bool = True , lowerCamelCase_ : Union[int, float] = 1 / 2_55 , lowerCamelCase_ : Dict[str, int] = None , lowerCamelCase_ : bool = True , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , **lowerCamelCase_ : Dict , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = size if size is not None else {"""height""": 2_24, """width""": 2_24} SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24} SCREAMING_SNAKE_CASE : str = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ , param_name="""crop_size""" ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : Dict = do_rescale SCREAMING_SNAKE_CASE : Dict = do_normalize SCREAMING_SNAKE_CASE : Tuple = do_center_crop SCREAMING_SNAKE_CASE : List[Any] = crop_size SCREAMING_SNAKE_CASE : Any = size SCREAMING_SNAKE_CASE : Tuple = resample SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE : List[str] = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else IMAGENET_DEFAULT_STD def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Dict[str, int] , lowerCamelCase_ : PILImageResampling = PILImageResampling.BILINEAR , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = get_size_dict(lowerCamelCase_ ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size(lowerCamelCase_ , size=size["""shortest_edge"""] , default_to_square=lowerCamelCase_ ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE : int = (size["""height"""], size["""width"""]) else: raise ValueError(f'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}''' ) return resize(lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Dict[str, int] , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = get_size_dict(lowerCamelCase_ ) 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(lowerCamelCase_ , size=(size["""height"""], size["""width"""]) , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : float , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : Any ): '''simple docstring''' return rescale(lowerCamelCase_ , scale=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Union[float, List[float]] , lowerCamelCase_ : Union[float, List[float]] , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : Union[str, Any] , ): '''simple docstring''' return normalize(lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : ImageInput , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Dict[str, int] = None , lowerCamelCase_ : PILImageResampling = None , lowerCamelCase_ : bool = None , lowerCamelCase_ : int = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[float] = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[str, TensorType]] = None , lowerCamelCase_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Tuple = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[Any] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(lowerCamelCase_ , param_name="""crop_size""" , default_to_square=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Dict = get_size_dict(lowerCamelCase_ ) if not is_batched(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : List[str] = [images] if not valid_images(lowerCamelCase_ ): 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.""" ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : int = [to_numpy_array(lowerCamelCase_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : int = [self.resize(image=lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE : List[Any] = [self.center_crop(image=lowerCamelCase_ , size=lowerCamelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Optional[int] = [self.rescale(image=lowerCamelCase_ , scale=lowerCamelCase_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Union[str, Any] = [self.normalize(image=lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ ) for image in images] SCREAMING_SNAKE_CASE : int = [to_channel_dimension_format(lowerCamelCase_ , lowerCamelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"""pixel_values""": images} return BatchFeature(data=lowerCamelCase_ , tensor_type=lowerCamelCase_ )
79
'''simple docstring''' import math def __A ( lowerCamelCase_ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __A ( lowerCamelCase_ = 1_00_01 ): """simple docstring""" try: SCREAMING_SNAKE_CASE : Tuple = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError("""Parameter nth must be int or castable to int.""" ) from None if nth <= 0: raise ValueError("""Parameter nth must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE : list[int] = [] SCREAMING_SNAKE_CASE : Dict = 2 while len(lowerCamelCase_ ) < nth: if is_prime(lowerCamelCase_ ): primes.append(lowerCamelCase_ ) num += 1 else: num += 1 return primes[len(lowerCamelCase_ ) - 1] if __name__ == "__main__": print(f'''{solution() = }''')
79
1
'''simple docstring''' 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_small""": [ """BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlenderbotSmallConfig""", """BlenderbotSmallOnnxConfig""", ], """tokenization_blenderbot_small""": ["""BlenderbotSmallTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""BlenderbotSmallTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlenderbotSmallForCausalLM""", """BlenderbotSmallForConditionalGeneration""", """BlenderbotSmallModel""", """BlenderbotSmallPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """TFBlenderbotSmallForConditionalGeneration""", """TFBlenderbotSmallModel""", """TFBlenderbotSmallPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """FlaxBlenderbotSmallForConditionalGeneration""", """FlaxBlenderbotSmallModel""", """FlaxBlenderbotSmallPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __UpperCAmelCase = {"""UserAgent""": UserAgent().random} def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = script.contents[0] SCREAMING_SNAKE_CASE : int = json.loads(data[data.find("""{\"config\"""" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f'''https://www.instagram.com/{username}/''' SCREAMING_SNAKE_CASE : Any = self.get_json() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = requests.get(self.url , headers=lowerCamelCase_ ).text SCREAMING_SNAKE_CASE : List[Any] = BeautifulSoup(lowerCamelCase_ , """html.parser""" ).find_all("""script""" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Dict ): '''simple docstring''' return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self : int ): '''simple docstring''' return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return self.user_data["username"] @property def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return self.user_data["full_name"] @property def lowerCamelCase_ ( self : int ): '''simple docstring''' return self.user_data["biography"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["business_email"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["external_url"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return self.user_data["is_verified"] @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.user_data["is_private"] def __A ( lowerCamelCase_ = "github" ): """simple docstring""" import os if os.environ.get("""CI""" ): return # test failing on GitHub Actions SCREAMING_SNAKE_CASE : Any = InstagramUser(lowerCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , lowerCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("""https://instagram.""" ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = InstagramUser("""github""") print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
79
1
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = ArgumentParser( description=( """PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes""" ) ) # Optional arguments for the launch helper parser.add_argument("""--num_cores""" , type=lowerCamelCase_ , default=1 , help="""Number of TPU cores to use (1 or 8).""" ) # positional parser.add_argument( """training_script""" , type=lowerCamelCase_ , help=( """The full path to the single TPU training """ """program/script to be launched in parallel, """ """followed by all the arguments for the """ """training script""" ) , ) # rest from the training program parser.add_argument("""training_script_args""" , nargs=lowerCamelCase_ ) return parser.parse_args() def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = parse_args() # Import training_script as a module. SCREAMING_SNAKE_CASE : Tuple = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) SCREAMING_SNAKE_CASE : Optional[Any] = script_fpath.stem SCREAMING_SNAKE_CASE : int = importlib.import_module(lowerCamelCase_ ) # Patch sys.argv SCREAMING_SNAKE_CASE : str = [args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
79
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __UpperCAmelCase = logging.getLogger(__name__) __UpperCAmelCase = """Hello world! cécé herlolip""" __UpperCAmelCase = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = BertAbsConfig( temp_dir=""".""" , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="""bert""" , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : int = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) SCREAMING_SNAKE_CASE : List[str] = AbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) , lowerCamelCase_ ) original.eval() SCREAMING_SNAKE_CASE : Optional[int] = BertAbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) SCREAMING_SNAKE_CASE : int = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE : Optional[int] = encoder_input_ids SCREAMING_SNAKE_CASE : Optional[Any] = decoder_input_ids SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE : str = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = original.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : str = new_model.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Any = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) __UpperCAmelCase = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
79
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """facebook/data2vec-text-base""": """https://huggingface.co/data2vec/resolve/main/config.json""", } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''data2vec-text''' def __init__( self : int , lowerCamelCase_ : Tuple=3_05_22 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : Union[str, Any]=12 , lowerCamelCase_ : Union[str, Any]=30_72 , lowerCamelCase_ : List[str]="gelu" , lowerCamelCase_ : List[str]=0.1 , lowerCamelCase_ : str=0.1 , lowerCamelCase_ : Optional[int]=5_12 , lowerCamelCase_ : Union[str, Any]=2 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : Union[str, Any]=1e-12 , lowerCamelCase_ : Dict=1 , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : Optional[Any]=2 , lowerCamelCase_ : Optional[Any]="absolute" , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : Optional[Any]=None , **lowerCamelCase_ : int , ): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE : Any = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = hidden_act SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Dict = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[int] = position_embedding_type SCREAMING_SNAKE_CASE : Any = use_cache SCREAMING_SNAKE_CASE : Any = classifier_dropout class UpperCamelCase__ ( lowercase_ ): """simple docstring""" @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE : Union[str, Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
79
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=True , lowerCamelCase_="pt" ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {"""add_prefix_space""": True} if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and not line.startswith(""" """ ) else {} SCREAMING_SNAKE_CASE : Optional[Any] = padding_side return tokenizer( [line] , max_length=lowerCamelCase_ , padding="""max_length""" if pad_to_max_length else None , truncation=lowerCamelCase_ , return_tensors=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , **lowerCamelCase_ , ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , ): """simple docstring""" SCREAMING_SNAKE_CASE : int = input_ids.ne(lowerCamelCase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : str , lowerCamelCase_ : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str]="train" , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : int=None , lowerCamelCase_ : Union[str, Any]="" , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : str = Path(lowerCamelCase_ ).joinpath(type_path + """.source""" ) SCREAMING_SNAKE_CASE : Optional[Any] = Path(lowerCamelCase_ ).joinpath(type_path + """.target""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_char_lens(self.src_file ) SCREAMING_SNAKE_CASE : int = max_source_length SCREAMING_SNAKE_CASE : str = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' SCREAMING_SNAKE_CASE : List[str] = tokenizer SCREAMING_SNAKE_CASE : Dict = prefix if n_obs is not None: SCREAMING_SNAKE_CASE : List[Any] = self.src_lens[:n_obs] SCREAMING_SNAKE_CASE : int = src_lang SCREAMING_SNAKE_CASE : Optional[int] = tgt_lang def __len__( self : List[Any] ): '''simple docstring''' return len(self.src_lens ) def __getitem__( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = index + 1 # linecache starts at 1 SCREAMING_SNAKE_CASE : Dict = self.prefix + linecache.getline(str(self.src_file ) , lowerCamelCase_ ).rstrip("""\n""" ) SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , lowerCamelCase_ ).rstrip("""\n""" ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , lowerCamelCase_ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer ) SCREAMING_SNAKE_CASE : Any = self.tokenizer.generator if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer SCREAMING_SNAKE_CASE : Optional[int] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_source_length , """right""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_target_length , """right""" ) SCREAMING_SNAKE_CASE : Tuple = source_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : Tuple = target_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : List[str] = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : Dict ): '''simple docstring''' return [len(lowerCamelCase_ ) for x in Path(lowerCamelCase_ ).open().readlines()] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = torch.stack([x["""input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""attention_mask"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""decoder_input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ , attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch __UpperCAmelCase = getLogger(__name__) def __A ( lowerCamelCase_ ): """simple docstring""" return list(itertools.chain.from_iterable(lowerCamelCase_ ) ) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = get_git_info() save_json(lowerCamelCase_ , os.path.join(lowerCamelCase_ , """git_log.json""" ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=4 , **lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """w""" ) as f: json.dump(lowerCamelCase_ , lowerCamelCase_ , indent=lowerCamelCase_ , **lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ ) as f: return json.load(lowerCamelCase_ ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = git.Repo(search_parent_directories=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { """repo_id""": str(lowerCamelCase_ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return list(map(lowerCamelCase_ , lowerCamelCase_ ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """wb""" ) as f: return pickle.dump(lowerCamelCase_ , lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" def remove_articles(lowerCamelCase_ ): return re.sub(R"""\b(a|an|the)\b""" , """ """ , lowerCamelCase_ ) def white_space_fix(lowerCamelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_ ) ) ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Optional[int] = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Tuple = Counter(lowerCamelCase_ ) & Counter(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = sum(common.values() ) if num_same == 0: return 0 SCREAMING_SNAKE_CASE : Optional[int] = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = (2 * precision * recall) / (precision + recall) return fa def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return normalize_answer(lowerCamelCase_ ) == normalize_answer(lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert len(lowerCamelCase_ ) == len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowerCamelCase_ , lowerCamelCase_ ): em += exact_match_score(lowerCamelCase_ , lowerCamelCase_ ) if len(lowerCamelCase_ ) > 0: em /= len(lowerCamelCase_ ) return {"em": em} def __A ( lowerCamelCase_ ): """simple docstring""" return model_prefix.startswith("""rag""" ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead SCREAMING_SNAKE_CASE : Dict = """dropout_rate""" for p in extra_params: if getattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): if not hasattr(lowerCamelCase_ , lowerCamelCase_ ) and not hasattr(lowerCamelCase_ , equivalent_param[p] ): logger.info("""config doesn't have a `{}` attribute""".format(lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) continue SCREAMING_SNAKE_CASE : Dict = p if hasattr(lowerCamelCase_ , lowerCamelCase_ ) else equivalent_param[p] setattr(lowerCamelCase_ , lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) return hparams, config
79
1
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __UpperCAmelCase = {"""UserAgent""": UserAgent().random} def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = script.contents[0] SCREAMING_SNAKE_CASE : int = json.loads(data[data.find("""{\"config\"""" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f'''https://www.instagram.com/{username}/''' SCREAMING_SNAKE_CASE : Any = self.get_json() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = requests.get(self.url , headers=lowerCamelCase_ ).text SCREAMING_SNAKE_CASE : List[Any] = BeautifulSoup(lowerCamelCase_ , """html.parser""" ).find_all("""script""" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Dict ): '''simple docstring''' return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self : int ): '''simple docstring''' return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return self.user_data["username"] @property def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return self.user_data["full_name"] @property def lowerCamelCase_ ( self : int ): '''simple docstring''' return self.user_data["biography"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["business_email"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["external_url"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return self.user_data["is_verified"] @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.user_data["is_private"] def __A ( lowerCamelCase_ = "github" ): """simple docstring""" import os if os.environ.get("""CI""" ): return # test failing on GitHub Actions SCREAMING_SNAKE_CASE : Any = InstagramUser(lowerCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , lowerCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("""https://instagram.""" ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = InstagramUser("""github""") print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
79
'''simple docstring''' def __A ( lowerCamelCase_ ): """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : List[str] = number while duplicate > 0: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = divmod(lowerCamelCase_ , 10 ) fact_sum += factorial(lowerCamelCase_ ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") __UpperCAmelCase = int(input("""Enter number: """).strip()) print( f'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
79
1
'''simple docstring''' import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors @require_tokenizers class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = MvpTokenizer SCREAMING_SNAKE_CASE__ = MvpTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = filter_roberta_detectors def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[int] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] SCREAMING_SNAKE_CASE : str = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Tuple = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] SCREAMING_SNAKE_CASE : str = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(lowerCamelCase_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowerCamelCase_ ) ) def lowerCamelCase_ ( self : Optional[Any] , **lowerCamelCase_ : List[str] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : List[Any] ): '''simple docstring''' return "lower newer", "lower newer" @cached_property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return MvpTokenizer.from_pretrained("""RUCAIBox/mvp""" ) @cached_property def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return MvpTokenizerFast.from_pretrained("""RUCAIBox/mvp""" ) @require_torch def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] SCREAMING_SNAKE_CASE : List[str] = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE : List[Any] = tokenizer(lowerCamelCase_ , max_length=len(lowerCamelCase_ ) , padding=lowerCamelCase_ , return_tensors="""pt""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE : int = batch.input_ids.tolist()[0] self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) # Test that special tokens are reset @require_torch def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE : int = tokenizer(lowerCamelCase_ , padding=lowerCamelCase_ , return_tensors="""pt""" ) # check if input_ids are returned and no labels self.assertIn("""input_ids""" , lowerCamelCase_ ) self.assertIn("""attention_mask""" , lowerCamelCase_ ) self.assertNotIn("""labels""" , lowerCamelCase_ ) self.assertNotIn("""decoder_attention_mask""" , lowerCamelCase_ ) @require_torch def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE : Dict = tokenizer(text_target=lowerCamelCase_ , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE : Dict = tokenizer( ["""I am a small frog""" * 10_24, """I am a small frog"""] , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , return_tensors="""pt""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) self.assertEqual(batch.input_ids.shape , (2, 10_24) ) @require_torch def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = ["""A long paragraph for summarization."""] SCREAMING_SNAKE_CASE : int = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE : List[Any] = tokenizer(lowerCamelCase_ , text_target=lowerCamelCase_ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE : List[str] = inputs["""input_ids"""] SCREAMING_SNAKE_CASE : int = inputs["""labels"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' pass def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE : List[str] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = """A, <mask> AllenNLP sentence.""" SCREAMING_SNAKE_CASE : Dict = tokenizer_r.encode_plus(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_p.encode_plus(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) SCREAMING_SNAKE_CASE : Dict = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( lowerCamelCase_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( lowerCamelCase_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
79
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class UpperCamelCase__ ( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase_ : str=None , **lowerCamelCase_ : Dict ): '''simple docstring''' super().__init__(features=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch_tensor_kwargs import torch # noqa import torch at initialization def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and column: if all( isinstance(lowerCamelCase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : int ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , (str, bytes, type(lowerCamelCase_ )) ): return value elif isinstance(lowerCamelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE : str = {} if isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): SCREAMING_SNAKE_CASE : Any = {"""dtype""": torch.intaa} elif isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE : int = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowerCamelCase_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(lowerCamelCase_ ) return torch.tensor(lowerCamelCase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(lowerCamelCase_ , """__array__""" ) and not isinstance(lowerCamelCase_ , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowerCamelCase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) elif isinstance(lowerCamelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) return self._tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : dict ): '''simple docstring''' return map_nested(self._recursive_tensorize , lowerCamelCase_ , map_list=lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.numpy_arrow_extractor().extract_row(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_row(lowerCamelCase_ ) return self.recursive_tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.numpy_arrow_extractor().extract_column(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.python_features_decoder.decode_column(lowerCamelCase_ , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE : List[str] = self.recursive_tensorize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self._consolidate(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.numpy_arrow_extractor().extract_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.recursive_tensorize(lowerCamelCase_ ) for column_name in batch: SCREAMING_SNAKE_CASE : Tuple = self._consolidate(batch[column_name] ) return batch
79
1
'''simple docstring''' import math __UpperCAmelCase = 10 __UpperCAmelCase = 7 __UpperCAmelCase = BALLS_PER_COLOUR * NUM_COLOURS def __A ( lowerCamelCase_ = 20 ): """simple docstring""" SCREAMING_SNAKE_CASE : int = math.comb(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = math.comb(NUM_BALLS - BALLS_PER_COLOUR , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = NUM_COLOURS * (1 - missing_colour / total) return f'''{result:.9f}''' if __name__ == "__main__": print(solution(20))
79
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCAmelCase = random.Random() def __A ( lowerCamelCase_ , lowerCamelCase_=1.0 , lowerCamelCase_=None , lowerCamelCase_=None ): """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE : Optional[Any] = global_rng SCREAMING_SNAKE_CASE : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int]=7 , lowerCamelCase_ : Optional[int]=4_00 , lowerCamelCase_ : int=20_00 , lowerCamelCase_ : List[str]=20_48 , lowerCamelCase_ : Optional[Any]=1_28 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : Dict=30 , lowerCamelCase_ : Dict=4_41_00 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = min_seq_length SCREAMING_SNAKE_CASE : Any = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : int = spectrogram_length SCREAMING_SNAKE_CASE : List[Any] = feature_size SCREAMING_SNAKE_CASE : Any = num_audio_channels SCREAMING_SNAKE_CASE : Tuple = hop_length SCREAMING_SNAKE_CASE : str = chunk_length SCREAMING_SNAKE_CASE : Dict = sampling_rate def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : Any=False ): '''simple docstring''' def _flatten(lowerCamelCase_ : Dict ): return list(itertools.chain(*lowerCamelCase_ ) ) if equal_length: SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(lowerCamelCase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = TvltFeatureExtractor def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TvltFeatureExtractionTester(self ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase_ , """spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """sampling_rate""" ) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Any = feat_extract_first.save_pretrained(lowerCamelCase_ )[0] check_json_file_has_correct_format(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : List[Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : int = os.path.join(lowerCamelCase_ , """feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class.from_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : int = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : List[str] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Optional[Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] SCREAMING_SNAKE_CASE : int = [np.asarray(lowerCamelCase_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 , mask_audio=lowerCamelCase_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] SCREAMING_SNAKE_CASE : int = np.asarray(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Union[str, Any] = ds.sort("""id""" ).select(range(lowerCamelCase_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : Tuple = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(lowerCamelCase_ , return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_92, 1_28) ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , lowerCamelCase_ , atol=1e-4 ) )
79
1
'''simple docstring''' import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline __UpperCAmelCase = argparse.ArgumentParser("""Stable Diffusion script with intel optimization""", add_help=False) parser.add_argument("""--dpm""", action="""store_true""", help="""Enable DPMSolver or not""") parser.add_argument("""--steps""", default=None, type=int, help="""Num inference steps""") __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = """cpu""" __UpperCAmelCase = """a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings""" __UpperCAmelCase = """path-to-your-trained-model""" __UpperCAmelCase = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: __UpperCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) __UpperCAmelCase = pipe.to(device) # to channels last __UpperCAmelCase = pipe.unet.to(memory_format=torch.channels_last) __UpperCAmelCase = pipe.vae.to(memory_format=torch.channels_last) __UpperCAmelCase = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: __UpperCAmelCase = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex __UpperCAmelCase = torch.randn(2, 4, 64, 64) __UpperCAmelCase = torch.rand(1) * 999 __UpperCAmelCase = torch.randn(2, 77, 768) __UpperCAmelCase = (sample, timestep, encoder_hidden_status) try: __UpperCAmelCase = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: __UpperCAmelCase = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) __UpperCAmelCase = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) __UpperCAmelCase = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: __UpperCAmelCase = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute __UpperCAmelCase = 666 __UpperCAmelCase = torch.Generator(device).manual_seed(seed) __UpperCAmelCase = {"""generator""": generator} if args.steps is not None: __UpperCAmelCase = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): __UpperCAmelCase = pipe(prompt, **generate_kwargs).images[0] # save image image.save("""generated.png""")
79
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __UpperCAmelCase = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
1
'''simple docstring''' from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 __UpperCAmelCase = { # 1536-bit 5: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 2048-bit 14: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AACAA68FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 3072-bit 15: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64""" + """ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7""" + """ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B""" + """F12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31""" + """43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 4096-bit 16: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64""" + """ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7""" + """ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B""" + """F12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31""" + """43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7""" + """88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA""" + """2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6""" + """287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED""" + """1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9""" + """93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199""" + """FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 6144-bit 17: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08""" + """8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B""" + """302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9""" + """A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6""" + """49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8""" + """FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C""" + """180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718""" + """3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D""" + """04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D""" + """B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226""" + """1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC""" + """E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26""" + """99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB""" + """04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2""" + """233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127""" + """D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492""" + """36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406""" + """AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918""" + """DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151""" + """2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03""" + """F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F""" + """BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA""" + """CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B""" + """B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632""" + """387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E""" + """6DCC4024FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 8192-bit 18: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64""" + """ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7""" + """ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B""" + """F12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31""" + """43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7""" + """88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA""" + """2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6""" + """287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED""" + """1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9""" + """93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492""" + """36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD""" + """F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831""" + """179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B""" + """DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF""" + """5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6""" + """D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3""" + """23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA""" + """CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328""" + """06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C""" + """DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE""" + """12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4""" + """38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300""" + """741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568""" + """3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9""" + """22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B""" + """4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A""" + """062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36""" + """4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1""" + """B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92""" + """4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47""" + """9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71""" + """60C980DD98EDD3DFFFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, } class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase_ : int = 14 ): '''simple docstring''' if group not in primes: raise ValueError("""Unsupported Group""" ) SCREAMING_SNAKE_CASE : str = primes[group]["""prime"""] SCREAMING_SNAKE_CASE : Union[str, Any] = primes[group]["""generator"""] SCREAMING_SNAKE_CASE : Tuple = int(hexlify(urandom(32 ) ) , base=16 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return hex(self.__private_key )[2:] def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = pow(self.generator , self.__private_key , self.prime ) return hex(lowerCamelCase_ )[2:] def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : int ): '''simple docstring''' return ( 2 <= key <= self.prime - 2 and pow(lowerCamelCase_ , (self.prime - 1) // 2 , self.prime ) == 1 ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = int(lowerCamelCase_ , base=16 ) if not self.is_valid_public_key(lowerCamelCase_ ): raise ValueError("""Invalid public key""" ) SCREAMING_SNAKE_CASE : Dict = pow(lowerCamelCase_ , self.__private_key , self.prime ) return shaaaa(str(lowerCamelCase_ ).encode() ).hexdigest() @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' return ( 2 <= remote_public_key_str <= prime - 2 and pow(lowerCamelCase_ , (prime - 1) // 2 , lowerCamelCase_ ) == 1 ) @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : str , lowerCamelCase_ : str , lowerCamelCase_ : int = 14 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = int(lowerCamelCase_ , base=16 ) SCREAMING_SNAKE_CASE : Union[str, Any] = int(lowerCamelCase_ , base=16 ) SCREAMING_SNAKE_CASE : Optional[Any] = primes[group]["""prime"""] if not DiffieHellman.is_valid_public_key_static(lowerCamelCase_ , lowerCamelCase_ ): raise ValueError("""Invalid public key""" ) SCREAMING_SNAKE_CASE : int = pow(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return shaaaa(str(lowerCamelCase_ ).encode() ).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
79
'''simple docstring''' __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
79
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''facebook/bart-large-mnli''' SCREAMING_SNAKE_CASE__ = ( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) SCREAMING_SNAKE_CASE__ = '''text_classifier''' SCREAMING_SNAKE_CASE__ = AutoTokenizer SCREAMING_SNAKE_CASE__ = AutoModelForSequenceClassification SCREAMING_SNAKE_CASE__ = ['''text''', ['''text''']] SCREAMING_SNAKE_CASE__ = ['''text'''] def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' super().setup() SCREAMING_SNAKE_CASE : int = self.model.config SCREAMING_SNAKE_CASE : Union[str, Any] = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(lowerCamelCase_ ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = labels return self.pre_processor( [text] * len(lowerCamelCase_ ) , [f'''This example is {label}''' for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = outputs.logits SCREAMING_SNAKE_CASE : Dict = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
79
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCAmelCase = """ Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)[\"depth\"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline(\"depth-estimation\") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to(\"cuda\") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to(\"cuda\") >>> img = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/cat.png\" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\") >>> prompt = \"A robot, 4k photo\" >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\" >>> generator = torch.Generator(device=\"cuda\").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save(\"robot_cat.png\") ``` """ def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=8 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Union[str, Any] , lowerCamelCase_ : UNetaDConditionModel , lowerCamelCase_ : DDPMScheduler , lowerCamelCase_ : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=lowerCamelCase_ , scheduler=lowerCamelCase_ , movq=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : str = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase_ ( self : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): '''simple docstring''' if latents is None: SCREAMING_SNAKE_CASE : Tuple = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ , device=lowerCamelCase_ , dtype=lowerCamelCase_ ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) SCREAMING_SNAKE_CASE : Dict = latents.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = latents * scheduler.init_noise_sigma return latents def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Dict=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE : List[Any] = torch.device(f'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple=0 ): '''simple docstring''' if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) SCREAMING_SNAKE_CASE : Any = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCamelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE : Union[str, Any] = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = cpu_offload_with_hook(lowerCamelCase_ , lowerCamelCase_ , prev_module_hook=lowerCamelCase_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE : str = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase_ ( self : str ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase_ , """_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() @replace_example_docstring(lowerCamelCase_ ) def __call__( self : Optional[Any] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : torch.FloatTensor , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 1_00 , lowerCamelCase_ : float = 4.0 , lowerCamelCase_ : int = 1 , lowerCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase_ : Optional[torch.FloatTensor] = None , lowerCamelCase_ : Optional[str] = "pil" , lowerCamelCase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._execution_device SCREAMING_SNAKE_CASE : Optional[int] = guidance_scale > 1.0 if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Any = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : List[Any] = image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Optional[int] = negative_image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Dict = hint.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) self.scheduler.set_timesteps(lowerCamelCase_ , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.timesteps SCREAMING_SNAKE_CASE : Any = self.movq.config.latent_channels SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = downscale_height_and_width(lowerCamelCase_ , lowerCamelCase_ , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCamelCase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Union[str, Any] = {"""image_embeds""": image_embeds, """hint""": hint} SCREAMING_SNAKE_CASE : Dict = self.unet( sample=lowerCamelCase_ , timestep=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , added_cond_kwargs=lowerCamelCase_ , return_dict=lowerCamelCase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE : str = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : str = self.scheduler.step( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ , )[0] # post-processing SCREAMING_SNAKE_CASE : List[str] = self.movq.decode(lowerCamelCase_ , force_not_quantize=lowerCamelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE : Optional[int] = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : List[Any] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Any = self.numpy_to_pil(lowerCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase_ )
79
1
'''simple docstring''' import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def __A ( lowerCamelCase_ ): """simple docstring""" assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def __A ( ): """simple docstring""" assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = """mock-s3-bucket""" SCREAMING_SNAKE_CASE : int = f'''s3://{mock_bucket}''' SCREAMING_SNAKE_CASE : Optional[Any] = extract_path_from_uri(lowerCamelCase_ ) assert dataset_path.startswith("""s3://""" ) is False SCREAMING_SNAKE_CASE : Optional[int] = """./local/path""" SCREAMING_SNAKE_CASE : Dict = extract_path_from_uri(lowerCamelCase_ ) assert dataset_path == new_dataset_path def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = is_remote_filesystem(lowerCamelCase_ ) assert is_remote is True SCREAMING_SNAKE_CASE : List[str] = fsspec.filesystem("""file""" ) SCREAMING_SNAKE_CASE : Any = is_remote_filesystem(lowerCamelCase_ ) assert is_remote is False @pytest.mark.parametrize("""compression_fs_class""" , lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_file, """bz2""": bza_file, """lz4""": lza_file} SCREAMING_SNAKE_CASE : List[str] = input_paths[compression_fs_class.protocol] if input_path is None: SCREAMING_SNAKE_CASE : Dict = f'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = fsspec.filesystem(compression_fs_class.protocol , fo=lowerCamelCase_ ) assert isinstance(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = os.path.basename(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = expected_filename[: expected_filename.rindex(""".""" )] assert fs.glob("""*""" ) == [expected_filename] with fs.open(lowerCamelCase_ , """r""" , encoding="""utf-8""" ) as f, open(lowerCamelCase_ , encoding="""utf-8""" ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("""protocol""" , ["""zip""", """gzip"""] ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = {"""zip""": zip_jsonl_path, """gzip""": jsonl_gz_path} SCREAMING_SNAKE_CASE : int = compressed_file_paths[protocol] SCREAMING_SNAKE_CASE : int = """dataset.jsonl""" SCREAMING_SNAKE_CASE : List[str] = f'''{protocol}://{member_file_path}::{compressed_file_path}''' SCREAMING_SNAKE_CASE, *SCREAMING_SNAKE_CASE : Optional[int] = fsspec.get_fs_token_paths(lowerCamelCase_ ) assert fs.isfile(lowerCamelCase_ ) assert not fs.isfile("""non_existing_""" + member_file_path ) @pytest.mark.integration def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = hf_api.dataset_info(lowerCamelCase_ , token=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = HfFileSystem(repo_info=lowerCamelCase_ , token=lowerCamelCase_ ) assert sorted(hffs.glob("""*""" ) ) == [".gitattributes", "data"] assert hffs.isdir("""data""" ) assert hffs.isfile(""".gitattributes""" ) and hffs.isfile("""data/text_data.txt""" ) with open(lowerCamelCase_ ) as f: assert hffs.open("""data/text_data.txt""" , """r""" ).read() == f.read() def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = """bz2""" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(lowerCamelCase_ , lowerCamelCase_ , clobber=lowerCamelCase_ ) with pytest.warns(lowerCamelCase_ ) as warning_info: importlib.reload(datasets.filesystems ) assert len(lowerCamelCase_ ) == 1 assert ( str(warning_info[0].message ) == f'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
79
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """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""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = BigBirdTokenizer SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] SCREAMING_SNAKE_CASE__ = [] def __init__( self : Any , lowerCamelCase_ : str=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict="<unk>" , lowerCamelCase_ : int="<s>" , lowerCamelCase_ : Optional[Any]="</s>" , lowerCamelCase_ : Dict="<pad>" , lowerCamelCase_ : Tuple="[SEP]" , lowerCamelCase_ : Dict="[MASK]" , lowerCamelCase_ : Union[str, Any]="[CLS]" , **lowerCamelCase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else bos_token SCREAMING_SNAKE_CASE : Dict = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else eos_token SCREAMING_SNAKE_CASE : Optional[Any] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else unk_token SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else pad_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else cls_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Optional[Any] = False if not self.vocab_file else True def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : 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] def lowerCamelCase_ ( self : str , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' 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(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Tuple = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ): copyfile(self.vocab_file , lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = s.rsplit(lowerCamelCase_ , lowerCamelCase_ ) return new.join(lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {} SCREAMING_SNAKE_CASE : Optional[Any] = ["""group_1""", """group_2""", """group_3""", """group_4"""] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: SCREAMING_SNAKE_CASE : Dict = key.replace(f'''{group_key}.''' , f'''{group_key}.group.''' ) if "res_path" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.replace("""res_path.""" , """res_path.path.""" ) if key.endswith(""".w""" ): SCREAMING_SNAKE_CASE : Dict = rreplace(lowerCamelCase_ , """.w""" , """.weight""" , 1 ) if key.endswith(""".b""" ): SCREAMING_SNAKE_CASE : Optional[Any] = rreplace(lowerCamelCase_ , """.b""" , """.bias""" , 1 ) SCREAMING_SNAKE_CASE : Tuple = value.float() return upgrade @torch.no_grad() def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , lowerCamelCase_=True ): """simple docstring""" from dall_e import Encoder SCREAMING_SNAKE_CASE : Any = Encoder() if os.path.exists(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : str = torch.load(lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE : Tuple = torch.hub.load_state_dict_from_url(lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : List[str] = ckpt.state_dict() encoder.load_state_dict(lowerCamelCase_ ) if config_path is not None: SCREAMING_SNAKE_CASE : List[Any] = FlavaImageCodebookConfig.from_pretrained(lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[int] = FlavaImageCodebookConfig() SCREAMING_SNAKE_CASE : int = FlavaImageCodebook(lowerCamelCase_ ).eval() SCREAMING_SNAKE_CASE : Dict = encoder.state_dict() SCREAMING_SNAKE_CASE : Dict = upgrade_state_dict(lowerCamelCase_ ) hf_model.load_state_dict(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = hf_model.state_dict() SCREAMING_SNAKE_CASE : str = count_parameters(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = count_parameters(lowerCamelCase_ ) assert torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-3 ) if save_checkpoint: hf_model.save_pretrained(lowerCamelCase_ ) else: return hf_state_dict if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to flava checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") __UpperCAmelCase = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
79
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""swish""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = get_activation("""silu""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""mish""" ) self.assertIsInstance(lowerCamelCase_ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = get_activation("""gelu""" ) self.assertIsInstance(lowerCamelCase_ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
79
1
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): __UpperCAmelCase = yaml.safe_load( """\ name: \"\" allow_empty: false allow_empty_text: true subsections: - name: \"Dataset Card for X\" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: \"Table of Contents\" allow_empty: false allow_empty_text: false subsections: null - name: \"Dataset Description\" allow_empty: false allow_empty_text: false subsections: - name: \"Dataset Summary\" allow_empty: false allow_empty_text: false subsections: null - name: \"Supported Tasks and Leaderboards\" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null """ ) __UpperCAmelCase = { """name""": """root""", """text""": """""", """is_empty_text""": True, """subsections""": [ { """name""": """Dataset Card for My Dataset""", """text""": """""", """is_empty_text""": True, """subsections""": [ {"""name""": """Table of Contents""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": []}, { """name""": """Dataset Description""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": [ { """name""": """Dataset Summary""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": [], }, { """name""": """Supported Tasks and Leaderboards""", """text""": """""", """is_empty_text""": True, """subsections""": [], }, {"""name""": """Languages""", """text""": """Language Text""", """is_empty_text""": False, """subsections""": []}, ], }, ], } ], } __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = { """name""": """root""", """text""": """""", """is_empty_text""": True, """subsections""": [ { """name""": """Dataset Card for My Dataset""", """text""": """""", """is_empty_text""": True, """subsections""": [ {"""name""": """Table of Contents""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": []}, { """name""": """Dataset Description""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": [ { """name""": """Dataset Summary""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": [ { """name""": """Extra Ignored Subsection""", """text""": """""", """is_empty_text""": True, """subsections""": [], } ], }, { """name""": """Supported Tasks and Leaderboards""", """text""": """""", """is_empty_text""": True, """subsections""": [], }, {"""name""": """Languages""", """text""": """Language Text""", """is_empty_text""": False, """subsections""": []}, ], }, ], } ], } __UpperCAmelCase = """\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = ( """The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.""" ) __UpperCAmelCase = """\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = ( """The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.""" ) __UpperCAmelCase = """\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.""" __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).""" __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'.""" __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.""" __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.""" __UpperCAmelCase = """\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.""" __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.""" __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.""" __UpperCAmelCase = """""" __UpperCAmelCase = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.""" __UpperCAmelCase = """\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ __UpperCAmelCase = """The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.""" @pytest.mark.parametrize( """readme_md, expected_dict""" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert ReadMe.from_string(lowerCamelCase_ , lowerCamelCase_ ).to_dict() == expected_dict @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with pytest.raises(lowerCamelCase_ , match=re.escape(expected_error.format(path="""root""" ) ) ): SCREAMING_SNAKE_CASE : Optional[int] = ReadMe.from_string(lowerCamelCase_ , lowerCamelCase_ ) readme.validate() @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with pytest.raises(lowerCamelCase_ , match=re.escape(expected_error.format(path="""root""" ) ) ): ReadMe.from_string(lowerCamelCase_ , lowerCamelCase_ ) @pytest.mark.parametrize( """readme_md,""" , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( lowerCamelCase_ ): """simple docstring""" ReadMe.from_string(lowerCamelCase_ , lowerCamelCase_ , suppress_parsing_errors=lowerCamelCase_ ) @pytest.mark.parametrize( """readme_md, expected_dict""" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Dict = Path(lowerCamelCase_ ) / """README.md""" with open(lowerCamelCase_ , """w+""" ) as readme_file: readme_file.write(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = ReadMe.from_readme(lowerCamelCase_ , lowerCamelCase_ ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : List[Any] = Path(lowerCamelCase_ ) / """README.md""" with open(lowerCamelCase_ , """w+""" ) as readme_file: readme_file.write(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = expected_error.format(path=lowerCamelCase_ ) with pytest.raises(lowerCamelCase_ , match=re.escape(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : Optional[int] = ReadMe.from_readme(lowerCamelCase_ , lowerCamelCase_ ) readme.validate() @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : List[str] = Path(lowerCamelCase_ ) / """README.md""" with open(lowerCamelCase_ , """w+""" ) as readme_file: readme_file.write(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = expected_error.format(path=lowerCamelCase_ ) with pytest.raises(lowerCamelCase_ , match=re.escape(lowerCamelCase_ ) ): ReadMe.from_readme(lowerCamelCase_ , lowerCamelCase_ ) @pytest.mark.parametrize( """readme_md,""" , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( lowerCamelCase_ ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Tuple = Path(lowerCamelCase_ ) / """README.md""" with open(lowerCamelCase_ , """w+""" ) as readme_file: readme_file.write(lowerCamelCase_ ) ReadMe.from_readme(lowerCamelCase_ , lowerCamelCase_ , suppress_parsing_errors=lowerCamelCase_ )
79
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''deberta-v2''' def __init__( self : int , lowerCamelCase_ : Optional[Any]=12_81_00 , lowerCamelCase_ : str=15_36 , lowerCamelCase_ : int=24 , lowerCamelCase_ : List[str]=24 , lowerCamelCase_ : List[Any]=61_44 , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : str=0 , lowerCamelCase_ : Union[str, Any]=0.02 , lowerCamelCase_ : Dict=1e-7 , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : Optional[int]=-1 , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : Dict="gelu" , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : List[Any] = relative_attention SCREAMING_SNAKE_CASE : str = max_relative_positions SCREAMING_SNAKE_CASE : int = pad_token_id SCREAMING_SNAKE_CASE : List[str] = position_biased_input # Backwards compatibility if type(lowerCamelCase_ ) == str: SCREAMING_SNAKE_CASE : Dict = [x.strip() for x in pos_att_type.lower().split("""|""" )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = kwargs.get("""pooler_hidden_size""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = pooler_dropout SCREAMING_SNAKE_CASE : Any = pooler_hidden_act class UpperCamelCase__ ( lowercase_ ): """simple docstring""" @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE : Union[str, Any] = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return 12 def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional["TensorType"] = None , lowerCamelCase_ : int = 3 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = super().generate_dummy_inputs(preprocessor=lowerCamelCase_ , framework=lowerCamelCase_ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
79
1
'''simple docstring''' import math def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if ( not isinstance(lowerCamelCase_ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * power_factor def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if ( not isinstance(lowerCamelCase_ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
79
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = {} def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: SCREAMING_SNAKE_CASE : str = [[w, v]] if not self.graph.get(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = [] def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : str ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[str, Any]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Tuple = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Any = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[int]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : str = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : Union[str, Any] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Any=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = deque() SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : int = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Optional[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Union[str, Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : List[str] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[Any] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : int = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return sorted_nodes def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : Union[str, Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Any = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : int = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = s SCREAMING_SNAKE_CASE : List[Any] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = -2 SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Tuple = s SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : str = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Dict = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[str] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = s SCREAMING_SNAKE_CASE : Optional[int] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str=-2 , lowerCamelCase_ : int=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin def lowerCamelCase_ ( self : int , lowerCamelCase_ : Tuple=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, v]] # add the other way if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, u]] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) # the other way round if self.graph.get(lowerCamelCase_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : str=-2 , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] if s == -2: SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : Any = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : List[str] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = deque() SCREAMING_SNAKE_CASE : Tuple = [] if s == -2: SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : List[Any] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = -2 SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Optional[Any] = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : str = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Optional[int] = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Union[str, Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s SCREAMING_SNAKE_CASE : str = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = s SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Any = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : str = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Optional[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Tuple = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[str]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = time() return end - begin def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Dict=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = time() return end - begin
79
1
'''simple docstring''' from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class UpperCamelCase__ : """simple docstring""" def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' raise NotImplementedError() def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' raise NotImplementedError() class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : "AutoTokenizer" , lowerCamelCase_ : bool = False , **lowerCamelCase_ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer SCREAMING_SNAKE_CASE : List[Any] = skip_prompt SCREAMING_SNAKE_CASE : List[Any] = decode_kwargs # variables used in the streaming process SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Any = 0 SCREAMING_SNAKE_CASE : Optional[Any] = True def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[str] ): '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("""TextStreamer only supports batch size 1""" ) elif len(value.shape ) > 1: SCREAMING_SNAKE_CASE : Optional[Any] = value[0] if self.skip_prompt and self.next_tokens_are_prompt: SCREAMING_SNAKE_CASE : str = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("""\n""" ): SCREAMING_SNAKE_CASE : Any = text[self.print_len :] SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Union[str, Any] = 0 # If the last token is a CJK character, we print the characters. elif len(lowerCamelCase_ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): SCREAMING_SNAKE_CASE : Any = text[self.print_len :] self.print_len += len(lowerCamelCase_ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: SCREAMING_SNAKE_CASE : Any = text[self.print_len : text.rfind(""" """ ) + 1] self.print_len += len(lowerCamelCase_ ) self.on_finalized_text(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' if len(self.token_cache ) > 0: SCREAMING_SNAKE_CASE : List[str] = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) SCREAMING_SNAKE_CASE : str = text[self.print_len :] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[int] = 0 else: SCREAMING_SNAKE_CASE : int = """""" SCREAMING_SNAKE_CASE : int = True self.on_finalized_text(lowerCamelCase_ , stream_end=lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : bool = False ): '''simple docstring''' print(lowerCamelCase_ , flush=lowerCamelCase_ , end="""""" if not stream_end else None ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if ( (cp >= 0X4_e00 and cp <= 0X9_fff) or (cp >= 0X3_400 and cp <= 0X4_dbf) # or (cp >= 0X20_000 and cp <= 0X2a_6df) # or (cp >= 0X2a_700 and cp <= 0X2b_73f) # or (cp >= 0X2b_740 and cp <= 0X2b_81f) # or (cp >= 0X2b_820 and cp <= 0X2c_eaf) # or (cp >= 0Xf_900 and cp <= 0Xf_aff) or (cp >= 0X2f_800 and cp <= 0X2f_a1f) # ): # return True return False class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : "AutoTokenizer" , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional[float] = None , **lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' super().__init__(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = Queue() SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : List[Any] = timeout def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : bool = False ): '''simple docstring''' self.text_queue.put(lowerCamelCase_ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self : str ): '''simple docstring''' return self def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
79
'''simple docstring''' import os 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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} __UpperCAmelCase = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } __UpperCAmelCase = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple="<s>" , lowerCamelCase_ : Union[str, Any]="</s>" , lowerCamelCase_ : Tuple="</s>" , lowerCamelCase_ : str="<s>" , lowerCamelCase_ : Optional[int]="<unk>" , lowerCamelCase_ : List[Any]="<pad>" , lowerCamelCase_ : Optional[Any]="<mask>" , lowerCamelCase_ : Optional[Dict[str, Any]] = None , **lowerCamelCase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Dict = vocab_file SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} SCREAMING_SNAKE_CASE : str = len(self.sp_model ) - 1 SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1, 1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [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] @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return len(self.sp_model ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = {self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str ): '''simple docstring''' return self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.PieceToId(lowerCamelCase_ ) return spm_id if spm_id else self.unk_token_id def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[str] ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Tuple = """""" SCREAMING_SNAKE_CASE : Dict = 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(lowerCamelCase_ ) + token SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(lowerCamelCase_ ) return out_string.strip() def __getstate__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE : List[Any] = None return state def __setstate__( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Dict = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCamelCase_ , """wb""" ) as fi: SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def __A ( lowerCamelCase_ , lowerCamelCase_="shi-labs/oneformer_demo" ): """simple docstring""" with open(hf_hub_download(lowerCamelCase_ , lowerCamelCase_ , repo_type="""dataset""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE : Any = json.load(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = {} SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Optional[int] = [] for key, info in class_info.items(): SCREAMING_SNAKE_CASE : str = info["""name"""] class_names.append(info["""name"""] ) if info["isthing"]: thing_ids.append(int(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : List[str] = thing_ids SCREAMING_SNAKE_CASE : List[str] = class_names return metadata class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[Any]=7 , lowerCamelCase_ : Dict=3 , lowerCamelCase_ : str=30 , lowerCamelCase_ : List[str]=4_00 , lowerCamelCase_ : int=None , lowerCamelCase_ : int=True , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Dict=[0.5, 0.5, 0.5] , lowerCamelCase_ : Any=[0.5, 0.5, 0.5] , lowerCamelCase_ : str=10 , lowerCamelCase_ : Any=False , lowerCamelCase_ : Union[str, Any]=2_55 , lowerCamelCase_ : Optional[Any]="shi-labs/oneformer_demo" , lowerCamelCase_ : Tuple="ade20k_panoptic.json" , lowerCamelCase_ : int=10 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = parent SCREAMING_SNAKE_CASE : Any = batch_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE : List[str] = min_resolution SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : Tuple = {"""shortest_edge""": 32, """longest_edge""": 13_33} if size is None else size SCREAMING_SNAKE_CASE : Any = do_normalize SCREAMING_SNAKE_CASE : Optional[Any] = image_mean SCREAMING_SNAKE_CASE : List[Any] = image_std SCREAMING_SNAKE_CASE : List[Any] = class_info_file SCREAMING_SNAKE_CASE : Tuple = prepare_metadata(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = num_text SCREAMING_SNAKE_CASE : int = repo_path # for the post_process_functions SCREAMING_SNAKE_CASE : List[Any] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = 10 SCREAMING_SNAKE_CASE : Tuple = 10 SCREAMING_SNAKE_CASE : List[str] = 3 SCREAMING_SNAKE_CASE : Optional[int] = 4 SCREAMING_SNAKE_CASE : Any = num_labels SCREAMING_SNAKE_CASE : Tuple = do_reduce_labels SCREAMING_SNAKE_CASE : Dict = ignore_index def lowerCamelCase_ ( self : Union[str, Any] ): '''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, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[int]=False ): '''simple docstring''' if not batched: SCREAMING_SNAKE_CASE : Union[str, Any] = image_inputs[0] if isinstance(lowerCamelCase_ , Image.Image ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = image.size else: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE : List[Any] = int(self.size["""shortest_edge"""] * h / w ) SCREAMING_SNAKE_CASE : Optional[Any] = self.size["""shortest_edge"""] elif w > h: SCREAMING_SNAKE_CASE : Optional[Any] = self.size["""shortest_edge"""] SCREAMING_SNAKE_CASE : Optional[int] = int(self.size["""shortest_edge"""] * w / h ) else: SCREAMING_SNAKE_CASE : List[str] = self.size["""shortest_edge"""] SCREAMING_SNAKE_CASE : List[str] = self.size["""shortest_edge"""] else: SCREAMING_SNAKE_CASE : Optional[int] = [] for image in image_inputs: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) SCREAMING_SNAKE_CASE : Any = max(lowerCamelCase_ , key=lambda lowerCamelCase_ : item[0] )[0] SCREAMING_SNAKE_CASE : Any = max(lowerCamelCase_ , key=lambda lowerCamelCase_ : item[1] )[1] return expected_height, expected_width def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string SCREAMING_SNAKE_CASE__ = image_processing_class def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = OneFormerImageProcessorTester(self ) @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.image_processing_tester.prepare_image_processor_dict() def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase_ , """image_mean""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """image_std""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """do_normalize""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """size""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """ignore_index""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """class_info_file""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """num_text""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """repo_path""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """metadata""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """do_reduce_labels""" ) ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase_ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : int = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = self.image_processing_tester.get_expected_values(lowerCamelCase_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_tester.get_expected_values(lowerCamelCase_ , batched=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = image_processor( lowerCamelCase_ , ["""semantic"""] * len(lowerCamelCase_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase_ , numpify=lowerCamelCase_ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase_ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Dict = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self.image_processing_tester.get_expected_values(lowerCamelCase_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_tester.get_expected_values(lowerCamelCase_ , batched=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = image_processor( lowerCamelCase_ , ["""semantic"""] * len(lowerCamelCase_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase_ , torchify=lowerCamelCase_ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[int] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self.image_processing_tester.get_expected_values(lowerCamelCase_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_tester.get_expected_values(lowerCamelCase_ , batched=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor( lowerCamelCase_ , ["""semantic"""] * len(lowerCamelCase_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[Any]=False , lowerCamelCase_ : Union[str, Any]=False , lowerCamelCase_ : Tuple="np" ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # prepare image and target SCREAMING_SNAKE_CASE : Any = self.image_processing_tester.num_labels SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : str = prepare_image_inputs(self.image_processing_tester , equal_resolution=lowerCamelCase_ ) if with_segmentation_maps: SCREAMING_SNAKE_CASE : str = num_labels if is_instance_map: SCREAMING_SNAKE_CASE : Dict = list(range(lowerCamelCase_ ) ) * 2 SCREAMING_SNAKE_CASE : List[Any] = dict(enumerate(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Tuple = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": SCREAMING_SNAKE_CASE : List[str] = [Image.fromarray(lowerCamelCase_ ) for annotation in annotations] SCREAMING_SNAKE_CASE : str = image_processor( lowerCamelCase_ , ["""semantic"""] * len(lowerCamelCase_ ) , lowerCamelCase_ , return_tensors="""pt""" , instance_id_to_semantic_id=lowerCamelCase_ , pad_and_return_pixel_mask=lowerCamelCase_ , ) return inputs def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' pass def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' def common(lowerCamelCase_ : List[str]=False , lowerCamelCase_ : int=None ): SCREAMING_SNAKE_CASE : Optional[Any] = self.comm_get_image_processor_inputs( with_segmentation_maps=lowerCamelCase_ , is_instance_map=lowerCamelCase_ , segmentation_type=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inputs["""mask_labels"""] SCREAMING_SNAKE_CASE : Optional[Any] = inputs["""class_labels"""] SCREAMING_SNAKE_CASE : Tuple = inputs["""pixel_values"""] SCREAMING_SNAKE_CASE : Optional[Any] = inputs["""text_inputs"""] # check the batch_size for mask_label, class_label, text_input in zip(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(lowerCamelCase_ ) , self.image_processing_tester.num_text ) common() common(is_instance_map=lowerCamelCase_ ) common(is_instance_map=lowerCamelCase_ , segmentation_type="""pil""" ) common(is_instance_map=lowerCamelCase_ , segmentation_type="""pil""" ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = np.zeros((20, 50) ) SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : str = 1 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Tuple = binary_mask_to_rle(lowerCamelCase_ ) self.assertEqual(len(lowerCamelCase_ ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_tester.get_fake_oneformer_outputs() SCREAMING_SNAKE_CASE : Optional[Any] = fature_extractor.post_process_semantic_segmentation(lowerCamelCase_ ) self.assertEqual(len(lowerCamelCase_ ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) SCREAMING_SNAKE_CASE : Optional[Any] = [(1, 4) for i in range(self.image_processing_tester.batch_size )] SCREAMING_SNAKE_CASE : Dict = fature_extractor.post_process_semantic_segmentation(lowerCamelCase_ , target_sizes=lowerCamelCase_ ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) SCREAMING_SNAKE_CASE : List[str] = self.image_processing_tester.get_fake_oneformer_outputs() SCREAMING_SNAKE_CASE : List[Any] = image_processor.post_process_instance_segmentation(lowerCamelCase_ , threshold=0 ) self.assertTrue(len(lowerCamelCase_ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , lowerCamelCase_ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) SCREAMING_SNAKE_CASE : List[str] = self.image_processing_tester.get_fake_oneformer_outputs() SCREAMING_SNAKE_CASE : Any = image_processor.post_process_panoptic_segmentation(lowerCamelCase_ , threshold=0 ) self.assertTrue(len(lowerCamelCase_ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , lowerCamelCase_ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
79
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) SCREAMING_SNAKE_CASE : Dict = { """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 ), } SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , lowerCamelCase_ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
79
1
'''simple docstring''' import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors __UpperCAmelCase = logging.getLogger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''sequence-classification''' def __init__( self : Optional[int] , lowerCamelCase_ : str ): '''simple docstring''' if type(lowerCamelCase_ ) == dict: SCREAMING_SNAKE_CASE : List[Any] = Namespace(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = glue_output_modes[hparams.task] SCREAMING_SNAKE_CASE : Any = glue_tasks_num_labels[hparams.task] super().__init__(lowerCamelCase_ , lowerCamelCase_ , self.mode ) def lowerCamelCase_ ( self : List[Any] , **lowerCamelCase_ : Any ): '''simple docstring''' return self.model(**lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: SCREAMING_SNAKE_CASE : List[str] = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None SCREAMING_SNAKE_CASE : List[Any] = self(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.trainer.lr_schedulers[0]["""scheduler"""] SCREAMING_SNAKE_CASE : Optional[Any] = {"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.hparams SCREAMING_SNAKE_CASE : Tuple = processors[args.task]() SCREAMING_SNAKE_CASE : Any = processor.get_labels() for mode in ["train", "dev"]: SCREAMING_SNAKE_CASE : str = self._feature_file(lowerCamelCase_ ) if os.path.exists(lowerCamelCase_ ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , lowerCamelCase_ ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) SCREAMING_SNAKE_CASE : int = ( processor.get_dev_examples(args.data_dir ) if mode == """dev""" else processor.get_train_examples(args.data_dir ) ) SCREAMING_SNAKE_CASE : List[Any] = convert_examples_to_features( lowerCamelCase_ , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("""Saving features into cached file %s""" , lowerCamelCase_ ) torch.save(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : bool = False ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = """dev""" if mode == """test""" else mode SCREAMING_SNAKE_CASE : Optional[Any] = self._feature_file(lowerCamelCase_ ) logger.info("""Loading features from cached file %s""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = torch.load(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": SCREAMING_SNAKE_CASE : str = torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) , batch_size=lowerCamelCase_ , shuffle=lowerCamelCase_ , ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: SCREAMING_SNAKE_CASE : Tuple = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None SCREAMING_SNAKE_CASE : int = self(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = outputs[:2] SCREAMING_SNAKE_CASE : Tuple = logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE : Any = inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item() SCREAMING_SNAKE_CASE : Union[str, Any] = np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": SCREAMING_SNAKE_CASE : List[str] = np.argmax(lowerCamelCase_ , axis=1 ) elif self.hparams.glue_output_mode == "regression": SCREAMING_SNAKE_CASE : Union[str, Any] = np.squeeze(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = np.concatenate([x["""target"""] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE : str = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE : str = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE : Dict = {**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , lowerCamelCase_ , lowerCamelCase_ )} SCREAMING_SNAKE_CASE : List[str] = dict(results.items() ) SCREAMING_SNAKE_CASE : str = results return ret, preds_list, out_label_list def lowerCamelCase_ ( self : Any , lowerCamelCase_ : list ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = self._eval_end(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self._eval_end(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict ): '''simple docstring''' BaseTransformer.add_model_specific_args(lowerCamelCase_ , lowerCamelCase_ ) parser.add_argument( """--max_seq_length""" , default=1_28 , type=lowerCamelCase_ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--task""" , default="""""" , type=lowerCamelCase_ , required=lowerCamelCase_ , help="""The GLUE task to run""" , ) parser.add_argument( """--gpus""" , default=0 , type=lowerCamelCase_ , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() add_generic_args(lowerCamelCase_ , os.getcwd() ) SCREAMING_SNAKE_CASE : Tuple = GLUETransformer.add_model_specific_args(lowerCamelCase_ , os.getcwd() ) SCREAMING_SNAKE_CASE : Any = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: SCREAMING_SNAKE_CASE : Optional[int] = os.path.join( """./results""" , f'''{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}''' , ) os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = GLUETransformer(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = generic_train(lowerCamelCase_ , lowerCamelCase_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: SCREAMING_SNAKE_CASE : Tuple = sorted(glob.glob(os.path.join(args.output_dir , """checkpoint-epoch=*.ckpt""" ) , recursive=lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : int = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(lowerCamelCase_ ) if __name__ == "__main__": main()
79
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''Translation''' , init=lowercase_ , repr=lowercase_ ) def __call__( self : int ): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''TranslationVariableLanguages''' , init=lowercase_ , repr=lowercase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = sorted(set(self.languages ) ) if self.languages else None SCREAMING_SNAKE_CASE : str = len(self.languages ) if self.languages else None def __call__( self : Tuple ): '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = set(self.languages ) if self.languages and set(lowerCamelCase_ ) - lang_set: raise ValueError( f'''Some languages in example ({", ".join(sorted(set(lowerCamelCase_ ) - lang_set ) )}) are not in valid set ({", ".join(lowerCamelCase_ )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE : List[Any] = [] for lang, text in translation_dict.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = zip(*sorted(lowerCamelCase_ ) ) return {"language": languages, "translation": translations} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
79
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase = { """configuration_blip_2""": [ """BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Blip2Config""", """Blip2QFormerConfig""", """Blip2VisionConfig""", ], """processing_blip_2""": ["""Blip2Processor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST""", """Blip2Model""", """Blip2QFormerModel""", """Blip2PreTrainedModel""", """Blip2ForConditionalGeneration""", """Blip2VisionModel""", ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , *lowerCamelCase_ : List[str] , **lowerCamelCase_ : Dict ): '''simple docstring''' warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , lowerCamelCase_ , ) super().__init__(*lowerCamelCase_ , **lowerCamelCase_ )
79
1
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = False, False, False @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) SCREAMING_SNAKE_CASE__ = field(default='''Audio''' , init=lowercase_ , repr=lowercase_ ) def __call__( self : List[str] ): '''simple docstring''' return self.pa_type def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, bytes, dict] ): '''simple docstring''' try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("""To support encoding audio data, please install 'soundfile'.""" ) from err if isinstance(lowerCamelCase_ , lowerCamelCase_ ): return {"bytes": None, "path": value} elif isinstance(lowerCamelCase_ , lowerCamelCase_ ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes SCREAMING_SNAKE_CASE : List[str] = BytesIO() sf.write(lowerCamelCase_ , value["""array"""] , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("""pcm""" ): # "PCM" only has raw audio bytes if value.get("""sampling_rate""" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object""" ) if value.get("""bytes""" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) SCREAMING_SNAKE_CASE : Dict = np.frombuffer(value["""bytes"""] , dtype=np.intaa ).astype(np.floataa ) / 3_27_67 else: SCREAMING_SNAKE_CASE : int = np.memmap(value["""path"""] , dtype="""h""" , mode="""r""" ).astype(np.floataa ) / 3_27_67 SCREAMING_SNAKE_CASE : Optional[Any] = BytesIO(bytes() ) sf.write(lowerCamelCase_ , lowerCamelCase_ , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : dict , lowerCamelCase_ : Optional[Dict[str, Union[str, bool, None]]] = None ): '''simple docstring''' if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead.""" ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = (value["""path"""], BytesIO(value["""bytes"""] )) if value["""bytes"""] is not None else (value["""path"""], None) if path is None and file is None: raise ValueError(f'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'.""" ) from err SCREAMING_SNAKE_CASE : Dict = xsplitext(lowerCamelCase_ )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) if file is None: SCREAMING_SNAKE_CASE : Tuple = token_per_repo_id or {} SCREAMING_SNAKE_CASE : str = path.split("""::""" )[-1] try: SCREAMING_SNAKE_CASE : int = string_to_dict(lowerCamelCase_ , config.HUB_DATASETS_URL )["""repo_id"""] SCREAMING_SNAKE_CASE : Optional[Any] = token_per_repo_id[repo_id] except (ValueError, KeyError): SCREAMING_SNAKE_CASE : int = None with xopen(lowerCamelCase_ , """rb""" , use_auth_token=lowerCamelCase_ ) as f: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = sf.read(lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = sf.read(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = array.T if self.mono: SCREAMING_SNAKE_CASE : Optional[Any] = librosa.to_mono(lowerCamelCase_ ) if self.sampling_rate and self.sampling_rate != sampling_rate: SCREAMING_SNAKE_CASE : List[Any] = librosa.resample(lowerCamelCase_ , orig_sr=lowerCamelCase_ , target_sr=self.sampling_rate ) SCREAMING_SNAKE_CASE : List[str] = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' from .features import Value if self.decode: raise ValueError("""Cannot flatten a decoded Audio feature.""" ) return { "bytes": Value("""binary""" ), "path": Value("""string""" ), } def lowerCamelCase_ ( self : str , lowerCamelCase_ : Union[pa.StringArray, pa.StructArray] ): '''simple docstring''' if pa.types.is_string(storage.type ): SCREAMING_SNAKE_CASE : Optional[Any] = pa.array([None] * len(lowerCamelCase_ ) , type=pa.binary() ) SCREAMING_SNAKE_CASE : str = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): SCREAMING_SNAKE_CASE : str = pa.array([None] * len(lowerCamelCase_ ) , type=pa.string() ) SCREAMING_SNAKE_CASE : List[Any] = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("""array""" ): SCREAMING_SNAKE_CASE : Optional[int] = pa.array([Audio().encode_example(lowerCamelCase_ ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: SCREAMING_SNAKE_CASE : str = storage.field("""bytes""" ) else: SCREAMING_SNAKE_CASE : int = pa.array([None] * len(lowerCamelCase_ ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: SCREAMING_SNAKE_CASE : Any = storage.field("""path""" ) else: SCREAMING_SNAKE_CASE : Dict = pa.array([None] * len(lowerCamelCase_ ) , type=pa.string() ) SCREAMING_SNAKE_CASE : Any = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) return array_cast(lowerCamelCase_ , self.pa_type ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : pa.StructArray ): '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(lowerCamelCase_ : int ): with xopen(lowerCamelCase_ , """rb""" ) as f: SCREAMING_SNAKE_CASE : str = f.read() return bytes_ SCREAMING_SNAKE_CASE : List[Any] = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) SCREAMING_SNAKE_CASE : int = pa.array( [os.path.basename(lowerCamelCase_ ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) SCREAMING_SNAKE_CASE : int = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(lowerCamelCase_ , self.pa_type )
79
'''simple docstring''' 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 UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : str ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : int , lowerCamelCase_ : Dict ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Optional[int] ): '''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 lowerCamelCase_ ( cls : Any ): '''simple docstring''' return f'''`pip install {cls.pip_package or cls.name}`''' class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''optuna''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Dict ): '''simple docstring''' return run_hp_search_optuna(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Any ): '''simple docstring''' return default_hp_space_optuna(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''ray''' SCREAMING_SNAKE_CASE__ = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_ray_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_ray(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' return default_hp_space_ray(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''sigopt''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_sigopt(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return default_hp_space_sigopt(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''wandb''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return run_hp_search_wandb(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return default_hp_space_wandb(lowerCamelCase_ ) __UpperCAmelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCamelCase_ ) > 0: SCREAMING_SNAKE_CASE : List[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() ) )
79
1
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __UpperCAmelCase = logging.getLogger(__name__) __UpperCAmelCase = """Hello world! cécé herlolip""" __UpperCAmelCase = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = BertAbsConfig( temp_dir=""".""" , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="""bert""" , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : int = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) SCREAMING_SNAKE_CASE : List[str] = AbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) , lowerCamelCase_ ) original.eval() SCREAMING_SNAKE_CASE : Optional[int] = BertAbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) SCREAMING_SNAKE_CASE : int = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE : Optional[int] = encoder_input_ids SCREAMING_SNAKE_CASE : Optional[Any] = decoder_input_ids SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE : str = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = original.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : str = new_model.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Any = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) __UpperCAmelCase = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
79
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = 1 # (0 is vertical, 1 is horizontal) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = get_dataset(lowerCamelCase_ , lowerCamelCase_ ) print("""Processing...""" ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = update_image_and_anno(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for index, image in enumerate(lowerCamelCase_ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Optional[int] = random_chars(32 ) SCREAMING_SNAKE_CASE : Optional[Any] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE : Dict = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , lowerCamelCase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(lowerCamelCase_ )} with {file_name}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE : Optional[Any] = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(lowerCamelCase_ ) with open(f'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Any = [] for label_file in glob.glob(os.path.join(lowerCamelCase_ , """*.txt""" ) ): SCREAMING_SNAKE_CASE : str = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(lowerCamelCase_ ) as in_file: SCREAMING_SNAKE_CASE : Any = in_file.readlines() SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowerCamelCase_ , f'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE : Tuple = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : Union[str, Any] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(lowerCamelCase_ ) labels.append(lowerCamelCase_ ) return img_paths, labels def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [] for idx in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Dict = img_list[idx] path_list.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = anno_list[idx] SCREAMING_SNAKE_CASE : Optional[Any] = cva.imread(lowerCamelCase_ ) if flip_type == 1: SCREAMING_SNAKE_CASE : List[str] = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE : Any = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(lowerCamelCase_ ) new_imgs_list.append(lowerCamelCase_ ) return new_imgs_list, new_annos_lists, path_list def __A ( lowerCamelCase_ = 32 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : Dict = ascii_lowercase + digits return "".join(random.choice(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
79
1
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase__ ( lowercase_ ): """simple docstring""" @staticmethod @abstractmethod def lowerCamelCase_ ( lowerCamelCase_ : ArgumentParser ): '''simple docstring''' raise NotImplementedError() @abstractmethod def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' raise NotImplementedError()
79
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''vivit''' def __init__( self : Tuple , lowerCamelCase_ : str=2_24 , lowerCamelCase_ : List[Any]=32 , lowerCamelCase_ : Tuple=[2, 16, 16] , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Dict=12 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : List[Any]=30_72 , lowerCamelCase_ : List[str]="gelu_fast" , lowerCamelCase_ : str=0.0 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : List[Any]=1e-06 , lowerCamelCase_ : Tuple=True , **lowerCamelCase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Dict = num_frames SCREAMING_SNAKE_CASE : Optional[Any] = tubelet_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : int = qkv_bias super().__init__(**lowerCamelCase_ )
79
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __UpperCAmelCase = { """configuration_layoutlmv2""": ["""LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMv2Config"""], """processing_layoutlmv2""": ["""LayoutLMv2Processor"""], """tokenization_layoutlmv2""": ["""LayoutLMv2Tokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""LayoutLMv2TokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""LayoutLMv2FeatureExtractor"""] __UpperCAmelCase = ["""LayoutLMv2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST""", """LayoutLMv2ForQuestionAnswering""", """LayoutLMv2ForSequenceClassification""", """LayoutLMv2ForTokenClassification""", """LayoutLMv2Layer""", """LayoutLMv2Model""", """LayoutLMv2PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' import math class UpperCamelCase__ : """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Tuple=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' SCREAMING_SNAKE_CASE : Any = n SCREAMING_SNAKE_CASE : Optional[int] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # adjacency matrix for weight SCREAMING_SNAKE_CASE : Union[str, Any] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # dp[i][j] stores minimum distance from i to j def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = w def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): SCREAMING_SNAKE_CASE : Union[str, Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": __UpperCAmelCase = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
79
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) SCREAMING_SNAKE_CASE : Dict = { """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 ), } SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , lowerCamelCase_ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
79
'''simple docstring''' import math def __A ( lowerCamelCase_ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __A ( lowerCamelCase_ = 1_00_01 ): """simple docstring""" try: SCREAMING_SNAKE_CASE : Tuple = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError("""Parameter nth must be int or castable to int.""" ) from None if nth <= 0: raise ValueError("""Parameter nth must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE : list[int] = [] SCREAMING_SNAKE_CASE : Dict = 2 while len(lowerCamelCase_ ) < nth: if is_prime(lowerCamelCase_ ): primes.append(lowerCamelCase_ ) num += 1 else: num += 1 return primes[len(lowerCamelCase_ ) - 1] if __name__ == "__main__": print(f'''{solution() = }''')
79
1
'''simple docstring''' from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
79
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __UpperCAmelCase = {"""UserAgent""": UserAgent().random} def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = script.contents[0] SCREAMING_SNAKE_CASE : int = json.loads(data[data.find("""{\"config\"""" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f'''https://www.instagram.com/{username}/''' SCREAMING_SNAKE_CASE : Any = self.get_json() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = requests.get(self.url , headers=lowerCamelCase_ ).text SCREAMING_SNAKE_CASE : List[Any] = BeautifulSoup(lowerCamelCase_ , """html.parser""" ).find_all("""script""" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Dict ): '''simple docstring''' return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self : int ): '''simple docstring''' return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return self.user_data["username"] @property def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return self.user_data["full_name"] @property def lowerCamelCase_ ( self : int ): '''simple docstring''' return self.user_data["biography"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["business_email"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["external_url"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return self.user_data["is_verified"] @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.user_data["is_private"] def __A ( lowerCamelCase_ = "github" ): """simple docstring""" import os if os.environ.get("""CI""" ): return # test failing on GitHub Actions SCREAMING_SNAKE_CASE : Any = InstagramUser(lowerCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , lowerCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("""https://instagram.""" ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = InstagramUser("""github""") print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
79
1
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = ["""model.decoder.embed_positions.weights"""] def __A ( lowerCamelCase_ ): """simple docstring""" if "emb" in name: SCREAMING_SNAKE_CASE : Any = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: SCREAMING_SNAKE_CASE : Any = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: SCREAMING_SNAKE_CASE : Any = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = list(state_dict.keys() ) SCREAMING_SNAKE_CASE : int = {} for key in keys: SCREAMING_SNAKE_CASE : str = state_dict.pop(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = rename_keys(lowerCamelCase_ ) if "in_proj_weight" in key: # split fused qkv proj SCREAMING_SNAKE_CASE : List[Any] = val[:hidden_size, :] SCREAMING_SNAKE_CASE : Union[str, Any] = val[hidden_size : 2 * hidden_size, :] SCREAMING_SNAKE_CASE : Dict = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: SCREAMING_SNAKE_CASE : str = val else: SCREAMING_SNAKE_CASE : Union[str, Any] = val return state_dict, enc_dec_proj_state_dict def __A ( lowerCamelCase_ ): """simple docstring""" if checkpoint == "small": # default config values SCREAMING_SNAKE_CASE : Optional[int] = 10_24 SCREAMING_SNAKE_CASE : Tuple = 24 SCREAMING_SNAKE_CASE : Dict = 16 elif checkpoint == "medium": SCREAMING_SNAKE_CASE : int = 15_36 SCREAMING_SNAKE_CASE : int = 48 SCREAMING_SNAKE_CASE : int = 24 elif checkpoint == "large": SCREAMING_SNAKE_CASE : Optional[Any] = 20_48 SCREAMING_SNAKE_CASE : Any = 48 SCREAMING_SNAKE_CASE : Any = 32 else: raise ValueError(f'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) SCREAMING_SNAKE_CASE : Dict = MusicgenDecoderConfig( hidden_size=lowerCamelCase_ , ffn_dim=hidden_size * 4 , num_hidden_layers=lowerCamelCase_ , num_attention_heads=lowerCamelCase_ , ) return config @torch.no_grad() def __A ( lowerCamelCase_ , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_="cpu" ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = MusicGen.get_pretrained(lowerCamelCase_ , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = decoder_config_from_checkpoint(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = fairseq_model.lm.state_dict() SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = rename_state_dict( lowerCamelCase_ , hidden_size=decoder_config.hidden_size ) SCREAMING_SNAKE_CASE : int = TaEncoderModel.from_pretrained("""t5-base""" ) SCREAMING_SNAKE_CASE : Any = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) SCREAMING_SNAKE_CASE : Dict = MusicgenForCausalLM(lowerCamelCase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = decoder.load_state_dict(lowerCamelCase_ , strict=lowerCamelCase_ ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowerCamelCase_ ) if len(lowerCamelCase_ ) > 0: raise ValueError(f'''Missing key(s) in state_dict: {missing_keys}''' ) if len(lowerCamelCase_ ) > 0: raise ValueError(f'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model SCREAMING_SNAKE_CASE : Optional[Any] = MusicgenForConditionalGeneration(text_encoder=lowerCamelCase_ , audio_encoder=lowerCamelCase_ , decoder=lowerCamelCase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowerCamelCase_ ) # check we can do a forward pass SCREAMING_SNAKE_CASE : str = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) SCREAMING_SNAKE_CASE : Tuple = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(input_ids=lowerCamelCase_ , decoder_input_ids=lowerCamelCase_ ).logits if logits.shape != (8, 1, 20_48): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""t5-base""" ) SCREAMING_SNAKE_CASE : List[str] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) SCREAMING_SNAKE_CASE : str = MusicgenProcessor(feature_extractor=lowerCamelCase_ , tokenizer=lowerCamelCase_ ) # set the appropriate bos/pad token ids SCREAMING_SNAKE_CASE : int = 20_48 SCREAMING_SNAKE_CASE : Optional[int] = 20_48 # set other default generation config params SCREAMING_SNAKE_CASE : Optional[int] = int(30 * audio_encoder.config.frame_rate ) SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : str = 3.0 if pytorch_dump_folder is not None: Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) logger.info(f'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(lowerCamelCase_ ) processor.save_pretrained(lowerCamelCase_ ) if repo_id: logger.info(f'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(lowerCamelCase_ ) processor.push_to_hub(lowerCamelCase_ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint""", default="""small""", type=str, help="""Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.""", ) parser.add_argument( """--pytorch_dump_folder""", required=True, default=None, type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) parser.add_argument( """--device""", default="""cpu""", type=str, help="""Torch device to run the conversion, either cpu or cuda.""" ) __UpperCAmelCase = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
79
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __UpperCAmelCase = logging.getLogger(__name__) __UpperCAmelCase = """Hello world! cécé herlolip""" __UpperCAmelCase = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = BertAbsConfig( temp_dir=""".""" , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="""bert""" , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : int = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) SCREAMING_SNAKE_CASE : List[str] = AbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) , lowerCamelCase_ ) original.eval() SCREAMING_SNAKE_CASE : Optional[int] = BertAbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) SCREAMING_SNAKE_CASE : int = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE : Optional[int] = encoder_input_ids SCREAMING_SNAKE_CASE : Optional[Any] = decoder_input_ids SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE : str = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = original.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : str = new_model.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Any = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) __UpperCAmelCase = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
79
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[Any]=7 , lowerCamelCase_ : int=3 , lowerCamelCase_ : int=10 , lowerCamelCase_ : str=18 , lowerCamelCase_ : str=30 , lowerCamelCase_ : Tuple=4_00 , lowerCamelCase_ : Any=True , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Optional[Any]=[0.5, 0.5, 0.5] , lowerCamelCase_ : Tuple=[0.5, 0.5, 0.5] , lowerCamelCase_ : List[Any]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = size if size is not None else {"""shortest_edge""": 18} SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} SCREAMING_SNAKE_CASE : List[Any] = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : List[Any] = num_channels SCREAMING_SNAKE_CASE : Tuple = num_frames SCREAMING_SNAKE_CASE : int = image_size SCREAMING_SNAKE_CASE : Any = min_resolution SCREAMING_SNAKE_CASE : Optional[int] = max_resolution SCREAMING_SNAKE_CASE : str = do_resize SCREAMING_SNAKE_CASE : str = size SCREAMING_SNAKE_CASE : Dict = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean SCREAMING_SNAKE_CASE : Dict = image_std SCREAMING_SNAKE_CASE : List[Any] = crop_size def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VivitImageProcessor if is_vision_available() else None def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = VivitImageProcessingTester(self ) @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase_ , """image_mean""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """image_std""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """do_normalize""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """do_center_crop""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """size""" ) ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL videos SCREAMING_SNAKE_CASE : int = prepare_video_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase_ ) for video in video_inputs: self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) self.assertIsInstance(video[0] , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[str] = image_processing(video_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE : Dict = image_processing(lowerCamelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_video_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase_ , numpify=lowerCamelCase_ ) for video in video_inputs: self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) self.assertIsInstance(video[0] , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Tuple = image_processing(video_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(lowerCamelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Optional[int] = prepare_video_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase_ , torchify=lowerCamelCase_ ) for video in video_inputs: self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) self.assertIsInstance(video[0] , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : int = image_processing(video_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(lowerCamelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
79
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=True , lowerCamelCase_="pt" ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {"""add_prefix_space""": True} if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and not line.startswith(""" """ ) else {} SCREAMING_SNAKE_CASE : Optional[Any] = padding_side return tokenizer( [line] , max_length=lowerCamelCase_ , padding="""max_length""" if pad_to_max_length else None , truncation=lowerCamelCase_ , return_tensors=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , **lowerCamelCase_ , ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , ): """simple docstring""" SCREAMING_SNAKE_CASE : int = input_ids.ne(lowerCamelCase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : str , lowerCamelCase_ : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str]="train" , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : int=None , lowerCamelCase_ : Union[str, Any]="" , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : str = Path(lowerCamelCase_ ).joinpath(type_path + """.source""" ) SCREAMING_SNAKE_CASE : Optional[Any] = Path(lowerCamelCase_ ).joinpath(type_path + """.target""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_char_lens(self.src_file ) SCREAMING_SNAKE_CASE : int = max_source_length SCREAMING_SNAKE_CASE : str = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' SCREAMING_SNAKE_CASE : List[str] = tokenizer SCREAMING_SNAKE_CASE : Dict = prefix if n_obs is not None: SCREAMING_SNAKE_CASE : List[Any] = self.src_lens[:n_obs] SCREAMING_SNAKE_CASE : int = src_lang SCREAMING_SNAKE_CASE : Optional[int] = tgt_lang def __len__( self : List[Any] ): '''simple docstring''' return len(self.src_lens ) def __getitem__( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = index + 1 # linecache starts at 1 SCREAMING_SNAKE_CASE : Dict = self.prefix + linecache.getline(str(self.src_file ) , lowerCamelCase_ ).rstrip("""\n""" ) SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , lowerCamelCase_ ).rstrip("""\n""" ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , lowerCamelCase_ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer ) SCREAMING_SNAKE_CASE : Any = self.tokenizer.generator if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer SCREAMING_SNAKE_CASE : Optional[int] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_source_length , """right""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_target_length , """right""" ) SCREAMING_SNAKE_CASE : Tuple = source_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : Tuple = target_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : List[str] = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : Dict ): '''simple docstring''' return [len(lowerCamelCase_ ) for x in Path(lowerCamelCase_ ).open().readlines()] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = torch.stack([x["""input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""attention_mask"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""decoder_input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ , attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch __UpperCAmelCase = getLogger(__name__) def __A ( lowerCamelCase_ ): """simple docstring""" return list(itertools.chain.from_iterable(lowerCamelCase_ ) ) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = get_git_info() save_json(lowerCamelCase_ , os.path.join(lowerCamelCase_ , """git_log.json""" ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=4 , **lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """w""" ) as f: json.dump(lowerCamelCase_ , lowerCamelCase_ , indent=lowerCamelCase_ , **lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ ) as f: return json.load(lowerCamelCase_ ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = git.Repo(search_parent_directories=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { """repo_id""": str(lowerCamelCase_ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return list(map(lowerCamelCase_ , lowerCamelCase_ ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """wb""" ) as f: return pickle.dump(lowerCamelCase_ , lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" def remove_articles(lowerCamelCase_ ): return re.sub(R"""\b(a|an|the)\b""" , """ """ , lowerCamelCase_ ) def white_space_fix(lowerCamelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_ ) ) ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Optional[int] = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Tuple = Counter(lowerCamelCase_ ) & Counter(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = sum(common.values() ) if num_same == 0: return 0 SCREAMING_SNAKE_CASE : Optional[int] = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = (2 * precision * recall) / (precision + recall) return fa def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return normalize_answer(lowerCamelCase_ ) == normalize_answer(lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert len(lowerCamelCase_ ) == len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowerCamelCase_ , lowerCamelCase_ ): em += exact_match_score(lowerCamelCase_ , lowerCamelCase_ ) if len(lowerCamelCase_ ) > 0: em /= len(lowerCamelCase_ ) return {"em": em} def __A ( lowerCamelCase_ ): """simple docstring""" return model_prefix.startswith("""rag""" ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead SCREAMING_SNAKE_CASE : Dict = """dropout_rate""" for p in extra_params: if getattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): if not hasattr(lowerCamelCase_ , lowerCamelCase_ ) and not hasattr(lowerCamelCase_ , equivalent_param[p] ): logger.info("""config doesn't have a `{}` attribute""".format(lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) continue SCREAMING_SNAKE_CASE : Dict = p if hasattr(lowerCamelCase_ , lowerCamelCase_ ) else equivalent_param[p] setattr(lowerCamelCase_ , lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) return hparams, config
79
1
'''simple docstring''' import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """vocab_file""": """vocab.json""", """tokenizer_config_file""": """tokenizer_config.json""", """merges_file""": """merges.txt""", } __UpperCAmelCase = { """vocab_file""": { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json""" ), }, """tokenizer_config_file""": { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json""" ), }, """merges_file""": { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt""" ), }, } __UpperCAmelCase = """</w>""" __UpperCAmelCase = """@@ """ def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = set() SCREAMING_SNAKE_CASE : Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE : Optional[Any] = char return pairs # Speech2Text2 has no max input length __UpperCAmelCase = {"""facebook/s2t-wav2vec2-large-en-de""": 1024} class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] def __init__( self : str , lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any]="<s>" , lowerCamelCase_ : Optional[int]="<pad>" , lowerCamelCase_ : Any="</s>" , lowerCamelCase_ : str="<unk>" , lowerCamelCase_ : Dict=False , lowerCamelCase_ : Dict=None , **lowerCamelCase_ : str , ): '''simple docstring''' super().__init__( unk_token=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , do_lower_case=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = do_lower_case with open(lowerCamelCase_ , encoding="""utf-8""" ) as vocab_handle: SCREAMING_SNAKE_CASE : Optional[int] = json.load(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(f'''No merges files provided. {self.__class__.__name__} can only be used for decoding.''' ) SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Optional[Any] = None else: with open(lowerCamelCase_ , encoding="""utf-8""" ) as merges_handle: SCREAMING_SNAKE_CASE : Optional[int] = merges_handle.read().split("""\n""" )[:-1] SCREAMING_SNAKE_CASE : int = [tuple(merge.split()[:2] ) for merge in merges] SCREAMING_SNAKE_CASE : str = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : List[str] = {} @property def lowerCamelCase_ ( self : int ): '''simple docstring''' return len(self.decoder ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE : Dict = get_pairs(lowerCamelCase_ ) if not pairs: return token while True: SCREAMING_SNAKE_CASE : Optional[int] = min(lowerCamelCase_ , key=lambda lowerCamelCase_ : self.bpe_ranks.get(lowerCamelCase_ , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = bigram SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[int] = 0 while i < len(lowerCamelCase_ ): try: SCREAMING_SNAKE_CASE : List[str] = word.index(lowerCamelCase_ , lowerCamelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE : Union[str, Any] = j if word[i] == first and i < len(lowerCamelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE : List[Any] = tuple(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = new_word if len(lowerCamelCase_ ) == 1: break else: SCREAMING_SNAKE_CASE : Any = get_pairs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = """ """.join(lowerCamelCase_ ) if word == "\n " + BPE_TOKEN_MERGES: SCREAMING_SNAKE_CASE : List[str] = """\n""" + BPE_TOKEN_MERGES if word.endswith(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = word.replace(lowerCamelCase_ , """""" ) SCREAMING_SNAKE_CASE : Optional[Any] = word.replace(""" """ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = word return word def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' if self.bpe_ranks is None: raise ValueError( """This tokenizer was instantiated without a `merges.txt` file, so""" """ that it can only be used for decoding, not for encoding.""" """Make sure to provide `merges.txt` file at instantiation to enable """ """encoding.""" ) if self.do_lower_case: SCREAMING_SNAKE_CASE : Any = text.lower() SCREAMING_SNAKE_CASE : Any = text.split() SCREAMING_SNAKE_CASE : Optional[int] = [] for token in text: if token: split_tokens.extend(list(self.bpe(lowerCamelCase_ ).split(""" """ ) ) ) return split_tokens def lowerCamelCase_ ( self : int , lowerCamelCase_ : str ): '''simple docstring''' return self.encoder.get(lowerCamelCase_ , self.encoder.get(self.unk_token ) ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.decoder.get(lowerCamelCase_ , self.unk_token ) return result def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = """ """.join(lowerCamelCase_ ) # make sure @@ tokens are concatenated SCREAMING_SNAKE_CASE : Optional[int] = """""".join(string.split(lowerCamelCase_ ) ) return string def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : List[str] = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE : int = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(lowerCamelCase_ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCamelCase_ , ensure_ascii=lowerCamelCase_ ) + """\n""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = 0 if self.bpe_ranks is None: return (vocab_file,) with open(lowerCamelCase_ , """w""" , encoding="""utf-8""" ) as writer: 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 {merges_file}: BPE merge indices are not consecutive.''' """ Please check that the tokenizer is not corrupted!""" ) SCREAMING_SNAKE_CASE : Any = token_index writer.write(""" """.join(lowerCamelCase_ ) + """\n""" ) index += 1 return (vocab_file, merges_file)
79
'''simple docstring''' def __A ( lowerCamelCase_ ): """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : List[str] = number while duplicate > 0: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = divmod(lowerCamelCase_ , 10 ) fact_sum += factorial(lowerCamelCase_ ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") __UpperCAmelCase = int(input("""Enter number: """).strip()) print( f'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
79
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """microsoft/unispeech-large-1500h-cv""": ( """https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json""" ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''unispeech''' def __init__( self : Optional[Any] , lowerCamelCase_ : int=32 , lowerCamelCase_ : List[Any]=7_68 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : Union[str, Any]=12 , lowerCamelCase_ : Optional[int]=30_72 , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Union[str, Any]=0.1 , lowerCamelCase_ : Any=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[Any]=0.0 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : Optional[Any]=0.02 , lowerCamelCase_ : List[Any]=1e-5 , lowerCamelCase_ : List[Any]="group" , lowerCamelCase_ : Optional[Any]="gelu" , lowerCamelCase_ : List[Any]=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , lowerCamelCase_ : Tuple=(5, 2, 2, 2, 2, 2, 2) , lowerCamelCase_ : List[str]=(10, 3, 3, 3, 3, 2, 2) , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : str=1_28 , lowerCamelCase_ : int=16 , lowerCamelCase_ : str=False , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Optional[int]=0.05 , lowerCamelCase_ : Dict=10 , lowerCamelCase_ : Tuple=2 , lowerCamelCase_ : Union[str, Any]=0.0 , lowerCamelCase_ : Dict=10 , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : Union[str, Any]=3_20 , lowerCamelCase_ : Dict=2 , lowerCamelCase_ : List[str]=0.1 , lowerCamelCase_ : str=1_00 , lowerCamelCase_ : List[Any]=2_56 , lowerCamelCase_ : Tuple=2_56 , lowerCamelCase_ : Dict=0.1 , lowerCamelCase_ : Any="mean" , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : Any=False , lowerCamelCase_ : List[str]=2_56 , lowerCamelCase_ : Optional[Any]=80 , lowerCamelCase_ : int=0 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : str=2 , lowerCamelCase_ : Dict=0.5 , **lowerCamelCase_ : str , ): '''simple docstring''' super().__init__(**lowerCamelCase_ , pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE : List[str] = feat_extract_norm SCREAMING_SNAKE_CASE : int = feat_extract_activation SCREAMING_SNAKE_CASE : List[str] = list(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = list(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = list(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = conv_bias SCREAMING_SNAKE_CASE : Tuple = num_conv_pos_embeddings SCREAMING_SNAKE_CASE : Dict = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE : List[str] = len(self.conv_dim ) SCREAMING_SNAKE_CASE : str = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout SCREAMING_SNAKE_CASE : Dict = attention_dropout SCREAMING_SNAKE_CASE : Any = activation_dropout SCREAMING_SNAKE_CASE : Union[str, Any] = feat_proj_dropout SCREAMING_SNAKE_CASE : Optional[Any] = final_dropout SCREAMING_SNAKE_CASE : List[Any] = layerdrop SCREAMING_SNAKE_CASE : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = num_ctc_classes SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = do_stable_layer_norm SCREAMING_SNAKE_CASE : Any = use_weighted_layer_sum SCREAMING_SNAKE_CASE : Union[str, Any] = 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 SCREAMING_SNAKE_CASE : Optional[int] = apply_spec_augment SCREAMING_SNAKE_CASE : Any = mask_time_prob SCREAMING_SNAKE_CASE : Any = mask_time_length SCREAMING_SNAKE_CASE : Dict = mask_time_min_masks SCREAMING_SNAKE_CASE : Tuple = mask_feature_prob SCREAMING_SNAKE_CASE : str = mask_feature_length SCREAMING_SNAKE_CASE : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE : str = num_codevectors_per_group SCREAMING_SNAKE_CASE : Dict = num_codevector_groups SCREAMING_SNAKE_CASE : Union[str, Any] = contrastive_logits_temperature SCREAMING_SNAKE_CASE : int = feat_quantizer_dropout SCREAMING_SNAKE_CASE : List[str] = num_negatives SCREAMING_SNAKE_CASE : Dict = codevector_dim SCREAMING_SNAKE_CASE : Optional[int] = proj_codevector_dim SCREAMING_SNAKE_CASE : int = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE : Dict = ctc_loss_reduction SCREAMING_SNAKE_CASE : Optional[int] = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE : Tuple = replace_prob @property def lowerCamelCase_ ( self : Any ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
79
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class UpperCamelCase__ ( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase_ : str=None , **lowerCamelCase_ : Dict ): '''simple docstring''' super().__init__(features=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch_tensor_kwargs import torch # noqa import torch at initialization def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and column: if all( isinstance(lowerCamelCase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : int ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , (str, bytes, type(lowerCamelCase_ )) ): return value elif isinstance(lowerCamelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE : str = {} if isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): SCREAMING_SNAKE_CASE : Any = {"""dtype""": torch.intaa} elif isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE : int = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowerCamelCase_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(lowerCamelCase_ ) return torch.tensor(lowerCamelCase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(lowerCamelCase_ , """__array__""" ) and not isinstance(lowerCamelCase_ , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowerCamelCase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) elif isinstance(lowerCamelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) return self._tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : dict ): '''simple docstring''' return map_nested(self._recursive_tensorize , lowerCamelCase_ , map_list=lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.numpy_arrow_extractor().extract_row(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_row(lowerCamelCase_ ) return self.recursive_tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.numpy_arrow_extractor().extract_column(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.python_features_decoder.decode_column(lowerCamelCase_ , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE : List[str] = self.recursive_tensorize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self._consolidate(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.numpy_arrow_extractor().extract_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.recursive_tensorize(lowerCamelCase_ ) for column_name in batch: SCREAMING_SNAKE_CASE : Tuple = self._consolidate(batch[column_name] ) return batch
79
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __UpperCAmelCase = { """Acehnese Arabic""": """ace_Arab""", """Acehnese Latin""": """ace_Latn""", """Mesopotamian Arabic""": """acm_Arab""", """Ta'izzi-Adeni Arabic""": """acq_Arab""", """Tunisian Arabic""": """aeb_Arab""", """Afrikaans""": """afr_Latn""", """South Levantine Arabic""": """ajp_Arab""", """Akan""": """aka_Latn""", """Amharic""": """amh_Ethi""", """North Levantine Arabic""": """apc_Arab""", """Modern Standard Arabic""": """arb_Arab""", """Modern Standard Arabic Romanized""": """arb_Latn""", """Najdi Arabic""": """ars_Arab""", """Moroccan Arabic""": """ary_Arab""", """Egyptian Arabic""": """arz_Arab""", """Assamese""": """asm_Beng""", """Asturian""": """ast_Latn""", """Awadhi""": """awa_Deva""", """Central Aymara""": """ayr_Latn""", """South Azerbaijani""": """azb_Arab""", """North Azerbaijani""": """azj_Latn""", """Bashkir""": """bak_Cyrl""", """Bambara""": """bam_Latn""", """Balinese""": """ban_Latn""", """Belarusian""": """bel_Cyrl""", """Bemba""": """bem_Latn""", """Bengali""": """ben_Beng""", """Bhojpuri""": """bho_Deva""", """Banjar Arabic""": """bjn_Arab""", """Banjar Latin""": """bjn_Latn""", """Standard Tibetan""": """bod_Tibt""", """Bosnian""": """bos_Latn""", """Buginese""": """bug_Latn""", """Bulgarian""": """bul_Cyrl""", """Catalan""": """cat_Latn""", """Cebuano""": """ceb_Latn""", """Czech""": """ces_Latn""", """Chokwe""": """cjk_Latn""", """Central Kurdish""": """ckb_Arab""", """Crimean Tatar""": """crh_Latn""", """Welsh""": """cym_Latn""", """Danish""": """dan_Latn""", """German""": """deu_Latn""", """Southwestern Dinka""": """dik_Latn""", """Dyula""": """dyu_Latn""", """Dzongkha""": """dzo_Tibt""", """Greek""": """ell_Grek""", """English""": """eng_Latn""", """Esperanto""": """epo_Latn""", """Estonian""": """est_Latn""", """Basque""": """eus_Latn""", """Ewe""": """ewe_Latn""", """Faroese""": """fao_Latn""", """Fijian""": """fij_Latn""", """Finnish""": """fin_Latn""", """Fon""": """fon_Latn""", """French""": """fra_Latn""", """Friulian""": """fur_Latn""", """Nigerian Fulfulde""": """fuv_Latn""", """Scottish Gaelic""": """gla_Latn""", """Irish""": """gle_Latn""", """Galician""": """glg_Latn""", """Guarani""": """grn_Latn""", """Gujarati""": """guj_Gujr""", """Haitian Creole""": """hat_Latn""", """Hausa""": """hau_Latn""", """Hebrew""": """heb_Hebr""", """Hindi""": """hin_Deva""", """Chhattisgarhi""": """hne_Deva""", """Croatian""": """hrv_Latn""", """Hungarian""": """hun_Latn""", """Armenian""": """hye_Armn""", """Igbo""": """ibo_Latn""", """Ilocano""": """ilo_Latn""", """Indonesian""": """ind_Latn""", """Icelandic""": """isl_Latn""", """Italian""": """ita_Latn""", """Javanese""": """jav_Latn""", """Japanese""": """jpn_Jpan""", """Kabyle""": """kab_Latn""", """Jingpho""": """kac_Latn""", """Kamba""": """kam_Latn""", """Kannada""": """kan_Knda""", """Kashmiri Arabic""": """kas_Arab""", """Kashmiri Devanagari""": """kas_Deva""", """Georgian""": """kat_Geor""", """Central Kanuri Arabic""": """knc_Arab""", """Central Kanuri Latin""": """knc_Latn""", """Kazakh""": """kaz_Cyrl""", """Kabiyè""": """kbp_Latn""", """Kabuverdianu""": """kea_Latn""", """Khmer""": """khm_Khmr""", """Kikuyu""": """kik_Latn""", """Kinyarwanda""": """kin_Latn""", """Kyrgyz""": """kir_Cyrl""", """Kimbundu""": """kmb_Latn""", """Northern Kurdish""": """kmr_Latn""", """Kikongo""": """kon_Latn""", """Korean""": """kor_Hang""", """Lao""": """lao_Laoo""", """Ligurian""": """lij_Latn""", """Limburgish""": """lim_Latn""", """Lingala""": """lin_Latn""", """Lithuanian""": """lit_Latn""", """Lombard""": """lmo_Latn""", """Latgalian""": """ltg_Latn""", """Luxembourgish""": """ltz_Latn""", """Luba-Kasai""": """lua_Latn""", """Ganda""": """lug_Latn""", """Luo""": """luo_Latn""", """Mizo""": """lus_Latn""", """Standard Latvian""": """lvs_Latn""", """Magahi""": """mag_Deva""", """Maithili""": """mai_Deva""", """Malayalam""": """mal_Mlym""", """Marathi""": """mar_Deva""", """Minangkabau Arabic """: """min_Arab""", """Minangkabau Latin""": """min_Latn""", """Macedonian""": """mkd_Cyrl""", """Plateau Malagasy""": """plt_Latn""", """Maltese""": """mlt_Latn""", """Meitei Bengali""": """mni_Beng""", """Halh Mongolian""": """khk_Cyrl""", """Mossi""": """mos_Latn""", """Maori""": """mri_Latn""", """Burmese""": """mya_Mymr""", """Dutch""": """nld_Latn""", """Norwegian Nynorsk""": """nno_Latn""", """Norwegian Bokmål""": """nob_Latn""", """Nepali""": """npi_Deva""", """Northern Sotho""": """nso_Latn""", """Nuer""": """nus_Latn""", """Nyanja""": """nya_Latn""", """Occitan""": """oci_Latn""", """West Central Oromo""": """gaz_Latn""", """Odia""": """ory_Orya""", """Pangasinan""": """pag_Latn""", """Eastern Panjabi""": """pan_Guru""", """Papiamento""": """pap_Latn""", """Western Persian""": """pes_Arab""", """Polish""": """pol_Latn""", """Portuguese""": """por_Latn""", """Dari""": """prs_Arab""", """Southern Pashto""": """pbt_Arab""", """Ayacucho Quechua""": """quy_Latn""", """Romanian""": """ron_Latn""", """Rundi""": """run_Latn""", """Russian""": """rus_Cyrl""", """Sango""": """sag_Latn""", """Sanskrit""": """san_Deva""", """Santali""": """sat_Olck""", """Sicilian""": """scn_Latn""", """Shan""": """shn_Mymr""", """Sinhala""": """sin_Sinh""", """Slovak""": """slk_Latn""", """Slovenian""": """slv_Latn""", """Samoan""": """smo_Latn""", """Shona""": """sna_Latn""", """Sindhi""": """snd_Arab""", """Somali""": """som_Latn""", """Southern Sotho""": """sot_Latn""", """Spanish""": """spa_Latn""", """Tosk Albanian""": """als_Latn""", """Sardinian""": """srd_Latn""", """Serbian""": """srp_Cyrl""", """Swati""": """ssw_Latn""", """Sundanese""": """sun_Latn""", """Swedish""": """swe_Latn""", """Swahili""": """swh_Latn""", """Silesian""": """szl_Latn""", """Tamil""": """tam_Taml""", """Tatar""": """tat_Cyrl""", """Telugu""": """tel_Telu""", """Tajik""": """tgk_Cyrl""", """Tagalog""": """tgl_Latn""", """Thai""": """tha_Thai""", """Tigrinya""": """tir_Ethi""", """Tamasheq Latin""": """taq_Latn""", """Tamasheq Tifinagh""": """taq_Tfng""", """Tok Pisin""": """tpi_Latn""", """Tswana""": """tsn_Latn""", """Tsonga""": """tso_Latn""", """Turkmen""": """tuk_Latn""", """Tumbuka""": """tum_Latn""", """Turkish""": """tur_Latn""", """Twi""": """twi_Latn""", """Central Atlas Tamazight""": """tzm_Tfng""", """Uyghur""": """uig_Arab""", """Ukrainian""": """ukr_Cyrl""", """Umbundu""": """umb_Latn""", """Urdu""": """urd_Arab""", """Northern Uzbek""": """uzn_Latn""", """Venetian""": """vec_Latn""", """Vietnamese""": """vie_Latn""", """Waray""": """war_Latn""", """Wolof""": """wol_Latn""", """Xhosa""": """xho_Latn""", """Eastern Yiddish""": """ydd_Hebr""", """Yoruba""": """yor_Latn""", """Yue Chinese""": """yue_Hant""", """Chinese Simplified""": """zho_Hans""", """Chinese Traditional""": """zho_Hant""", """Standard Malay""": """zsm_Latn""", """Zulu""": """zul_Latn""", } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''facebook/nllb-200-distilled-600M''' SCREAMING_SNAKE_CASE__ = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) SCREAMING_SNAKE_CASE__ = '''translator''' SCREAMING_SNAKE_CASE__ = AutoTokenizer SCREAMING_SNAKE_CASE__ = AutoModelForSeqaSeqLM SCREAMING_SNAKE_CASE__ = LANGUAGE_CODES SCREAMING_SNAKE_CASE__ = ['''text''', '''text''', '''text'''] SCREAMING_SNAKE_CASE__ = ['''text'''] def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Any , lowerCamelCase_ : List[Any] ): '''simple docstring''' if src_lang not in self.lang_to_code: raise ValueError(f'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'''{tgt_lang} is not a supported language.''' ) SCREAMING_SNAKE_CASE : Dict = self.lang_to_code[src_lang] SCREAMING_SNAKE_CASE : Dict = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( lowerCamelCase_ , return_tensors="""pt""" , src_lang=lowerCamelCase_ , tgt_lang=lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return self.model.generate(**lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : Any ): '''simple docstring''' return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=lowerCamelCase_ )
79
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCAmelCase = random.Random() def __A ( lowerCamelCase_ , lowerCamelCase_=1.0 , lowerCamelCase_=None , lowerCamelCase_=None ): """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE : Optional[Any] = global_rng SCREAMING_SNAKE_CASE : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int]=7 , lowerCamelCase_ : Optional[int]=4_00 , lowerCamelCase_ : int=20_00 , lowerCamelCase_ : List[str]=20_48 , lowerCamelCase_ : Optional[Any]=1_28 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : Dict=30 , lowerCamelCase_ : Dict=4_41_00 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = min_seq_length SCREAMING_SNAKE_CASE : Any = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : int = spectrogram_length SCREAMING_SNAKE_CASE : List[Any] = feature_size SCREAMING_SNAKE_CASE : Any = num_audio_channels SCREAMING_SNAKE_CASE : Tuple = hop_length SCREAMING_SNAKE_CASE : str = chunk_length SCREAMING_SNAKE_CASE : Dict = sampling_rate def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : Any=False ): '''simple docstring''' def _flatten(lowerCamelCase_ : Dict ): return list(itertools.chain(*lowerCamelCase_ ) ) if equal_length: SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(lowerCamelCase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = TvltFeatureExtractor def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TvltFeatureExtractionTester(self ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase_ , """spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """sampling_rate""" ) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Any = feat_extract_first.save_pretrained(lowerCamelCase_ )[0] check_json_file_has_correct_format(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : List[Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : int = os.path.join(lowerCamelCase_ , """feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class.from_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : int = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : List[str] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Optional[Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] SCREAMING_SNAKE_CASE : int = [np.asarray(lowerCamelCase_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 , mask_audio=lowerCamelCase_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] SCREAMING_SNAKE_CASE : int = np.asarray(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Union[str, Any] = ds.sort("""id""" ).select(range(lowerCamelCase_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : Tuple = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(lowerCamelCase_ , return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_92, 1_28) ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , lowerCamelCase_ , atol=1e-4 ) )
79
1
'''simple docstring''' from __future__ import annotations import pandas as pd def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [0] * no_of_processes SCREAMING_SNAKE_CASE : Union[str, Any] = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = burst_time[i] SCREAMING_SNAKE_CASE : Union[str, Any] = 0 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Any = 9_99_99_99_99 SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : List[Any] = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCamelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: SCREAMING_SNAKE_CASE : Tuple = remaining_time[j] SCREAMING_SNAKE_CASE : Tuple = j SCREAMING_SNAKE_CASE : Optional[Any] = True if not check: increment_time += 1 continue remaining_time[short] -= 1 SCREAMING_SNAKE_CASE : Any = remaining_time[short] if minm == 0: SCREAMING_SNAKE_CASE : Union[str, Any] = 9_99_99_99_99 if remaining_time[short] == 0: complete += 1 SCREAMING_SNAKE_CASE : Optional[Any] = False # Find finish time of current process SCREAMING_SNAKE_CASE : Tuple = increment_time + 1 # Calculate waiting time SCREAMING_SNAKE_CASE : Optional[int] = finish_time - arrival_time[short] SCREAMING_SNAKE_CASE : Any = finar - burst_time[short] if waiting_time[short] < 0: SCREAMING_SNAKE_CASE : Tuple = 0 # Increment time increment_time += 1 return waiting_time def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = [0] * no_of_processes for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Any = burst_time[i] + waiting_time[i] return turn_around_time def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = total_waiting_time + waiting_time[i] SCREAMING_SNAKE_CASE : Union[str, Any] = total_turn_around_time + turn_around_time[i] print(f'''Average waiting time = {total_waiting_time / no_of_processes:.5f}''' ) print("""Average turn around time =""" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print("""Enter how many process you want to analyze""") __UpperCAmelCase = int(input()) __UpperCAmelCase = [0] * no_of_processes __UpperCAmelCase = [0] * no_of_processes __UpperCAmelCase = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("""Enter the arrival time and burst time for process:--""" + str(i + 1)) __UpperCAmelCase , __UpperCAmelCase = map(int, input().split()) __UpperCAmelCase = calculate_waitingtime(arrival_time, burst_time, no_of_processes) __UpperCAmelCase = burst_time __UpperCAmelCase = no_of_processes __UpperCAmelCase = waiting_time __UpperCAmelCase = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) __UpperCAmelCase = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ """Process""", """BurstTime""", """ArrivalTime""", """WaitingTime""", """TurnAroundTime""", ], ) # Printing the dataFrame pd.set_option("""display.max_rows""", fcfs.shape[0] + 1) print(fcfs)
79
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __UpperCAmelCase = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
1
'''simple docstring''' def __A ( lowerCamelCase_ ): """simple docstring""" if p < 2: raise ValueError("""p should not be less than 2!""" ) elif p == 2: return True SCREAMING_SNAKE_CASE : Optional[int] = 4 SCREAMING_SNAKE_CASE : Tuple = (1 << p) - 1 for _ in range(p - 2 ): SCREAMING_SNAKE_CASE : Optional[Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
79
'''simple docstring''' __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
79
1
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCAmelCase = """ Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)[\"depth\"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline(\"depth-estimation\") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to(\"cuda\") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to(\"cuda\") >>> img = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/cat.png\" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\") >>> prompt = \"A robot, 4k photo\" >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\" >>> generator = torch.Generator(device=\"cuda\").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save(\"robot_cat.png\") ``` """ def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=8 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Union[str, Any] , lowerCamelCase_ : UNetaDConditionModel , lowerCamelCase_ : DDPMScheduler , lowerCamelCase_ : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=lowerCamelCase_ , scheduler=lowerCamelCase_ , movq=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : str = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase_ ( self : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): '''simple docstring''' if latents is None: SCREAMING_SNAKE_CASE : Tuple = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ , device=lowerCamelCase_ , dtype=lowerCamelCase_ ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) SCREAMING_SNAKE_CASE : Dict = latents.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = latents * scheduler.init_noise_sigma return latents def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Dict=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE : List[Any] = torch.device(f'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple=0 ): '''simple docstring''' if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) SCREAMING_SNAKE_CASE : Any = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCamelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE : Union[str, Any] = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = cpu_offload_with_hook(lowerCamelCase_ , lowerCamelCase_ , prev_module_hook=lowerCamelCase_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE : str = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase_ ( self : str ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase_ , """_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() @replace_example_docstring(lowerCamelCase_ ) def __call__( self : Optional[Any] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : torch.FloatTensor , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 1_00 , lowerCamelCase_ : float = 4.0 , lowerCamelCase_ : int = 1 , lowerCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase_ : Optional[torch.FloatTensor] = None , lowerCamelCase_ : Optional[str] = "pil" , lowerCamelCase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._execution_device SCREAMING_SNAKE_CASE : Optional[int] = guidance_scale > 1.0 if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Any = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : List[Any] = image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Optional[int] = negative_image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Dict = hint.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) self.scheduler.set_timesteps(lowerCamelCase_ , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.timesteps SCREAMING_SNAKE_CASE : Any = self.movq.config.latent_channels SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = downscale_height_and_width(lowerCamelCase_ , lowerCamelCase_ , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCamelCase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Union[str, Any] = {"""image_embeds""": image_embeds, """hint""": hint} SCREAMING_SNAKE_CASE : Dict = self.unet( sample=lowerCamelCase_ , timestep=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , added_cond_kwargs=lowerCamelCase_ , return_dict=lowerCamelCase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE : str = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : str = self.scheduler.step( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ , )[0] # post-processing SCREAMING_SNAKE_CASE : List[str] = self.movq.decode(lowerCamelCase_ , force_not_quantize=lowerCamelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE : Optional[int] = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : List[Any] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Any = self.numpy_to_pil(lowerCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase_ )
79
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCAmelCase = """ Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)[\"depth\"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline(\"depth-estimation\") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to(\"cuda\") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to(\"cuda\") >>> img = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/cat.png\" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\") >>> prompt = \"A robot, 4k photo\" >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\" >>> generator = torch.Generator(device=\"cuda\").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save(\"robot_cat.png\") ``` """ def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=8 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Union[str, Any] , lowerCamelCase_ : UNetaDConditionModel , lowerCamelCase_ : DDPMScheduler , lowerCamelCase_ : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=lowerCamelCase_ , scheduler=lowerCamelCase_ , movq=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : str = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase_ ( self : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): '''simple docstring''' if latents is None: SCREAMING_SNAKE_CASE : Tuple = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ , device=lowerCamelCase_ , dtype=lowerCamelCase_ ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) SCREAMING_SNAKE_CASE : Dict = latents.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = latents * scheduler.init_noise_sigma return latents def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Dict=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE : List[Any] = torch.device(f'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple=0 ): '''simple docstring''' if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) SCREAMING_SNAKE_CASE : Any = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCamelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE : Union[str, Any] = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = cpu_offload_with_hook(lowerCamelCase_ , lowerCamelCase_ , prev_module_hook=lowerCamelCase_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE : str = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase_ ( self : str ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase_ , """_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() @replace_example_docstring(lowerCamelCase_ ) def __call__( self : Optional[Any] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : torch.FloatTensor , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 1_00 , lowerCamelCase_ : float = 4.0 , lowerCamelCase_ : int = 1 , lowerCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase_ : Optional[torch.FloatTensor] = None , lowerCamelCase_ : Optional[str] = "pil" , lowerCamelCase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._execution_device SCREAMING_SNAKE_CASE : Optional[int] = guidance_scale > 1.0 if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Any = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : List[Any] = image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Optional[int] = negative_image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Dict = hint.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) self.scheduler.set_timesteps(lowerCamelCase_ , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.timesteps SCREAMING_SNAKE_CASE : Any = self.movq.config.latent_channels SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = downscale_height_and_width(lowerCamelCase_ , lowerCamelCase_ , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCamelCase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Union[str, Any] = {"""image_embeds""": image_embeds, """hint""": hint} SCREAMING_SNAKE_CASE : Dict = self.unet( sample=lowerCamelCase_ , timestep=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , added_cond_kwargs=lowerCamelCase_ , return_dict=lowerCamelCase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE : str = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : str = self.scheduler.step( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ , )[0] # post-processing SCREAMING_SNAKE_CASE : List[str] = self.movq.decode(lowerCamelCase_ , force_not_quantize=lowerCamelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE : Optional[int] = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : List[Any] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Any = self.numpy_to_pil(lowerCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase_ )
79
1
'''simple docstring''' from __future__ import annotations from typing import TypedDict class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __A ( lowerCamelCase_ ): """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(lowerCamelCase_ ) )] def __A ( lowerCamelCase_ ): """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) SCREAMING_SNAKE_CASE : Tuple = all_rotations(lowerCamelCase_ ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation SCREAMING_SNAKE_CASE : BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(lowerCamelCase_ ), } return response def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): 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: SCREAMING_SNAKE_CASE : List[Any] = int(lowerCamelCase_ ) 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(lowerCamelCase_ ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) SCREAMING_SNAKE_CASE : List[str] = [""""""] * len(lowerCamelCase_ ) for _ in range(len(lowerCamelCase_ ) ): for i in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : Optional[Any] = 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}\'''' )
79
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """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""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = BigBirdTokenizer SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] SCREAMING_SNAKE_CASE__ = [] def __init__( self : Any , lowerCamelCase_ : str=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict="<unk>" , lowerCamelCase_ : int="<s>" , lowerCamelCase_ : Optional[Any]="</s>" , lowerCamelCase_ : Dict="<pad>" , lowerCamelCase_ : Tuple="[SEP]" , lowerCamelCase_ : Dict="[MASK]" , lowerCamelCase_ : Union[str, Any]="[CLS]" , **lowerCamelCase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else bos_token SCREAMING_SNAKE_CASE : Dict = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else eos_token SCREAMING_SNAKE_CASE : Optional[Any] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else unk_token SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else pad_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else cls_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Optional[Any] = False if not self.vocab_file else True def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : 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] def lowerCamelCase_ ( self : str , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' 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(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Tuple = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ): copyfile(self.vocab_file , lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' class UpperCamelCase__ : """simple docstring""" def __init__( self : Tuple , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = name SCREAMING_SNAKE_CASE : Optional[Any] = val def __str__( self : Union[str, Any] ): '''simple docstring''' return f'''{self.__class__.__name__}({self.name}, {self.val})''' def __lt__( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return self.val < other.val class UpperCamelCase__ : """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = {} SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Tuple = self.build_heap(lowerCamelCase_ ) def __getitem__( self : str , lowerCamelCase_ : str ): '''simple docstring''' return self.get_value(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return (idx - 1) // 2 def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[str] ): '''simple docstring''' return idx * 2 + 1 def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Dict ): '''simple docstring''' return idx * 2 + 2 def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.heap_dict[key] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = len(lowerCamelCase_ ) - 1 SCREAMING_SNAKE_CASE : Optional[Any] = self.get_parent_idx(lowerCamelCase_ ) for idx, i in enumerate(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = idx SCREAMING_SNAKE_CASE : List[Any] = i.val for i in range(lowerCamelCase_ , -1 , -1 ): self.sift_down(lowerCamelCase_ , lowerCamelCase_ ) return array def lowerCamelCase_ ( self : int , lowerCamelCase_ : Any , lowerCamelCase_ : List[Any] ): '''simple docstring''' while True: SCREAMING_SNAKE_CASE : int = self.get_left_child_idx(lowerCamelCase_ ) # noqa: E741 SCREAMING_SNAKE_CASE : List[Any] = self.get_right_child_idx(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = idx if l < len(lowerCamelCase_ ) and array[l] < array[idx]: SCREAMING_SNAKE_CASE : Dict = l if r < len(lowerCamelCase_ ) and array[r] < array[smallest]: SCREAMING_SNAKE_CASE : int = r if smallest != idx: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = array[smallest], array[idx] ( ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ) : Any = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) SCREAMING_SNAKE_CASE : List[Any] = smallest else: break def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_parent_idx(lowerCamelCase_ ) while p >= 0 and self.heap[p] > self.heap[idx]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = self.heap[idx], self.heap[p] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) SCREAMING_SNAKE_CASE : int = p SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_parent_idx(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.heap[0] def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = self.heap[-1], self.heap[0] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) SCREAMING_SNAKE_CASE : Dict = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[str] ): '''simple docstring''' self.heap.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = len(self.heap ) - 1 SCREAMING_SNAKE_CASE : str = node.val self.sift_up(len(self.heap ) - 1 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return len(self.heap ) == 0 def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" SCREAMING_SNAKE_CASE : Dict = new_value SCREAMING_SNAKE_CASE : Dict = new_value self.sift_up(self.idx_of_element[node] ) __UpperCAmelCase = Node("""R""", -1) __UpperCAmelCase = Node("""B""", 6) __UpperCAmelCase = Node("""A""", 3) __UpperCAmelCase = Node("""X""", 1) __UpperCAmelCase = Node("""E""", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __UpperCAmelCase = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("""Min Heap - before decrease key""") for i in my_min_heap.heap: print(i) print("""Min Heap - After decrease key of node [B -> -17]""") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
79
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""swish""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = get_activation("""silu""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""mish""" ) self.assertIsInstance(lowerCamelCase_ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = get_activation("""gelu""" ) self.assertIsInstance(lowerCamelCase_ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
79
1
'''simple docstring''' from math import factorial class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = real if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = [1] * rank else: SCREAMING_SNAKE_CASE : Dict = rank def __repr__( self : Union[str, Any] ): '''simple docstring''' return ( f'''{self.real}+''' f'''{"+".join(str(lowerCamelCase_ )+"E"+str(n+1 )for n,dual in enumerate(self.duals ) )}''' ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.duals.copy() while cur[-1] == 0: cur.pop(-1 ) return Dual(self.real , lowerCamelCase_ ) def __add__( self : Union[str, Any] , lowerCamelCase_ : Dict ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): return Dual(self.real + other , self.duals ) SCREAMING_SNAKE_CASE : Optional[Any] = self.duals.copy() SCREAMING_SNAKE_CASE : List[Any] = other.duals.copy() if len(lowerCamelCase_ ) > len(lowerCamelCase_ ): o_dual.extend([1] * (len(lowerCamelCase_ ) - len(lowerCamelCase_ )) ) elif len(lowerCamelCase_ ) < len(lowerCamelCase_ ): s_dual.extend([1] * (len(lowerCamelCase_ ) - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : Any = [] for i in range(len(lowerCamelCase_ ) ): new_duals.append(s_dual[i] + o_dual[i] ) return Dual(self.real + other.real , lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ = __add__ def __sub__( self : int , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self + other * -1 def __mul__( self : List[str] , lowerCamelCase_ : int ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = [] for i in self.duals: new_duals.append(i * other ) return Dual(self.real * other , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = [0] * (len(self.duals ) + len(other.duals ) + 1) for i, item in enumerate(self.duals ): for j, jtem in enumerate(other.duals ): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals ) ): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals ) ): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real , lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ = __mul__ def __truediv__( self : str , lowerCamelCase_ : int ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = [] for i in self.duals: new_duals.append(i / other ) return Dual(self.real / other , lowerCamelCase_ ) raise ValueError def __floordiv__( self : List[str] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = [] for i in self.duals: new_duals.append(i // other ) return Dual(self.real // other , lowerCamelCase_ ) raise ValueError def __pow__( self : int , lowerCamelCase_ : List[str] ): '''simple docstring''' if n < 0 or isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise ValueError("""power must be a positive integer""" ) if n == 0: return 1 if n == 1: return self SCREAMING_SNAKE_CASE : Optional[Any] = self for _ in range(n - 1 ): x *= self return x def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if not callable(lowerCamelCase_ ): raise ValueError("""differentiate() requires a function as input for func""" ) if not isinstance(lowerCamelCase_ , (float, int) ): raise ValueError("""differentiate() requires a float as input for position""" ) if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise ValueError("""differentiate() requires an int as input for order""" ) SCREAMING_SNAKE_CASE : Optional[int] = Dual(lowerCamelCase_ , 1 ) SCREAMING_SNAKE_CASE : Tuple = func(lowerCamelCase_ ) if order == 0: return result.real return result.duals[order - 1] * factorial(lowerCamelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() def __A ( lowerCamelCase_ ): """simple docstring""" return y**2 * y**4 print(differentiate(f, 9, 2))
79
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''deberta-v2''' def __init__( self : int , lowerCamelCase_ : Optional[Any]=12_81_00 , lowerCamelCase_ : str=15_36 , lowerCamelCase_ : int=24 , lowerCamelCase_ : List[str]=24 , lowerCamelCase_ : List[Any]=61_44 , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : str=0 , lowerCamelCase_ : Union[str, Any]=0.02 , lowerCamelCase_ : Dict=1e-7 , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : Optional[int]=-1 , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : Dict="gelu" , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : List[Any] = relative_attention SCREAMING_SNAKE_CASE : str = max_relative_positions SCREAMING_SNAKE_CASE : int = pad_token_id SCREAMING_SNAKE_CASE : List[str] = position_biased_input # Backwards compatibility if type(lowerCamelCase_ ) == str: SCREAMING_SNAKE_CASE : Dict = [x.strip() for x in pos_att_type.lower().split("""|""" )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = kwargs.get("""pooler_hidden_size""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = pooler_dropout SCREAMING_SNAKE_CASE : Any = pooler_hidden_act class UpperCamelCase__ ( lowercase_ ): """simple docstring""" @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE : Union[str, Any] = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return 12 def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional["TensorType"] = None , lowerCamelCase_ : int = 3 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = super().generate_dummy_inputs(preprocessor=lowerCamelCase_ , framework=lowerCamelCase_ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
79
1
'''simple docstring''' import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __UpperCAmelCase = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class UpperCamelCase__ ( datasets.BuilderConfig ): """simple docstring""" SCREAMING_SNAKE_CASE__ = None def __A ( lowerCamelCase_ , lowerCamelCase_ , ): """simple docstring""" import pyspark def generate_fn(): SCREAMING_SNAKE_CASE : List[str] = df.select("""*""" , pyspark.sql.functions.spark_partition_id().alias("""part_id""" ) ) for partition_id in partition_order: SCREAMING_SNAKE_CASE : List[str] = df_with_partition_id.select("""*""" ).where(f'''part_id = {partition_id}''' ).drop("""part_id""" ) SCREAMING_SNAKE_CASE : List[Any] = partition_df.collect() SCREAMING_SNAKE_CASE : Tuple = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class UpperCamelCase__ ( _BaseExamplesIterable ): """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase_ : "pyspark.sql.DataFrame" , lowerCamelCase_ : List[str]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = df SCREAMING_SNAKE_CASE : str = partition_order or range(self.df.rdd.getNumPartitions() ) SCREAMING_SNAKE_CASE : Tuple = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Tuple ): '''simple docstring''' yield from self.generate_examples_fn() def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : np.random.Generator ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(lowerCamelCase_ ) return SparkExamplesIterable(self.df , partition_order=lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.split_shard_indices_by_worker(lowerCamelCase_ , lowerCamelCase_ ) return SparkExamplesIterable(self.df , partition_order=lowerCamelCase_ ) @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return len(self.partition_order ) class UpperCamelCase__ ( datasets.DatasetBuilder ): """simple docstring""" SCREAMING_SNAKE_CASE__ = SparkConfig def __init__( self : Optional[Any] , lowerCamelCase_ : "pyspark.sql.DataFrame" , lowerCamelCase_ : str = None , lowerCamelCase_ : str = None , **lowerCamelCase_ : int , ): '''simple docstring''' import pyspark SCREAMING_SNAKE_CASE : Any = pyspark.sql.SparkSession.builder.getOrCreate() SCREAMING_SNAKE_CASE : List[str] = df SCREAMING_SNAKE_CASE : Optional[Any] = working_dir super().__init__( cache_dir=lowerCamelCase_ , config_name=str(self.df.semanticHash() ) , **lowerCamelCase_ , ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' def create_cache_and_write_probe(lowerCamelCase_ : str ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self._cache_dir , """fs_test""" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(lowerCamelCase_ , """a""" ) return [probe_file] if self._spark.conf.get("""spark.master""" , """""" ).startswith("""local""" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: SCREAMING_SNAKE_CASE : Optional[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(lowerCamelCase_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( """When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir""" ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : datasets.download.download_manager.DownloadManager ): '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : int ): '''simple docstring''' import pyspark def get_arrow_batch_size(lowerCamelCase_ : int ): for batch in it: yield pa.RecordBatch.from_pydict({"""batch_bytes""": [batch.nbytes]} ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.df.count() SCREAMING_SNAKE_CASE : int = df_num_rows if df_num_rows <= 1_00 else 1_00 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. SCREAMING_SNAKE_CASE : str = ( self.df.limit(lowerCamelCase_ ) .repartition(1 ) .mapInArrow(lowerCamelCase_ , """batch_bytes: long""" ) .agg(pyspark.sql.functions.sum("""batch_bytes""" ).alias("""sample_bytes""" ) ) .collect()[0] .sample_bytes / sample_num_rows ) SCREAMING_SNAKE_CASE : Dict = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. SCREAMING_SNAKE_CASE : Union[str, Any] = min(lowerCamelCase_ , int(approx_total_size / max_shard_size ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.df.repartition(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str , lowerCamelCase_ : str , lowerCamelCase_ : int , ): '''simple docstring''' import pyspark SCREAMING_SNAKE_CASE : List[str] = ParquetWriter if file_format == """parquet""" else ArrowWriter SCREAMING_SNAKE_CASE : Tuple = os.path.join(self._working_dir , os.path.basename(lowerCamelCase_ ) ) if self._working_dir else fpath SCREAMING_SNAKE_CASE : List[Any] = file_format == """parquet""" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. SCREAMING_SNAKE_CASE : int = self.config.features SCREAMING_SNAKE_CASE : Dict = self._writer_batch_size SCREAMING_SNAKE_CASE : Tuple = self._fs.storage_options def write_arrow(lowerCamelCase_ : List[Any] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. SCREAMING_SNAKE_CASE : Any = pyspark.TaskContext().taskAttemptId() SCREAMING_SNAKE_CASE : str = next(lowerCamelCase_ , lowerCamelCase_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) SCREAMING_SNAKE_CASE : Any = 0 SCREAMING_SNAKE_CASE : Any = writer_class( features=lowerCamelCase_ , path=working_fpath.replace("""SSSSS""" , f'''{shard_id:05d}''' ).replace("""TTTTT""" , f'''{task_id:05d}''' ) , writer_batch_size=lowerCamelCase_ , storage_options=lowerCamelCase_ , embed_local_files=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Tuple = pa.Table.from_batches([first_batch] ) writer.write_table(lowerCamelCase_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) shard_id += 1 SCREAMING_SNAKE_CASE : List[str] = writer_class( features=writer._features , path=working_fpath.replace("""SSSSS""" , f'''{shard_id:05d}''' ).replace("""TTTTT""" , f'''{task_id:05d}''' ) , writer_batch_size=lowerCamelCase_ , storage_options=lowerCamelCase_ , embed_local_files=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = pa.Table.from_batches([batch] ) writer.write_table(lowerCamelCase_ ) if writer._num_bytes > 0: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(os.path.dirname(lowerCamelCase_ ) , os.path.basename(lowerCamelCase_ ) ) shutil.move(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = ( self.df.mapInArrow(lowerCamelCase_ , """task_id: long, num_examples: long, num_bytes: long""" ) .groupBy("""task_id""" ) .agg( pyspark.sql.functions.sum("""num_examples""" ).alias("""total_num_examples""" ) , pyspark.sql.functions.sum("""num_bytes""" ).alias("""total_num_bytes""" ) , pyspark.sql.functions.count("""num_bytes""" ).alias("""num_shards""" ) , pyspark.sql.functions.collect_list("""num_examples""" ).alias("""shard_lengths""" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def lowerCamelCase_ ( self : str , lowerCamelCase_ : "datasets.SplitGenerator" , lowerCamelCase_ : str = "arrow" , lowerCamelCase_ : Optional[Union[str, int]] = None , lowerCamelCase_ : Optional[int] = None , **lowerCamelCase_ : List[Any] , ): '''simple docstring''' self._validate_cache_dir() SCREAMING_SNAKE_CASE : Any = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = not is_remote_filesystem(self._fs ) SCREAMING_SNAKE_CASE : Any = os.path.join if is_local else posixpath.join SCREAMING_SNAKE_CASE : Optional[int] = """-TTTTT-SSSSS-of-NNNNN""" SCREAMING_SNAKE_CASE : Optional[int] = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' SCREAMING_SNAKE_CASE : List[str] = path_join(self._output_dir , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : Any = 0 SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[int] = [] for task_id, content in self._prepare_split_single(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): ( ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ) : Union[str, Any] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = total_num_examples SCREAMING_SNAKE_CASE : Optional[Any] = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: SCREAMING_SNAKE_CASE : List[str] = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. SCREAMING_SNAKE_CASE : List[str] = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : int , ): rename( lowerCamelCase_ , fpath.replace("""SSSSS""" , f'''{shard_id:05d}''' ).replace("""TTTTT""" , f'''{task_id:05d}''' ) , fpath.replace("""TTTTT-SSSSS""" , f'''{global_shard_id:05d}''' ).replace("""NNNNN""" , f'''{total_shards:05d}''' ) , ) SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : Optional[int] = 0 for i in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = task_id_and_num_shards[i] for shard_id in range(lowerCamelCase_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(lowerCamelCase_ , len(lowerCamelCase_ ) ).map(lambda lowerCamelCase_ : _rename_shard(*lowerCamelCase_ ) ).collect() else: # don't use any pattern SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : int = task_id_and_num_shards[0][0] self._rename( fpath.replace("""SSSSS""" , f'''{shard_id:05d}''' ).replace("""TTTTT""" , f'''{task_id:05d}''' ) , fpath.replace(lowerCamelCase_ , """""" ) , ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : "datasets.SplitGenerator" , ): '''simple docstring''' return SparkExamplesIterable(self.df )
79
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = {} def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: SCREAMING_SNAKE_CASE : str = [[w, v]] if not self.graph.get(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = [] def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : str ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[str, Any]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Tuple = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Any = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[int]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : str = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : Union[str, Any] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Any=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = deque() SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : int = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Optional[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Union[str, Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : List[str] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[Any] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : int = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return sorted_nodes def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : Union[str, Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Any = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : int = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = s SCREAMING_SNAKE_CASE : List[Any] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = -2 SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Tuple = s SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : str = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Dict = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[str] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = s SCREAMING_SNAKE_CASE : Optional[int] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str=-2 , lowerCamelCase_ : int=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin def lowerCamelCase_ ( self : int , lowerCamelCase_ : Tuple=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, v]] # add the other way if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, u]] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) # the other way round if self.graph.get(lowerCamelCase_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : str=-2 , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] if s == -2: SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : Any = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : List[str] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = deque() SCREAMING_SNAKE_CASE : Tuple = [] if s == -2: SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : List[Any] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = -2 SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Optional[Any] = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : str = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Optional[int] = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Union[str, Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s SCREAMING_SNAKE_CASE : str = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = s SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Any = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : str = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Optional[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Tuple = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[str]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = time() return end - begin def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Dict=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = time() return end - begin
79
1
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __UpperCAmelCase = { """User-Agent""": """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582""" } def __A ( lowerCamelCase_ = "dhaka" , lowerCamelCase_ = 5 ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = min(lowerCamelCase_ , 50 ) # Prevent abuse! SCREAMING_SNAKE_CASE : Union[str, Any] = { """q""": query, """tbm""": """isch""", """hl""": """en""", """ijn""": """0""", } SCREAMING_SNAKE_CASE : Union[str, Any] = requests.get("""https://www.google.com/search""" , params=lowerCamelCase_ , headers=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = BeautifulSoup(html.text , """html.parser""" ) SCREAMING_SNAKE_CASE : Tuple = """""".join( re.findall(R"""AF_initDataCallback\(([^<]+)\);""" , str(soup.select("""script""" ) ) ) ) SCREAMING_SNAKE_CASE : Optional[Any] = json.dumps(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = json.loads(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = re.findall( R"""\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",""" , lowerCamelCase_ , ) if not matched_google_image_data: return 0 SCREAMING_SNAKE_CASE : int = re.sub( R"""\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]""" , """""" , str(lowerCamelCase_ ) , ) SCREAMING_SNAKE_CASE : Any = re.findall( R"""(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]""" , lowerCamelCase_ , ) for index, fixed_full_res_image in enumerate(lowerCamelCase_ ): if index >= max_images: return index SCREAMING_SNAKE_CASE : int = bytes(lowerCamelCase_ , """ascii""" ).decode( """unicode-escape""" ) SCREAMING_SNAKE_CASE : Dict = bytes(lowerCamelCase_ , """ascii""" ).decode( """unicode-escape""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = urllib.request.build_opener() SCREAMING_SNAKE_CASE : List[str] = [ ( """User-Agent""", """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582""", ) ] urllib.request.install_opener(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = f'''query_{query.replace(" " , "_" )}''' if not os.path.exists(lowerCamelCase_ ): os.makedirs(lowerCamelCase_ ) urllib.request.urlretrieve( # noqa: S310 lowerCamelCase_ , f'''{path_name}/original_size_img_{index}.jpg''' ) return index if __name__ == "__main__": try: __UpperCAmelCase = download_images_from_google_query(sys.argv[1]) print(f'''{image_count} images were downloaded to disk.''') except IndexError: print("""Please provide a search term.""") raise
79
'''simple docstring''' import os 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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} __UpperCAmelCase = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } __UpperCAmelCase = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple="<s>" , lowerCamelCase_ : Union[str, Any]="</s>" , lowerCamelCase_ : Tuple="</s>" , lowerCamelCase_ : str="<s>" , lowerCamelCase_ : Optional[int]="<unk>" , lowerCamelCase_ : List[Any]="<pad>" , lowerCamelCase_ : Optional[Any]="<mask>" , lowerCamelCase_ : Optional[Dict[str, Any]] = None , **lowerCamelCase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Dict = vocab_file SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} SCREAMING_SNAKE_CASE : str = len(self.sp_model ) - 1 SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1, 1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [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] @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return len(self.sp_model ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = {self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str ): '''simple docstring''' return self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.PieceToId(lowerCamelCase_ ) return spm_id if spm_id else self.unk_token_id def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[str] ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Tuple = """""" SCREAMING_SNAKE_CASE : Dict = 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(lowerCamelCase_ ) + token SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(lowerCamelCase_ ) return out_string.strip() def __getstate__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE : List[Any] = None return state def __setstate__( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Dict = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCamelCase_ , """wb""" ) as fi: SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[Any]=13 , lowerCamelCase_ : Tuple=7 , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Any=True , lowerCamelCase_ : int=False , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : Optional[int]=99 , lowerCamelCase_ : str=32 , lowerCamelCase_ : Tuple=5 , lowerCamelCase_ : Dict=4 , lowerCamelCase_ : List[str]=37 , lowerCamelCase_ : List[str]="gelu" , lowerCamelCase_ : Any=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : Tuple=5_12 , lowerCamelCase_ : Dict=16 , lowerCamelCase_ : List[str]=2 , lowerCamelCase_ : Optional[Any]=0.02 , lowerCamelCase_ : str=3 , lowerCamelCase_ : Tuple=4 , lowerCamelCase_ : int=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : int = seq_length SCREAMING_SNAKE_CASE : Optional[int] = is_training SCREAMING_SNAKE_CASE : List[Any] = use_input_mask SCREAMING_SNAKE_CASE : Tuple = use_token_type_ids SCREAMING_SNAKE_CASE : Any = use_labels SCREAMING_SNAKE_CASE : Optional[int] = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE : List[str] = type_vocab_size SCREAMING_SNAKE_CASE : Any = type_sequence_label_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = num_labels SCREAMING_SNAKE_CASE : List[Any] = num_choices SCREAMING_SNAKE_CASE : str = scope def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return BioGptConfig( 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=lowerCamelCase_ , initializer_range=self.initializer_range , ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Any , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = BioGptModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = BioGptForCausalLM(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() SCREAMING_SNAKE_CASE : int = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , token_type_ids=lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] , *lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = BioGptModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE : Optional[int] = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.seq_length // 2 SCREAMING_SNAKE_CASE : List[str] = 0 # first forward pass SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE : int = ids_tensor((1,) , lowerCamelCase_ ).item() + 1 SCREAMING_SNAKE_CASE : Dict = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=lowerCamelCase_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Optional[int] = model(lowerCamelCase_ , past_key_values=lowerCamelCase_ , attention_mask=lowerCamelCase_ )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE : Any = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE : Dict = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Tuple , *lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = BioGptModel(config=lowerCamelCase_ ).to(lowerCamelCase_ ).eval() SCREAMING_SNAKE_CASE : Optional[int] = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCamelCase_ ) # first forward pass SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , use_cache=lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE : Tuple = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Tuple = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ )[ """last_hidden_state""" ] # select random slice SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE : 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(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Union[str, Any] , *lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[int]=False ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = BioGptForCausalLM(lowerCamelCase_ ) model.to(lowerCamelCase_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE : Optional[Any] = model(lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : str , *lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = BioGptModel(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Any , lowerCamelCase_ : str , lowerCamelCase_ : str , lowerCamelCase_ : Any , *lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.num_labels SCREAMING_SNAKE_CASE : Optional[int] = BioGptForTokenClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , token_type_ids=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ( SCREAMING_SNAKE_CASE ), ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase__ ( lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { '''feature-extraction''': BioGptModel, '''text-classification''': BioGptForSequenceClassification, '''text-generation''': BioGptForCausalLM, '''token-classification''': BioGptForTokenClassification, '''zero-shot''': BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE : Optional[int] = ConfigTester(self , config_class=lowerCamelCase_ , hidden_size=37 ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE : Tuple = type self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*lowerCamelCase_ , gradient_checkpointing=lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*lowerCamelCase_ ) @slow def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) SCREAMING_SNAKE_CASE : Any = """left""" # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE : Optional[int] = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE : Optional[Any] = [ """Hello, my dog is a little""", """Today, I""", ] SCREAMING_SNAKE_CASE : int = tokenizer(lowerCamelCase_ , return_tensors="""pt""" , padding=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = inputs["""input_ids"""].to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model.generate( input_ids=lowerCamelCase_ , attention_mask=inputs["""attention_mask"""].to(lowerCamelCase_ ) , ) SCREAMING_SNAKE_CASE : Any = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = model.generate(input_ids=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE : Any = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = model.generate(input_ids=lowerCamelCase_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE : str = tokenizer.batch_decode(lowerCamelCase_ , skip_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , [non_padded_sentence, padded_sentence] ) @slow def lowerCamelCase_ ( self : Dict ): '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Optional[int] = BioGptModel.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : str = 3 SCREAMING_SNAKE_CASE : Optional[Any] = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE : Union[str, Any] = input_ids.ne(1 ).to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Dict = BioGptForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() SCREAMING_SNAKE_CASE : str = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : Tuple = 3 SCREAMING_SNAKE_CASE : Tuple = """multi_label_classification""" SCREAMING_SNAKE_CASE : Optional[Any] = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE : Any = input_ids.ne(1 ).to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE : Union[str, Any] = BioGptForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() SCREAMING_SNAKE_CASE : str = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) SCREAMING_SNAKE_CASE : List[Any] = model(lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : Any = 4_23_84 SCREAMING_SNAKE_CASE : str = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase_ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) SCREAMING_SNAKE_CASE : Tuple = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(lowerCamelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model.generate( **lowerCamelCase_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.decode(output_ids[0] , skip_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ )
79
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) SCREAMING_SNAKE_CASE : Dict = { """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 ), } SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , lowerCamelCase_ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
79
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __UpperCAmelCase = { """configuration_mobilevit""": ["""MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileViTConfig""", """MobileViTOnnxConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""MobileViTFeatureExtractor"""] __UpperCAmelCase = ["""MobileViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileViTForImageClassification""", """MobileViTForSemanticSegmentation""", """MobileViTModel""", """MobileViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFMobileViTForImageClassification""", """TFMobileViTForSemanticSegmentation""", """TFMobileViTModel""", """TFMobileViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''Translation''' , init=lowercase_ , repr=lowercase_ ) def __call__( self : int ): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''TranslationVariableLanguages''' , init=lowercase_ , repr=lowercase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = sorted(set(self.languages ) ) if self.languages else None SCREAMING_SNAKE_CASE : str = len(self.languages ) if self.languages else None def __call__( self : Tuple ): '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = set(self.languages ) if self.languages and set(lowerCamelCase_ ) - lang_set: raise ValueError( f'''Some languages in example ({", ".join(sorted(set(lowerCamelCase_ ) - lang_set ) )}) are not in valid set ({", ".join(lowerCamelCase_ )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE : List[Any] = [] for lang, text in translation_dict.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = zip(*sorted(lowerCamelCase_ ) ) return {"language": languages, "translation": translations} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
79
1
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = (DEISMultistepScheduler,) SCREAMING_SNAKE_CASE__ = (('''num_inference_steps''', 25),) def lowerCamelCase_ ( self : List[str] , **lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = { """num_train_timesteps""": 10_00, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """solver_order""": 2, } config.update(**lowerCamelCase_ ) return config def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Any=0 , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE : List[str] = kwargs.pop("""num_inference_steps""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.dummy_sample SCREAMING_SNAKE_CASE : Any = 0.1 * sample SCREAMING_SNAKE_CASE : str = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE : int = self.get_scheduler_config(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = scheduler_class.from_pretrained(lowerCamelCase_ ) new_scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE : List[str] = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = sample, sample for t in range(lowerCamelCase_ , time_step + scheduler.config.solver_order + 1 ): SCREAMING_SNAKE_CASE : Tuple = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample SCREAMING_SNAKE_CASE : Optional[int] = new_scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' pass def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Union[str, Any]=0 , **lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE : Optional[Any] = kwargs.pop("""num_inference_steps""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE : str = self.get_scheduler_config() SCREAMING_SNAKE_CASE : Any = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE : List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = scheduler_class.from_pretrained(lowerCamelCase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample SCREAMING_SNAKE_CASE : Tuple = new_scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Union[str, Any]=None , **lowerCamelCase_ : Optional[int] ): '''simple docstring''' if scheduler is None: SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_scheduler_config(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = scheduler_class(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE : str = self.get_scheduler_config(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = scheduler_class(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = 10 SCREAMING_SNAKE_CASE : Any = self.dummy_model() SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_sample_deter scheduler.set_timesteps(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE : Dict = model(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).prev_sample return sample def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE : int = kwargs.pop("""num_inference_steps""" , lowerCamelCase_ ) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE : str = self.get_scheduler_config() SCREAMING_SNAKE_CASE : Optional[Any] = scheduler_class(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowerCamelCase_ , """set_timesteps""" ): scheduler.set_timesteps(lowerCamelCase_ ) elif num_inference_steps is not None and not hasattr(lowerCamelCase_ , """set_timesteps""" ): SCREAMING_SNAKE_CASE : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] SCREAMING_SNAKE_CASE : int = dummy_past_residuals[: scheduler.config.solver_order] SCREAMING_SNAKE_CASE : int = scheduler.timesteps[5] SCREAMING_SNAKE_CASE : int = scheduler.timesteps[6] SCREAMING_SNAKE_CASE : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample SCREAMING_SNAKE_CASE : Tuple = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = DEISMultistepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.full_loop(scheduler=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 SCREAMING_SNAKE_CASE : List[str] = DPMSolverSinglestepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE : Tuple = DPMSolverMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE : Dict = UniPCMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE : int = DEISMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE : Optional[Any] = self.full_loop(scheduler=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 def lowerCamelCase_ ( self : str ): '''simple docstring''' for timesteps in [25, 50, 1_00, 9_99, 10_00]: self.check_over_configs(num_train_timesteps=lowerCamelCase_ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' self.check_over_configs(thresholding=lowerCamelCase_ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowerCamelCase_ , prediction_type=lowerCamelCase_ , sample_max_value=lowerCamelCase_ , algorithm_type="""deis""" , solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCamelCase_ ) def lowerCamelCase_ ( self : str ): '''simple docstring''' for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , prediction_type=lowerCamelCase_ , algorithm_type=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Dict = self.full_loop( solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , prediction_type=lowerCamelCase_ , algorithm_type=lowerCamelCase_ , ) assert not torch.isnan(lowerCamelCase_ ).any(), "Samples have nan numbers" def lowerCamelCase_ ( self : int ): '''simple docstring''' self.check_over_configs(lower_order_final=lowerCamelCase_ ) self.check_over_configs(lower_order_final=lowerCamelCase_ ) def lowerCamelCase_ ( self : str ): '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]: self.check_over_forward(num_inference_steps=lowerCamelCase_ , time_step=0 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.full_loop() SCREAMING_SNAKE_CASE : List[Any] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.full_loop(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE : Any = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.091 ) < 1e-3 def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE : List[str] = self.get_scheduler_config(thresholding=lowerCamelCase_ , dynamic_thresholding_ratio=0 ) SCREAMING_SNAKE_CASE : Dict = scheduler_class(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = 10 SCREAMING_SNAKE_CASE : Optional[int] = self.dummy_model() SCREAMING_SNAKE_CASE : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE : List[Any] = model(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).prev_sample assert sample.dtype == torch.floataa
79
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , *lowerCamelCase_ : List[str] , **lowerCamelCase_ : Dict ): '''simple docstring''' warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , lowerCamelCase_ , ) super().__init__(*lowerCamelCase_ , **lowerCamelCase_ )
79
1
'''simple docstring''' import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileBertTokenizer SCREAMING_SNAKE_CASE__ = MobileBertTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = filter_non_english SCREAMING_SNAKE_CASE__ = '''google/mobilebert-uncased''' def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[int] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE : str = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE : Any = """unwanted, running""" return input_text, output_text def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(lowerCamelCase_ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , [9, 6, 7, 12, 10, 11] ) def lowerCamelCase_ ( self : int ): '''simple docstring''' if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE : int = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Optional[int] = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) # With lower casing SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer(do_lower_case=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_rust_tokenizer(do_lower_case=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE : Tuple = tokenizer.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = rust_tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Dict = tokenizer.encode(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = rust_tokenizer.encode(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE : List[str] = {} for i, token in enumerate(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : List[str] = i SCREAMING_SNAKE_CASE : Union[str, Any] = WordpieceTokenizer(vocab=lowerCamelCase_ , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowerCamelCase_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) self.assertListEqual( [rust_tokenizer.tokenize(lowerCamelCase_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) @slow def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class.from_pretrained("""google/mobilebert-uncased""" ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode("""sequence builders""" , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode("""multi-sequence build""" , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ , lowerCamelCase_ ) assert encoded_sentence == [1_01] + text + [1_02] assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02] def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE : Optional[Any] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.encode_plus( lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ , return_offsets_mapping=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : int = tokenizer_r.do_lower_case if hasattr(lowerCamelCase_ , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE : Dict = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE : Tuple = """""".join(lowerCamelCase_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer_p.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_r.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.convert_ids_to_tokens(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_p.convert_ids_to_tokens(lowerCamelCase_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = False SCREAMING_SNAKE_CASE : int = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = tokenizer_r.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer_p.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = tokenizer_r.convert_ids_to_tokens(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = tokenizer_p.convert_ids_to_tokens(lowerCamelCase_ ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE : List[str] = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(lowerCamelCase_ ) ] self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
79
'''simple docstring''' 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 UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : str ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : int , lowerCamelCase_ : Dict ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Optional[int] ): '''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 lowerCamelCase_ ( cls : Any ): '''simple docstring''' return f'''`pip install {cls.pip_package or cls.name}`''' class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''optuna''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Dict ): '''simple docstring''' return run_hp_search_optuna(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Any ): '''simple docstring''' return default_hp_space_optuna(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''ray''' SCREAMING_SNAKE_CASE__ = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_ray_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_ray(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' return default_hp_space_ray(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''sigopt''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_sigopt(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return default_hp_space_sigopt(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''wandb''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return run_hp_search_wandb(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return default_hp_space_wandb(lowerCamelCase_ ) __UpperCAmelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCamelCase_ ) > 0: SCREAMING_SNAKE_CASE : List[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() ) )
79
1
'''simple docstring''' import random from .binary_exp_mod import bin_exp_mod def __A ( lowerCamelCase_ , lowerCamelCase_=10_00 ): """simple docstring""" if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd SCREAMING_SNAKE_CASE : Dict = n - 1 SCREAMING_SNAKE_CASE : str = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) SCREAMING_SNAKE_CASE : Dict = 0 while count < prec: SCREAMING_SNAKE_CASE : List[Any] = random.randint(2 , n - 1 ) SCREAMING_SNAKE_CASE : Tuple = bin_exp_mod(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if b != 1: SCREAMING_SNAKE_CASE : Any = True for _ in range(lowerCamelCase_ ): if b == n - 1: SCREAMING_SNAKE_CASE : int = False break SCREAMING_SNAKE_CASE : Optional[Any] = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": __UpperCAmelCase = abs(int(input("""Enter bound : """).strip())) print("""Here's the list of primes:""") print(""", """.join(str(i) for i in range(n + 1) if is_prime_big(i)))
79
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = 1 # (0 is vertical, 1 is horizontal) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = get_dataset(lowerCamelCase_ , lowerCamelCase_ ) print("""Processing...""" ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = update_image_and_anno(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for index, image in enumerate(lowerCamelCase_ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Optional[int] = random_chars(32 ) SCREAMING_SNAKE_CASE : Optional[Any] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE : Dict = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , lowerCamelCase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(lowerCamelCase_ )} with {file_name}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE : Optional[Any] = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(lowerCamelCase_ ) with open(f'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Any = [] for label_file in glob.glob(os.path.join(lowerCamelCase_ , """*.txt""" ) ): SCREAMING_SNAKE_CASE : str = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(lowerCamelCase_ ) as in_file: SCREAMING_SNAKE_CASE : Any = in_file.readlines() SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowerCamelCase_ , f'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE : Tuple = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : Union[str, Any] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(lowerCamelCase_ ) labels.append(lowerCamelCase_ ) return img_paths, labels def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [] for idx in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Dict = img_list[idx] path_list.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = anno_list[idx] SCREAMING_SNAKE_CASE : Optional[Any] = cva.imread(lowerCamelCase_ ) if flip_type == 1: SCREAMING_SNAKE_CASE : List[str] = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE : Any = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(lowerCamelCase_ ) new_imgs_list.append(lowerCamelCase_ ) return new_imgs_list, new_annos_lists, path_list def __A ( lowerCamelCase_ = 32 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : Dict = ascii_lowercase + digits return "".join(random.choice(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
79
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } __UpperCAmelCase = { """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = AlbertTokenizer def __init__( self : List[Any] , lowerCamelCase_ : Any=None , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Any=True , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : List[Any]="[CLS]" , lowerCamelCase_ : Optional[Any]="[SEP]" , lowerCamelCase_ : Any="<unk>" , lowerCamelCase_ : Union[str, Any]="[SEP]" , lowerCamelCase_ : Optional[Any]="<pad>" , lowerCamelCase_ : List[str]="[CLS]" , lowerCamelCase_ : List[Any]="[MASK]" , **lowerCamelCase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = ( AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ , normalized=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token ) super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , do_lower_case=lowerCamelCase_ , remove_space=lowerCamelCase_ , keep_accents=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[str] = do_lower_case SCREAMING_SNAKE_CASE : str = remove_space SCREAMING_SNAKE_CASE : Dict = keep_accents SCREAMING_SNAKE_CASE : Dict = vocab_file SCREAMING_SNAKE_CASE : Optional[int] = False if not self.vocab_file else True def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' 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(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : List[str] = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ): copyfile(self.vocab_file , lowerCamelCase_ ) return (out_vocab_file,)
79
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''vivit''' def __init__( self : Tuple , lowerCamelCase_ : str=2_24 , lowerCamelCase_ : List[Any]=32 , lowerCamelCase_ : Tuple=[2, 16, 16] , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Dict=12 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : List[Any]=30_72 , lowerCamelCase_ : List[str]="gelu_fast" , lowerCamelCase_ : str=0.0 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : List[Any]=1e-06 , lowerCamelCase_ : Tuple=True , **lowerCamelCase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Dict = num_frames SCREAMING_SNAKE_CASE : Optional[Any] = tubelet_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : int = qkv_bias super().__init__(**lowerCamelCase_ )
79
1
'''simple docstring''' 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 UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''tapas''' def __init__( self : str , lowerCamelCase_ : Tuple=3_05_22 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : Union[str, Any]=12 , lowerCamelCase_ : List[str]=30_72 , lowerCamelCase_ : str="gelu" , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : Optional[int]=10_24 , lowerCamelCase_ : Optional[Any]=[3, 2_56, 2_56, 2, 2_56, 2_56, 10] , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : Any=1e-12 , lowerCamelCase_ : Tuple=0 , lowerCamelCase_ : Tuple=10.0 , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : Optional[Any]=1.0 , lowerCamelCase_ : Any=None , lowerCamelCase_ : Optional[int]=1.0 , lowerCamelCase_ : Any=False , lowerCamelCase_ : Dict=None , lowerCamelCase_ : Optional[Any]=1.0 , lowerCamelCase_ : str=1.0 , lowerCamelCase_ : Optional[Any]=False , lowerCamelCase_ : int=False , lowerCamelCase_ : Optional[int]="ratio" , lowerCamelCase_ : Optional[Any]=None , lowerCamelCase_ : Union[str, Any]=None , lowerCamelCase_ : Optional[Any]=64 , lowerCamelCase_ : Optional[Any]=32 , lowerCamelCase_ : Dict=False , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : Any=False , lowerCamelCase_ : List[str]=False , lowerCamelCase_ : str=True , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : str=None , lowerCamelCase_ : Union[str, Any]=None , **lowerCamelCase_ : Dict , ): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) SCREAMING_SNAKE_CASE : Tuple = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Dict = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Any = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_sizes SCREAMING_SNAKE_CASE : Dict = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps # Fine-tuning task hyperparameters SCREAMING_SNAKE_CASE : Tuple = positive_label_weight SCREAMING_SNAKE_CASE : str = num_aggregation_labels SCREAMING_SNAKE_CASE : int = aggregation_loss_weight SCREAMING_SNAKE_CASE : str = use_answer_as_supervision SCREAMING_SNAKE_CASE : List[str] = answer_loss_importance SCREAMING_SNAKE_CASE : Optional[int] = use_normalized_answer_loss SCREAMING_SNAKE_CASE : Optional[int] = huber_loss_delta SCREAMING_SNAKE_CASE : Tuple = temperature SCREAMING_SNAKE_CASE : Union[str, Any] = aggregation_temperature SCREAMING_SNAKE_CASE : Union[str, Any] = use_gumbel_for_cells SCREAMING_SNAKE_CASE : Dict = use_gumbel_for_aggregation SCREAMING_SNAKE_CASE : str = average_approximation_function SCREAMING_SNAKE_CASE : Optional[Any] = cell_selection_preference SCREAMING_SNAKE_CASE : int = answer_loss_cutoff SCREAMING_SNAKE_CASE : int = max_num_rows SCREAMING_SNAKE_CASE : List[Any] = max_num_columns SCREAMING_SNAKE_CASE : Union[str, Any] = average_logits_per_cell SCREAMING_SNAKE_CASE : List[Any] = select_one_column SCREAMING_SNAKE_CASE : Optional[int] = allow_empty_column_selection SCREAMING_SNAKE_CASE : Union[str, Any] = init_cell_selection_weights_to_zero SCREAMING_SNAKE_CASE : Dict = reset_position_index_per_cell SCREAMING_SNAKE_CASE : Optional[int] = disable_per_token_loss # Aggregation hyperparameters SCREAMING_SNAKE_CASE : Optional[int] = aggregation_labels SCREAMING_SNAKE_CASE : Dict = no_aggregation_label_index if isinstance(self.aggregation_labels , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : List[str] = {int(lowerCamelCase_ ): v for k, v in aggregation_labels.items()}
79
'''simple docstring''' import math class UpperCamelCase__ : """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Tuple=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' SCREAMING_SNAKE_CASE : Any = n SCREAMING_SNAKE_CASE : Optional[int] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # adjacency matrix for weight SCREAMING_SNAKE_CASE : Union[str, Any] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # dp[i][j] stores minimum distance from i to j def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = w def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): SCREAMING_SNAKE_CASE : Union[str, Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": __UpperCAmelCase = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
79
1
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __UpperCAmelCase = logging.get_logger(__name__) @add_end_docstrings( lowercase_ , R''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def lowerCamelCase_ ( self : str , lowerCamelCase_ : GenericTensor ): '''simple docstring''' if self.framework == "tf": SCREAMING_SNAKE_CASE : Optional[int] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": SCREAMING_SNAKE_CASE : Optional[Any] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=lowerCamelCase_ ) else: raise ValueError("""Unsupported framework""" ) return masked_index def lowerCamelCase_ ( self : int , lowerCamelCase_ : GenericTensor ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.get_masked_index(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , f'''No mask_token ({self.tokenizer.mask_token}) found on the input''' , ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : GenericTensor ): '''simple docstring''' if isinstance(lowerCamelCase_ , lowerCamelCase_ ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Tuple=None , **lowerCamelCase_ : List[str] ): '''simple docstring''' if return_tensors is None: SCREAMING_SNAKE_CASE : Dict = self.framework SCREAMING_SNAKE_CASE : Tuple = self.tokenizer(lowerCamelCase_ , return_tensors=lowerCamelCase_ ) self.ensure_exactly_one_mask_token(lowerCamelCase_ ) return model_inputs def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.model(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = model_inputs["""input_ids"""] return model_outputs def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[int]=5 , lowerCamelCase_ : Dict=None ): '''simple docstring''' if target_ids is not None and target_ids.shape[0] < top_k: SCREAMING_SNAKE_CASE : List[Any] = target_ids.shape[0] SCREAMING_SNAKE_CASE : Dict = model_outputs["""input_ids"""][0] SCREAMING_SNAKE_CASE : List[str] = model_outputs["""logits"""] if self.framework == "tf": SCREAMING_SNAKE_CASE : str = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] SCREAMING_SNAKE_CASE : Optional[Any] = outputs.numpy() SCREAMING_SNAKE_CASE : Tuple = outputs[0, masked_index, :] SCREAMING_SNAKE_CASE : Dict = stable_softmax(lowerCamelCase_ , axis=-1 ) if target_ids is not None: SCREAMING_SNAKE_CASE : Any = tf.gather_nd(tf.squeeze(lowerCamelCase_ , 0 ) , target_ids.reshape(-1 , 1 ) ) SCREAMING_SNAKE_CASE : str = tf.expand_dims(lowerCamelCase_ , 0 ) SCREAMING_SNAKE_CASE : List[Any] = tf.math.top_k(lowerCamelCase_ , k=lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = topk.values.numpy(), topk.indices.numpy() else: SCREAMING_SNAKE_CASE : int = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=lowerCamelCase_ ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample SCREAMING_SNAKE_CASE : Any = outputs[0, masked_index, :] SCREAMING_SNAKE_CASE : Optional[int] = logits.softmax(dim=-1 ) if target_ids is not None: SCREAMING_SNAKE_CASE : int = probs[..., target_ids] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = probs.topk(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[str] = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): SCREAMING_SNAKE_CASE : Dict = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place SCREAMING_SNAKE_CASE : Tuple = input_ids.numpy().copy() if target_ids is not None: SCREAMING_SNAKE_CASE : List[str] = target_ids[p].tolist() SCREAMING_SNAKE_CASE : str = p # Filter padding out: SCREAMING_SNAKE_CASE : Tuple = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.decode(lowerCamelCase_ , skip_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p] ), """sequence""": sequence} row.append(lowerCamelCase_ ) result.append(lowerCamelCase_ ) if single_mask: return result[0] return result def lowerCamelCase_ ( self : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Union[str, Any]=None ): '''simple docstring''' if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : List[str] = [targets] try: SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.get_vocab() except Exception: SCREAMING_SNAKE_CASE : Dict = {} SCREAMING_SNAKE_CASE : Any = [] for target in targets: SCREAMING_SNAKE_CASE : Optional[int] = vocab.get(lowerCamelCase_ , lowerCamelCase_ ) if id_ is None: SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer( lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ , max_length=1 , truncation=lowerCamelCase_ , )["""input_ids"""] if len(lowerCamelCase_ ) == 0: logger.warning( f'''The specified target token `{target}` does not exist in the model vocabulary. ''' """We cannot replace it with anything meaningful, ignoring it""" ) continue SCREAMING_SNAKE_CASE : Union[str, Any] = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'''The specified target token `{target}` does not exist in the model vocabulary. ''' f'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.''' ) target_ids.append(id_ ) SCREAMING_SNAKE_CASE : Optional[Any] = list(set(lowerCamelCase_ ) ) if len(lowerCamelCase_ ) == 0: raise ValueError("""At least one target must be provided when passed.""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array(lowerCamelCase_ ) return target_ids def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : int=None , lowerCamelCase_ : Optional[int]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {} if targets is not None: SCREAMING_SNAKE_CASE : List[str] = self.get_target_ids(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = target_ids if top_k is not None: SCREAMING_SNAKE_CASE : Any = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , """The tokenizer does not define a `mask_token`.""" ) return {}, {}, postprocess_params def __call__( self : Optional[int] , lowerCamelCase_ : Tuple , *lowerCamelCase_ : Optional[Any] , **lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = super().__call__(lowerCamelCase_ , **lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(lowerCamelCase_ ) == 1: return outputs[0] return outputs
79
'''simple docstring''' import math def __A ( lowerCamelCase_ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __A ( lowerCamelCase_ = 1_00_01 ): """simple docstring""" try: SCREAMING_SNAKE_CASE : Tuple = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError("""Parameter nth must be int or castable to int.""" ) from None if nth <= 0: raise ValueError("""Parameter nth must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE : list[int] = [] SCREAMING_SNAKE_CASE : Dict = 2 while len(lowerCamelCase_ ) < nth: if is_prime(lowerCamelCase_ ): primes.append(lowerCamelCase_ ) num += 1 else: num += 1 return primes[len(lowerCamelCase_ ) - 1] if __name__ == "__main__": print(f'''{solution() = }''')
79
1
'''simple docstring''' from __future__ import annotations from math import pi def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if inductance < 0: raise ValueError("""Inductance cannot be negative""" ) if frequency < 0: raise ValueError("""Frequency cannot be negative""" ) if reactance < 0: raise ValueError("""Inductive reactance cannot be negative""" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
79
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __UpperCAmelCase = {"""UserAgent""": UserAgent().random} def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = script.contents[0] SCREAMING_SNAKE_CASE : int = json.loads(data[data.find("""{\"config\"""" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f'''https://www.instagram.com/{username}/''' SCREAMING_SNAKE_CASE : Any = self.get_json() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = requests.get(self.url , headers=lowerCamelCase_ ).text SCREAMING_SNAKE_CASE : List[Any] = BeautifulSoup(lowerCamelCase_ , """html.parser""" ).find_all("""script""" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Dict ): '''simple docstring''' return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self : int ): '''simple docstring''' return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return self.user_data["username"] @property def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return self.user_data["full_name"] @property def lowerCamelCase_ ( self : int ): '''simple docstring''' return self.user_data["biography"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["business_email"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["external_url"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowerCamelCase_ ( self : str ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return self.user_data["is_verified"] @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.user_data["is_private"] def __A ( lowerCamelCase_ = "github" ): """simple docstring""" import os if os.environ.get("""CI""" ): return # test failing on GitHub Actions SCREAMING_SNAKE_CASE : Any = InstagramUser(lowerCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , lowerCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("""https://instagram.""" ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = InstagramUser("""github""") print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
79
1
'''simple docstring''' import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Optional[Any] , lowerCamelCase_ : UNetaDModel , lowerCamelCase_ : UNetaDModel , lowerCamelCase_ : DDPMScheduler , lowerCamelCase_ : Optional[Any] , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Tuple = value_function SCREAMING_SNAKE_CASE : Dict = unet SCREAMING_SNAKE_CASE : Dict = scheduler SCREAMING_SNAKE_CASE : Any = env SCREAMING_SNAKE_CASE : Optional[int] = env.get_dataset() SCREAMING_SNAKE_CASE : List[Any] = {} for key in self.data.keys(): try: SCREAMING_SNAKE_CASE : int = self.data[key].mean() except: # noqa: E722 pass SCREAMING_SNAKE_CASE : Optional[Any] = {} for key in self.data.keys(): try: SCREAMING_SNAKE_CASE : Tuple = self.data[key].std() except: # noqa: E722 pass SCREAMING_SNAKE_CASE : Dict = env.observation_space.shape[0] SCREAMING_SNAKE_CASE : Any = env.action_space.shape[0] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Dict ): '''simple docstring''' return (x_in - self.means[key]) / self.stds[key] def lowerCamelCase_ ( self : str , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return x_in * self.stds[key] + self.means[key] def lowerCamelCase_ ( self : Any , lowerCamelCase_ : int ): '''simple docstring''' if type(lowerCamelCase_ ) is dict: return {k: self.to_torch(lowerCamelCase_ ) for k, v in x_in.items()} elif torch.is_tensor(lowerCamelCase_ ): return x_in.to(self.unet.device ) return torch.tensor(lowerCamelCase_ , device=self.unet.device ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : Any ): '''simple docstring''' for key, val in cond.items(): SCREAMING_SNAKE_CASE : List[Any] = val.clone() return x_in def lowerCamelCase_ ( self : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = x.shape[0] SCREAMING_SNAKE_CASE : List[Any] = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model SCREAMING_SNAKE_CASE : List[str] = torch.full((batch_size,) , lowerCamelCase_ , device=self.unet.device , dtype=torch.long ) for _ in range(lowerCamelCase_ ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models SCREAMING_SNAKE_CASE : Dict = self.value_function(x.permute(0 , 2 , 1 ) , lowerCamelCase_ ).sample SCREAMING_SNAKE_CASE : str = torch.autograd.grad([y.sum()] , [x] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler._get_variance(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch.exp(0.5 * posterior_variance ) SCREAMING_SNAKE_CASE : Tuple = model_std * grad SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : int = x.detach() SCREAMING_SNAKE_CASE : Union[str, Any] = x + scale * grad SCREAMING_SNAKE_CASE : Tuple = self.reset_xa(lowerCamelCase_ , lowerCamelCase_ , self.action_dim ) SCREAMING_SNAKE_CASE : int = self.unet(x.permute(0 , 2 , 1 ) , lowerCamelCase_ ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , predict_epsilon=lowerCamelCase_ )["""prev_sample"""] # apply conditions to the trajectory (set the initial state) SCREAMING_SNAKE_CASE : List[str] = self.reset_xa(lowerCamelCase_ , lowerCamelCase_ , self.action_dim ) SCREAMING_SNAKE_CASE : Tuple = self.to_torch(lowerCamelCase_ ) return x, y def __call__( self : Union[str, Any] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple=64 , lowerCamelCase_ : List[str]=32 , lowerCamelCase_ : Optional[Any]=2 , lowerCamelCase_ : Any=0.1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.normalize(lowerCamelCase_ , """observations""" ) SCREAMING_SNAKE_CASE : Optional[int] = obs[None].repeat(lowerCamelCase_ , axis=0 ) SCREAMING_SNAKE_CASE : Tuple = {0: self.to_torch(lowerCamelCase_ )} SCREAMING_SNAKE_CASE : Optional[Any] = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) SCREAMING_SNAKE_CASE : Tuple = randn_tensor(lowerCamelCase_ , device=self.unet.device ) SCREAMING_SNAKE_CASE : List[str] = self.reset_xa(lowerCamelCase_ , lowerCamelCase_ , self.action_dim ) SCREAMING_SNAKE_CASE : str = self.to_torch(lowerCamelCase_ ) # run the diffusion process SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self.run_diffusion(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # sort output trajectories by value SCREAMING_SNAKE_CASE : List[Any] = y.argsort(0 , descending=lowerCamelCase_ ).squeeze() SCREAMING_SNAKE_CASE : int = x[sorted_idx] SCREAMING_SNAKE_CASE : List[Any] = sorted_values[:, :, : self.action_dim] SCREAMING_SNAKE_CASE : Union[str, Any] = actions.detach().cpu().numpy() SCREAMING_SNAKE_CASE : str = self.de_normalize(lowerCamelCase_ , key="""actions""" ) # select the action with the highest value if y is not None: SCREAMING_SNAKE_CASE : int = 0 else: # if we didn't run value guiding, select a random action SCREAMING_SNAKE_CASE : Optional[int] = np.random.randint(0 , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = denorm_actions[selected_index, 0] return denorm_actions
79
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __UpperCAmelCase = logging.getLogger(__name__) __UpperCAmelCase = """Hello world! cécé herlolip""" __UpperCAmelCase = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = BertAbsConfig( temp_dir=""".""" , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="""bert""" , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : int = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) SCREAMING_SNAKE_CASE : List[str] = AbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) , lowerCamelCase_ ) original.eval() SCREAMING_SNAKE_CASE : Optional[int] = BertAbsSummarizer(lowerCamelCase_ , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) SCREAMING_SNAKE_CASE : int = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowerCamelCase_ )) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE : Optional[int] = encoder_input_ids SCREAMING_SNAKE_CASE : Optional[Any] = decoder_input_ids SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE : str = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = original.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] SCREAMING_SNAKE_CASE : str = new_model.generator(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Any = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) __UpperCAmelCase = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
79
1
'''simple docstring''' from __future__ import annotations __UpperCAmelCase = 8.988e9 # units = N * m^s * C^-2 def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if distance < 0: raise ValueError("""Distance cannot be negative""" ) if force == 0: SCREAMING_SNAKE_CASE : Dict = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: SCREAMING_SNAKE_CASE : Optional[int] = abs(lowerCamelCase_ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: SCREAMING_SNAKE_CASE : List[Any] = abs(lowerCamelCase_ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: SCREAMING_SNAKE_CASE : List[Any] = (COULOMBS_CONSTANT * charge_product / abs(lowerCamelCase_ )) ** 0.5 return {"distance": distance} raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
79
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=True , lowerCamelCase_="pt" ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {"""add_prefix_space""": True} if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and not line.startswith(""" """ ) else {} SCREAMING_SNAKE_CASE : Optional[Any] = padding_side return tokenizer( [line] , max_length=lowerCamelCase_ , padding="""max_length""" if pad_to_max_length else None , truncation=lowerCamelCase_ , return_tensors=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , **lowerCamelCase_ , ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , ): """simple docstring""" SCREAMING_SNAKE_CASE : int = input_ids.ne(lowerCamelCase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : str , lowerCamelCase_ : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str]="train" , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : int=None , lowerCamelCase_ : Union[str, Any]="" , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : str = Path(lowerCamelCase_ ).joinpath(type_path + """.source""" ) SCREAMING_SNAKE_CASE : Optional[Any] = Path(lowerCamelCase_ ).joinpath(type_path + """.target""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_char_lens(self.src_file ) SCREAMING_SNAKE_CASE : int = max_source_length SCREAMING_SNAKE_CASE : str = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' SCREAMING_SNAKE_CASE : List[str] = tokenizer SCREAMING_SNAKE_CASE : Dict = prefix if n_obs is not None: SCREAMING_SNAKE_CASE : List[Any] = self.src_lens[:n_obs] SCREAMING_SNAKE_CASE : int = src_lang SCREAMING_SNAKE_CASE : Optional[int] = tgt_lang def __len__( self : List[Any] ): '''simple docstring''' return len(self.src_lens ) def __getitem__( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = index + 1 # linecache starts at 1 SCREAMING_SNAKE_CASE : Dict = self.prefix + linecache.getline(str(self.src_file ) , lowerCamelCase_ ).rstrip("""\n""" ) SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , lowerCamelCase_ ).rstrip("""\n""" ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , lowerCamelCase_ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer ) SCREAMING_SNAKE_CASE : Any = self.tokenizer.generator if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer SCREAMING_SNAKE_CASE : Optional[int] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_source_length , """right""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_target_length , """right""" ) SCREAMING_SNAKE_CASE : Tuple = source_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : Tuple = target_inputs["""input_ids"""].squeeze() SCREAMING_SNAKE_CASE : List[str] = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : Dict ): '''simple docstring''' return [len(lowerCamelCase_ ) for x in Path(lowerCamelCase_ ).open().readlines()] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = torch.stack([x["""input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""attention_mask"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = torch.stack([x["""decoder_input_ids"""] for x in batch] ) SCREAMING_SNAKE_CASE : int = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = trim_batch(lowerCamelCase_ , lowerCamelCase_ , attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch __UpperCAmelCase = getLogger(__name__) def __A ( lowerCamelCase_ ): """simple docstring""" return list(itertools.chain.from_iterable(lowerCamelCase_ ) ) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = get_git_info() save_json(lowerCamelCase_ , os.path.join(lowerCamelCase_ , """git_log.json""" ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=4 , **lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """w""" ) as f: json.dump(lowerCamelCase_ , lowerCamelCase_ , indent=lowerCamelCase_ , **lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ ) as f: return json.load(lowerCamelCase_ ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = git.Repo(search_parent_directories=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { """repo_id""": str(lowerCamelCase_ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return list(map(lowerCamelCase_ , lowerCamelCase_ ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """wb""" ) as f: return pickle.dump(lowerCamelCase_ , lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" def remove_articles(lowerCamelCase_ ): return re.sub(R"""\b(a|an|the)\b""" , """ """ , lowerCamelCase_ ) def white_space_fix(lowerCamelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_ ) ) ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Optional[int] = normalize_answer(lowerCamelCase_ ).split() SCREAMING_SNAKE_CASE : Tuple = Counter(lowerCamelCase_ ) & Counter(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = sum(common.values() ) if num_same == 0: return 0 SCREAMING_SNAKE_CASE : Optional[int] = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = 1.0 * num_same / len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = (2 * precision * recall) / (precision + recall) return fa def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return normalize_answer(lowerCamelCase_ ) == normalize_answer(lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert len(lowerCamelCase_ ) == len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowerCamelCase_ , lowerCamelCase_ ): em += exact_match_score(lowerCamelCase_ , lowerCamelCase_ ) if len(lowerCamelCase_ ) > 0: em /= len(lowerCamelCase_ ) return {"em": em} def __A ( lowerCamelCase_ ): """simple docstring""" return model_prefix.startswith("""rag""" ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead SCREAMING_SNAKE_CASE : Dict = """dropout_rate""" for p in extra_params: if getattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): if not hasattr(lowerCamelCase_ , lowerCamelCase_ ) and not hasattr(lowerCamelCase_ , equivalent_param[p] ): logger.info("""config doesn't have a `{}` attribute""".format(lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) continue SCREAMING_SNAKE_CASE : Dict = p if hasattr(lowerCamelCase_ , lowerCamelCase_ ) else equivalent_param[p] setattr(lowerCamelCase_ , lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) delattr(lowerCamelCase_ , lowerCamelCase_ ) return hparams, config
79
1
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __UpperCAmelCase = ( """4S 3H 2C 7S 5H""", """9D 8H 2C 6S 7H""", """2D 6D 9D TH 7D""", """TC 8C 2S JH 6C""", """JH 8S TH AH QH""", """TS KS 5S 9S AC""", """KD 6S 9D TH AD""", """KS 8D 4D 9S 4S""", # pair """8C 4S KH JS 4D""", # pair """QH 8H KD JH 8S""", # pair """KC 4H KS 2H 8D""", # pair """KD 4S KC 3H 8S""", # pair """AH 8S AS KC JH""", # pair """3H 4C 4H 3S 2H""", # 2 pairs """5S 5D 2C KH KH""", # 2 pairs """3C KH 5D 5S KH""", # 2 pairs """AS 3C KH AD KH""", # 2 pairs """7C 7S 3S 7H 5S""", # 3 of a kind """7C 7S KH 2H 7H""", # 3 of a kind """AC KH QH AH AS""", # 3 of a kind """2H 4D 3C AS 5S""", # straight (low ace) """3C 5C 4C 2C 6H""", # straight """6S 8S 7S 5H 9H""", # straight """JS QS 9H TS KH""", # straight """QC KH TS JS AH""", # straight (high ace) """8C 9C 5C 3C TC""", # flush """3S 8S 9S 5S KS""", # flush """4C 5C 9C 8C KC""", # flush """JH 8H AH KH QH""", # flush """3D 2H 3H 2C 2D""", # full house """2H 2C 3S 3H 3D""", # full house """KH KC 3S 3H 3D""", # full house """JC 6H JS JD JH""", # 4 of a kind """JC 7H JS JD JH""", # 4 of a kind """JC KH JS JD JH""", # 4 of a kind """2S AS 4S 5S 3S""", # straight flush (low ace) """2D 6D 3D 4D 5D""", # straight flush """5C 6C 3C 7C 4C""", # straight flush """JH 9H TH KH QH""", # straight flush """JH AH TH KH QH""", # royal flush (high ace straight flush) ) __UpperCAmelCase = ( ("""2H 3H 4H 5H 6H""", """KS AS TS QS JS""", """Loss"""), ("""2H 3H 4H 5H 6H""", """AS AD AC AH JD""", """Win"""), ("""AS AH 2H AD AC""", """JS JD JC JH 3D""", """Win"""), ("""2S AH 2H AS AC""", """JS JD JC JH AD""", """Loss"""), ("""2S AH 2H AS AC""", """2H 3H 5H 6H 7H""", """Win"""), ("""AS 3S 4S 8S 2S""", """2H 3H 5H 6H 7H""", """Win"""), ("""2H 3H 5H 6H 7H""", """2S 3H 4H 5S 6C""", """Win"""), ("""2S 3H 4H 5S 6C""", """3D 4C 5H 6H 2S""", """Tie"""), ("""2S 3H 4H 5S 6C""", """AH AC 5H 6H AS""", """Win"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H AS""", """Loss"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H 7S""", """Win"""), ("""6S AD 7H 4S AS""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S AH 4H 5S KC""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S 3H 6H 7S 9C""", """7H 3C TH 6H 9S""", """Loss"""), ("""4S 5H 6H TS AC""", """3S 5H 6H TS AC""", """Win"""), ("""2S AH 4H 5S 6C""", """AD 4C 5H 6H 2C""", """Tie"""), ("""AS AH 3H AD AC""", """AS AH 2H AD AC""", """Win"""), ("""AH AC 5H 5C QS""", """AH AC 5H 5C KS""", """Loss"""), ("""AH AC 5H 5C QS""", """KH KC 5H 5C QS""", """Win"""), ("""7C 7S KH 2H 7H""", """3C 3S AH 2H 3H""", """Win"""), ("""3C 3S AH 2H 3H""", """7C 7S KH 2H 7H""", """Loss"""), ("""6H 5H 4H 3H 2H""", """5H 4H 3H 2H AH""", """Win"""), ("""5H 4H 3H 2H AH""", """5H 4H 3H 2H AH""", """Tie"""), ("""5H 4H 3H 2H AH""", """6H 5H 4H 3H 2H""", """Loss"""), ("""AH AD KS KC AC""", """AH KD KH AC KC""", """Win"""), ("""2H 4D 3C AS 5S""", """2H 4D 3C 6S 5S""", """Loss"""), ("""2H 3S 3C 3H 2S""", """3S 3C 2S 2H 2D""", """Win"""), ("""4D 6D 5D 2D JH""", """3S 8S 3H TC KH""", """Loss"""), ("""4S 6C 8S 3S 7S""", """AD KS 2D 7D 7C""", """Loss"""), ("""6S 4C 7H 8C 3H""", """5H JC AH 9D 9C""", """Loss"""), ("""9D 9H JH TC QH""", """3C 2S JS 5C 7H""", """Win"""), ("""2H TC 8S AD 9S""", """4H TS 7H 2C 5C""", """Win"""), ("""9D 3S 2C 7S 7C""", """JC TD 3C TC 9H""", """Loss"""), ) __UpperCAmelCase = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", True), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", False), ("""AS 3S 4S 8S 2S""", True), ) __UpperCAmelCase = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", False), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", True), ) __UpperCAmelCase = ( ("""2H 4D 3C AS 5S""", True, [5, 4, 3, 2, 14]), ("""2H 5D 3C AS 5S""", False, [14, 5, 5, 3, 2]), ("""JH QD KC AS TS""", False, [14, 13, 12, 11, 10]), ("""9D 3S 2C 7S 7C""", False, [9, 7, 7, 3, 2]), ) __UpperCAmelCase = ( ("""JH AH TH KH QH""", 0), ("""JH 9H TH KH QH""", 0), ("""JC KH JS JD JH""", 7), ("""KH KC 3S 3H 3D""", 6), ("""8C 9C 5C 3C TC""", 0), ("""JS QS 9H TS KH""", 0), ("""7C 7S KH 2H 7H""", 3), ("""3C KH 5D 5S KH""", 2), ("""QH 8H KD JH 8S""", 1), ("""2D 6D 9D TH 7D""", 0), ) __UpperCAmelCase = ( ("""JH AH TH KH QH""", 23), ("""JH 9H TH KH QH""", 22), ("""JC KH JS JD JH""", 21), ("""KH KC 3S 3H 3D""", 20), ("""8C 9C 5C 3C TC""", 19), ("""JS QS 9H TS KH""", 18), ("""7C 7S KH 2H 7H""", 17), ("""3C KH 5D 5S KH""", 16), ("""QH 8H KD JH 8S""", 15), ("""2D 6D 9D TH 7D""", 14), ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = randrange(len(lowerCamelCase_ ) ), randrange(len(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = ["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __A ( lowerCamelCase_ = 1_00 ): """simple docstring""" return (generate_random_hand() for _ in range(lowerCamelCase_ )) @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert PokerHand(lowerCamelCase_ )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert PokerHand(lowerCamelCase_ )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" , lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = PokerHand(lowerCamelCase_ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert PokerHand(lowerCamelCase_ )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert PokerHand(lowerCamelCase_ )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" , lowerCamelCase_ ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert PokerHand(lowerCamelCase_ ).compare_with(PokerHand(lowerCamelCase_ ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" , generate_random_hands() ) def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" assert PokerHand(lowerCamelCase_ ).compare_with(PokerHand(lowerCamelCase_ ) ) == expected def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [PokerHand(lowerCamelCase_ ) for hand in SORTED_HANDS] SCREAMING_SNAKE_CASE : Any = poker_hands.copy() shuffle(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = chain(sorted(lowerCamelCase_ ) ) for index, hand in enumerate(lowerCamelCase_ ): assert hand == poker_hands[index] def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=lowerCamelCase_ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = PokerHand("""2C 4S AS 3D 5C""" ) SCREAMING_SNAKE_CASE : Dict = True SCREAMING_SNAKE_CASE : str = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = 0 SCREAMING_SNAKE_CASE : Dict = os.path.abspath(os.path.dirname(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(lowerCamelCase_ , """poker_hands.txt""" ) with open(lowerCamelCase_ ) as file_hand: for line in file_hand: SCREAMING_SNAKE_CASE : Optional[int] = line[:14].strip() SCREAMING_SNAKE_CASE : Dict = line[15:].strip() SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = PokerHand(lowerCamelCase_ ), PokerHand(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = player.compare_with(lowerCamelCase_ ) if output == "Win": answer += 1 assert answer == 3_76
79
'''simple docstring''' def __A ( lowerCamelCase_ ): """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : List[str] = number while duplicate > 0: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = divmod(lowerCamelCase_ , 10 ) fact_sum += factorial(lowerCamelCase_ ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") __UpperCAmelCase = int(input("""Enter number: """).strip()) print( f'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
79
1
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def __A ( lowerCamelCase_ , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = None if token is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE : Optional[int] = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' SCREAMING_SNAKE_CASE : Any = requests.get(lowerCamelCase_ , headers=lowerCamelCase_ ).json() SCREAMING_SNAKE_CASE : Tuple = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) SCREAMING_SNAKE_CASE : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = requests.get(url + f'''&page={i + 2}''' , headers=lowerCamelCase_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def __A ( lowerCamelCase_ , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = None if token is not None: SCREAMING_SNAKE_CASE : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE : Union[str, Any] = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' SCREAMING_SNAKE_CASE : List[str] = requests.get(lowerCamelCase_ , headers=lowerCamelCase_ ).json() SCREAMING_SNAKE_CASE : Tuple = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) SCREAMING_SNAKE_CASE : str = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = requests.get(url + f'''&page={i + 2}''' , headers=lowerCamelCase_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = None if token is not None: SCREAMING_SNAKE_CASE : Optional[Any] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE : List[str] = requests.get(lowerCamelCase_ , headers=lowerCamelCase_ , allow_redirects=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = result.headers["""Location"""] SCREAMING_SNAKE_CASE : Union[str, Any] = requests.get(lowerCamelCase_ , allow_redirects=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(lowerCamelCase_ , f'''{artifact_name}.zip''' ) with open(lowerCamelCase_ , """wb""" ) as fp: fp.write(response.content ) def __A ( lowerCamelCase_ , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Union[str, Any] = [] SCREAMING_SNAKE_CASE : Tuple = None with zipfile.ZipFile(lowerCamelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCamelCase_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(lowerCamelCase_ ) as f: for line in f: SCREAMING_SNAKE_CASE : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs SCREAMING_SNAKE_CASE : Any = line[: line.index(""": """ )] SCREAMING_SNAKE_CASE : List[str] = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed SCREAMING_SNAKE_CASE : Union[str, Any] = line[len("""FAILED """ ) :] failed_tests.append(lowerCamelCase_ ) elif filename == "job_name.txt": SCREAMING_SNAKE_CASE : Any = line if len(lowerCamelCase_ ) != len(lowerCamelCase_ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(lowerCamelCase_ )} for `errors` ''' f'''and {len(lowerCamelCase_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) SCREAMING_SNAKE_CASE : Any = None if job_name and job_links: SCREAMING_SNAKE_CASE : int = job_links.get(lowerCamelCase_ , lowerCamelCase_ ) # A list with elements of the form (line of error, error, failed test) SCREAMING_SNAKE_CASE : Optional[Any] = [x + [y] + [job_link] for x, y in zip(lowerCamelCase_ , lowerCamelCase_ )] return result def __A ( lowerCamelCase_ , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[int] = [os.path.join(lowerCamelCase_ , lowerCamelCase_ ) for p in os.listdir(lowerCamelCase_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(lowerCamelCase_ , job_links=lowerCamelCase_ ) ) return errors def __A ( lowerCamelCase_ , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = Counter() counter.update([x[1] for x in logs] ) SCREAMING_SNAKE_CASE : str = counter.most_common() SCREAMING_SNAKE_CASE : Dict = {} for error, count in counts: if error_filter is None or error not in error_filter: SCREAMING_SNAKE_CASE : Optional[int] = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} SCREAMING_SNAKE_CASE : Tuple = dict(sorted(r.items() , key=lambda lowerCamelCase_ : item[1]["count"] , reverse=lowerCamelCase_ ) ) return r def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): SCREAMING_SNAKE_CASE : Union[str, Any] = test.split("""/""" )[2] else: SCREAMING_SNAKE_CASE : Any = None return test def __A ( lowerCamelCase_ , lowerCamelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [(x[0], x[1], get_model(x[2] )) for x in logs] SCREAMING_SNAKE_CASE : List[str] = [x for x in logs if x[2] is not None] SCREAMING_SNAKE_CASE : Tuple = {x[2] for x in logs} SCREAMING_SNAKE_CASE : Optional[Any] = {} for test in tests: SCREAMING_SNAKE_CASE : List[Any] = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) SCREAMING_SNAKE_CASE : Union[str, Any] = counter.most_common() SCREAMING_SNAKE_CASE : str = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} SCREAMING_SNAKE_CASE : Optional[int] = sum(error_counts.values() ) if n_errors > 0: SCREAMING_SNAKE_CASE : Any = {"""count""": n_errors, """errors""": error_counts} SCREAMING_SNAKE_CASE : Optional[Any] = dict(sorted(r.items() , key=lambda lowerCamelCase_ : item[1]["count"] , reverse=lowerCamelCase_ ) ) return r def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = """| no. | error | status |""" SCREAMING_SNAKE_CASE : Dict = """|-:|:-|:-|""" SCREAMING_SNAKE_CASE : List[Any] = [header, sep] for error in reduced_by_error: SCREAMING_SNAKE_CASE : List[Any] = reduced_by_error[error]["""count"""] SCREAMING_SNAKE_CASE : List[str] = f'''| {count} | {error[:1_00]} | |''' lines.append(lowerCamelCase_ ) return "\n".join(lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = """| model | no. of errors | major error | count |""" SCREAMING_SNAKE_CASE : Tuple = """|-:|-:|-:|-:|""" SCREAMING_SNAKE_CASE : List[Any] = [header, sep] for model in reduced_by_model: SCREAMING_SNAKE_CASE : int = reduced_by_model[model]["""count"""] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = list(reduced_by_model[model]["""errors"""].items() )[0] SCREAMING_SNAKE_CASE : Optional[int] = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(lowerCamelCase_ ) return "\n".join(lowerCamelCase_ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") __UpperCAmelCase = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) __UpperCAmelCase = get_job_links(args.workflow_run_id, token=args.token) __UpperCAmelCase = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: __UpperCAmelCase = k.find(""" / """) __UpperCAmelCase = k[index + len(""" / """) :] __UpperCAmelCase = v with open(os.path.join(args.output_dir, """job_links.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) __UpperCAmelCase = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) __UpperCAmelCase = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error __UpperCAmelCase = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors __UpperCAmelCase = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, """errors.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) __UpperCAmelCase = reduce_by_error(errors) __UpperCAmelCase = reduce_by_model(errors) __UpperCAmelCase = make_github_table(reduced_by_error) __UpperCAmelCase = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, """reduced_by_error.txt"""), """w""", encoding="""UTF-8""") as fp: fp.write(sa) with open(os.path.join(args.output_dir, """reduced_by_model.txt"""), """w""", encoding="""UTF-8""") as fp: fp.write(sa)
79
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class UpperCamelCase__ ( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase_ : str=None , **lowerCamelCase_ : Dict ): '''simple docstring''' super().__init__(features=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch_tensor_kwargs import torch # noqa import torch at initialization def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and column: if all( isinstance(lowerCamelCase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : int ): '''simple docstring''' import torch if isinstance(lowerCamelCase_ , (str, bytes, type(lowerCamelCase_ )) ): return value elif isinstance(lowerCamelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE : str = {} if isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): SCREAMING_SNAKE_CASE : Any = {"""dtype""": torch.intaa} elif isinstance(lowerCamelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE : int = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowerCamelCase_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(lowerCamelCase_ ) return torch.tensor(lowerCamelCase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(lowerCamelCase_ , """__array__""" ) and not isinstance(lowerCamelCase_ , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowerCamelCase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) elif isinstance(lowerCamelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowerCamelCase_ ) for substruct in data_struct] ) return self._tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : dict ): '''simple docstring''' return map_nested(self._recursive_tensorize , lowerCamelCase_ , map_list=lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.numpy_arrow_extractor().extract_row(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_row(lowerCamelCase_ ) return self.recursive_tensorize(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.numpy_arrow_extractor().extract_column(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.python_features_decoder.decode_column(lowerCamelCase_ , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE : List[str] = self.recursive_tensorize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self._consolidate(lowerCamelCase_ ) return column def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : pa.Table ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.numpy_arrow_extractor().extract_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.python_features_decoder.decode_batch(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.recursive_tensorize(lowerCamelCase_ ) for column_name in batch: SCREAMING_SNAKE_CASE : Tuple = self._consolidate(batch[column_name] ) return batch
79
1
'''simple docstring''' import string def __A ( lowerCamelCase_ ): """simple docstring""" for key in range(len(string.ascii_uppercase ) ): SCREAMING_SNAKE_CASE : Any = """""" for symbol in message: if symbol in string.ascii_uppercase: SCREAMING_SNAKE_CASE : List[str] = string.ascii_uppercase.find(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = num - key if num < 0: SCREAMING_SNAKE_CASE : Any = num + len(string.ascii_uppercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = translated + string.ascii_uppercase[num] else: SCREAMING_SNAKE_CASE : List[str] = translated + symbol print(f'''Decryption using Key #{key}: {translated}''' ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = input("""Encrypted message: """ ) SCREAMING_SNAKE_CASE : Union[str, Any] = message.upper() decrypt(lowerCamelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
79
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCAmelCase = random.Random() def __A ( lowerCamelCase_ , lowerCamelCase_=1.0 , lowerCamelCase_=None , lowerCamelCase_=None ): """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE : Optional[Any] = global_rng SCREAMING_SNAKE_CASE : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int]=7 , lowerCamelCase_ : Optional[int]=4_00 , lowerCamelCase_ : int=20_00 , lowerCamelCase_ : List[str]=20_48 , lowerCamelCase_ : Optional[Any]=1_28 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : Dict=30 , lowerCamelCase_ : Dict=4_41_00 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = min_seq_length SCREAMING_SNAKE_CASE : Any = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : int = spectrogram_length SCREAMING_SNAKE_CASE : List[Any] = feature_size SCREAMING_SNAKE_CASE : Any = num_audio_channels SCREAMING_SNAKE_CASE : Tuple = hop_length SCREAMING_SNAKE_CASE : str = chunk_length SCREAMING_SNAKE_CASE : Dict = sampling_rate def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : Any=False ): '''simple docstring''' def _flatten(lowerCamelCase_ : Dict ): return list(itertools.chain(*lowerCamelCase_ ) ) if equal_length: SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(lowerCamelCase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = TvltFeatureExtractor def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TvltFeatureExtractionTester(self ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase_ , """spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase_ , """sampling_rate""" ) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Any = feat_extract_first.save_pretrained(lowerCamelCase_ )[0] check_json_file_has_correct_format(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : List[Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : int = os.path.join(lowerCamelCase_ , """feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class.from_json_file(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : int = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : List[str] = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE : Optional[Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ ) ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] SCREAMING_SNAKE_CASE : int = [np.asarray(lowerCamelCase_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 , mask_audio=lowerCamelCase_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[int] = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] SCREAMING_SNAKE_CASE : int = np.asarray(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = feature_extractor(lowerCamelCase_ , return_tensors="""np""" , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Union[str, Any] = ds.sort("""id""" ).select(range(lowerCamelCase_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : Tuple = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(lowerCamelCase_ , return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_92, 1_28) ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , lowerCamelCase_ , atol=1e-4 ) )
79
1
'''simple docstring''' def __A ( lowerCamelCase_ = 60_08_51_47_51_43 ): """simple docstring""" try: SCREAMING_SNAKE_CASE : int = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Optional[int] = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE : Union[str, Any] = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE : Union[str, Any] = n return int(lowerCamelCase_ ) if __name__ == "__main__": print(f'''{solution() = }''')
79
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __UpperCAmelCase = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
1
'''simple docstring''' import json import sys def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = ["""<details>""", """<summary>Show updated benchmarks!</summary>""", """ """] for benchmark_name in sorted(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : str = results[benchmark_name] SCREAMING_SNAKE_CASE : Union[str, Any] = benchmark_name.split("""/""" )[-1] output_md.append(f'''### Benchmark: {benchmark_file_name}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = """| metric |""" SCREAMING_SNAKE_CASE : Dict = """|--------|""" SCREAMING_SNAKE_CASE : int = """| new / old (diff) |""" for metric_name in sorted(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = benchmark_res[metric_name] SCREAMING_SNAKE_CASE : Tuple = metric_vals["""new"""] SCREAMING_SNAKE_CASE : Optional[int] = metric_vals.get("""old""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = metric_vals.get("""diff""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = f''' {new_val:f}''' if isinstance(lowerCamelCase_ , (int, float) ) else """None""" if old_val is not None: val_str += f''' / {old_val:f}''' if isinstance(lowerCamelCase_ , (int, float) ) else "None" if dif_val is not None: val_str += f''' ({dif_val:f})''' if isinstance(lowerCamelCase_ , (int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append("""</details>""" ) with open(lowerCamelCase_ , """w""" , encoding="""utf-8""" ) as f: f.writelines("""\n""".join(lowerCamelCase_ ) ) if __name__ == "__main__": __UpperCAmelCase = sys.argv[1] __UpperCAmelCase = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
79
'''simple docstring''' __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
79
1
'''simple docstring''' from __future__ import annotations __UpperCAmelCase = 10 def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : str = max(lowerCamelCase_ ) while placement <= max_digit: # declare and initialize empty buckets SCREAMING_SNAKE_CASE : list[list] = [[] for _ in range(lowerCamelCase_ )] # split list_of_ints between the buckets for i in list_of_ints: SCREAMING_SNAKE_CASE : List[str] = int((i / placement) % RADIX ) buckets[tmp].append(lowerCamelCase_ ) # put each buckets' contents into list_of_ints SCREAMING_SNAKE_CASE : Dict = 0 for b in range(lowerCamelCase_ ): for i in buckets[b]: SCREAMING_SNAKE_CASE : List[str] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
79
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCAmelCase = """ Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)[\"depth\"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline(\"depth-estimation\") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to(\"cuda\") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to(\"cuda\") >>> img = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/cat.png\" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\") >>> prompt = \"A robot, 4k photo\" >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\" >>> generator = torch.Generator(device=\"cuda\").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save(\"robot_cat.png\") ``` """ def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=8 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Union[str, Any] , lowerCamelCase_ : UNetaDConditionModel , lowerCamelCase_ : DDPMScheduler , lowerCamelCase_ : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=lowerCamelCase_ , scheduler=lowerCamelCase_ , movq=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : str = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase_ ( self : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): '''simple docstring''' if latents is None: SCREAMING_SNAKE_CASE : Tuple = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ , device=lowerCamelCase_ , dtype=lowerCamelCase_ ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) SCREAMING_SNAKE_CASE : Dict = latents.to(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = latents * scheduler.init_noise_sigma return latents def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Dict=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE : List[Any] = torch.device(f'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple=0 ): '''simple docstring''' if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) SCREAMING_SNAKE_CASE : Any = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCamelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE : Union[str, Any] = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = cpu_offload_with_hook(lowerCamelCase_ , lowerCamelCase_ , prev_module_hook=lowerCamelCase_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE : str = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase_ ( self : str ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase_ , """_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() @replace_example_docstring(lowerCamelCase_ ) def __call__( self : Optional[Any] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : torch.FloatTensor , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 1_00 , lowerCamelCase_ : float = 4.0 , lowerCamelCase_ : int = 1 , lowerCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase_ : Optional[torch.FloatTensor] = None , lowerCamelCase_ : Optional[str] = "pil" , lowerCamelCase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._execution_device SCREAMING_SNAKE_CASE : Optional[int] = guidance_scale > 1.0 if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = torch.cat(lowerCamelCase_ , dim=0 ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Any = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : List[Any] = image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Optional[int] = negative_image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Dict = hint.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) self.scheduler.set_timesteps(lowerCamelCase_ , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.timesteps SCREAMING_SNAKE_CASE : Any = self.movq.config.latent_channels SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = downscale_height_and_width(lowerCamelCase_ , lowerCamelCase_ , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCamelCase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Union[str, Any] = {"""image_embeds""": image_embeds, """hint""": hint} SCREAMING_SNAKE_CASE : Dict = self.unet( sample=lowerCamelCase_ , timestep=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , added_cond_kwargs=lowerCamelCase_ , return_dict=lowerCamelCase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE : str = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : str = self.scheduler.step( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ , )[0] # post-processing SCREAMING_SNAKE_CASE : List[str] = self.movq.decode(lowerCamelCase_ , force_not_quantize=lowerCamelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE : Optional[int] = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : List[Any] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Any = self.numpy_to_pil(lowerCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase_ )
79
1
'''simple docstring''' import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: SCREAMING_SNAKE_CASE : str = 1_28 elif "12-12" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = 12 SCREAMING_SNAKE_CASE : Optional[int] = 12 elif "14-14" in model_name: SCREAMING_SNAKE_CASE : Optional[Any] = 14 SCREAMING_SNAKE_CASE : int = 14 elif "16-16" in model_name: SCREAMING_SNAKE_CASE : Optional[Any] = 16 SCREAMING_SNAKE_CASE : str = 16 else: raise ValueError("""Model not supported""" ) SCREAMING_SNAKE_CASE : List[Any] = """huggingface/label-files""" if "speech-commands" in model_name: SCREAMING_SNAKE_CASE : Tuple = 35 SCREAMING_SNAKE_CASE : List[Any] = """speech-commands-v2-id2label.json""" else: SCREAMING_SNAKE_CASE : Optional[int] = 5_27 SCREAMING_SNAKE_CASE : Tuple = """audioset-id2label.json""" SCREAMING_SNAKE_CASE : int = json.load(open(hf_hub_download(lowerCamelCase_ , lowerCamelCase_ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE : int = {int(lowerCamelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : Union[str, Any] = {v: k for k, v in idalabel.items()} return config def __A ( lowerCamelCase_ ): """simple docstring""" if "module.v" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE : int = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: SCREAMING_SNAKE_CASE : int = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: SCREAMING_SNAKE_CASE : Dict = name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: SCREAMING_SNAKE_CASE : Dict = name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Tuple = orig_state_dict.pop(lowerCamelCase_ ) if "qkv" in key: SCREAMING_SNAKE_CASE : int = key.split(""".""" ) SCREAMING_SNAKE_CASE : int = int(key_split[3] ) SCREAMING_SNAKE_CASE : int = config.hidden_size if "weight" in key: SCREAMING_SNAKE_CASE : List[str] = val[:dim, :] SCREAMING_SNAKE_CASE : Optional[Any] = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : List[str] = val[-dim:, :] else: SCREAMING_SNAKE_CASE : Dict = val[:dim] SCREAMING_SNAKE_CASE : List[str] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : List[Any] = val[-dim:] else: SCREAMING_SNAKE_CASE : Optional[int] = val return orig_state_dict def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(lowerCamelCase_ , lowerCamelCase_ ) @torch.no_grad() def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=False ): """simple docstring""" SCREAMING_SNAKE_CASE : int = get_audio_spectrogram_transformer_config(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict SCREAMING_SNAKE_CASE : Dict = model_name_to_url[model_name] SCREAMING_SNAKE_CASE : str = torch.hub.load_state_dict_from_url(lowerCamelCase_ , map_location="""cpu""" ) # remove some keys remove_keys(lowerCamelCase_ ) # rename some keys SCREAMING_SNAKE_CASE : Optional[Any] = convert_state_dict(lowerCamelCase_ , lowerCamelCase_ ) # load 🤗 model SCREAMING_SNAKE_CASE : List[str] = ASTForAudioClassification(lowerCamelCase_ ) model.eval() model.load_state_dict(lowerCamelCase_ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 SCREAMING_SNAKE_CASE : List[Any] = -4.2_677_393 if """speech-commands""" not in model_name else -6.845_978 SCREAMING_SNAKE_CASE : List[str] = 4.5_689_974 if """speech-commands""" not in model_name else 5.5_654_526 SCREAMING_SNAKE_CASE : Union[str, Any] = 10_24 if """speech-commands""" not in model_name else 1_28 SCREAMING_SNAKE_CASE : Tuple = ASTFeatureExtractor(mean=lowerCamelCase_ , std=lowerCamelCase_ , max_length=lowerCamelCase_ ) if "speech-commands" in model_name: SCREAMING_SNAKE_CASE : Dict = load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) SCREAMING_SNAKE_CASE : Tuple = dataset[0]["""audio"""]["""array"""] else: SCREAMING_SNAKE_CASE : Optional[Any] = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = torchaudio.load(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = waveform.squeeze().numpy() SCREAMING_SNAKE_CASE : Dict = feature_extractor(lowerCamelCase_ , sampling_rate=1_60_00 , return_tensors="""pt""" ) # forward pass SCREAMING_SNAKE_CASE : Any = model(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": SCREAMING_SNAKE_CASE : List[str] = torch.tensor([-1.1_986, -7.0_903, -8.2_718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-2.6_128, -8.0_080, -9.4_344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-1.5_080, -7.4_534, -8.8_917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": SCREAMING_SNAKE_CASE : Any = torch.tensor([-0.5_050, -6.5_833, -8.0_843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": SCREAMING_SNAKE_CASE : List[str] = torch.tensor([-0.3_826, -7.0_336, -8.2_413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": SCREAMING_SNAKE_CASE : int = torch.tensor([-1.2_113, -6.9_101, -8.3_470] ) elif model_name == "ast-finetuned-speech-commands-v2": SCREAMING_SNAKE_CASE : int = torch.tensor([6.1_589, -8.0_566, -8.7_984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , lowerCamelCase_ , atol=1E-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCamelCase_ ) print(f'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(lowerCamelCase_ ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f'''MIT/{model_name}''' ) feature_extractor.push_to_hub(f'''MIT/{model_name}''' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __UpperCAmelCase = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
79
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """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""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = BigBirdTokenizer SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] SCREAMING_SNAKE_CASE__ = [] def __init__( self : Any , lowerCamelCase_ : str=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict="<unk>" , lowerCamelCase_ : int="<s>" , lowerCamelCase_ : Optional[Any]="</s>" , lowerCamelCase_ : Dict="<pad>" , lowerCamelCase_ : Tuple="[SEP]" , lowerCamelCase_ : Dict="[MASK]" , lowerCamelCase_ : Union[str, Any]="[CLS]" , **lowerCamelCase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else bos_token SCREAMING_SNAKE_CASE : Dict = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else eos_token SCREAMING_SNAKE_CASE : Optional[Any] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else unk_token SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else pad_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else cls_token SCREAMING_SNAKE_CASE : Any = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : int = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Optional[Any] = False if not self.vocab_file else True def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : 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] def lowerCamelCase_ ( self : str , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' 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(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Tuple = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ): copyfile(self.vocab_file , lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ __UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ __UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ __UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ __UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): """simple docstring""" def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Union[str, Any]=[1, 10, 1_00] , lowerCamelCase_ : Optional[int]=4 , lowerCamelCase_ : Any=3.0 ): '''simple docstring''' if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""" ) with ThreadPoolExecutor(max_workers=lowerCamelCase_ ) as executor: SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[int] = Counter() SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : List[Any] = defaultdict(lowerCamelCase_ ) for task_id, (candidates, test_case) in enumerate(zip(lowerCamelCase_ , lowerCamelCase_ ) ): for candidate in candidates: SCREAMING_SNAKE_CASE : Any = candidate + """\n""" + test_case SCREAMING_SNAKE_CASE : Optional[int] = (test_program, timeout, task_id, completion_id[task_id]) SCREAMING_SNAKE_CASE : str = executor.submit(lowerCamelCase_ , *lowerCamelCase_ ) futures.append(lowerCamelCase_ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Any = future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = [], [] for result in results.values(): result.sort() SCREAMING_SNAKE_CASE : Tuple = [r[1]["""passed"""] for r in result] total.append(len(lowerCamelCase_ ) ) correct.append(sum(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Tuple = np.array(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = np.array(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = k SCREAMING_SNAKE_CASE : List[Any] = {f'''pass@{k}''': estimate_pass_at_k(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" def estimator(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : List[str] = itertools.repeat(lowerCamelCase_ , len(lowerCamelCase_ ) ) else: assert len(lowerCamelCase_ ) == len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = iter(lowerCamelCase_ ) return np.array([estimator(int(lowerCamelCase_ ) , int(lowerCamelCase_ ) , lowerCamelCase_ ) for n, c in zip(lowerCamelCase_ , lowerCamelCase_ )] )
79
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""swish""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = get_activation("""silu""" ) self.assertIsInstance(lowerCamelCase_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_activation("""mish""" ) self.assertIsInstance(lowerCamelCase_ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = get_activation("""gelu""" ) self.assertIsInstance(lowerCamelCase_ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
79
1
'''simple docstring''' def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return int(input_a == input_a == 0 ) def __A ( ): """simple docstring""" print("""Truth Table of NOR Gate:""" ) print("""| Input 1 | Input 2 | Output |""" ) print(f'''| 0 | 0 | {nor_gate(0 , 0 )} |''' ) print(f'''| 0 | 1 | {nor_gate(0 , 1 )} |''' ) print(f'''| 1 | 0 | {nor_gate(1 , 0 )} |''' ) print(f'''| 1 | 1 | {nor_gate(1 , 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
79
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''deberta-v2''' def __init__( self : int , lowerCamelCase_ : Optional[Any]=12_81_00 , lowerCamelCase_ : str=15_36 , lowerCamelCase_ : int=24 , lowerCamelCase_ : List[str]=24 , lowerCamelCase_ : List[Any]=61_44 , lowerCamelCase_ : List[Any]="gelu" , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : str=5_12 , lowerCamelCase_ : str=0 , lowerCamelCase_ : Union[str, Any]=0.02 , lowerCamelCase_ : Dict=1e-7 , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : Optional[int]=-1 , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : Dict="gelu" , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : List[Any] = relative_attention SCREAMING_SNAKE_CASE : str = max_relative_positions SCREAMING_SNAKE_CASE : int = pad_token_id SCREAMING_SNAKE_CASE : List[str] = position_biased_input # Backwards compatibility if type(lowerCamelCase_ ) == str: SCREAMING_SNAKE_CASE : Dict = [x.strip() for x in pos_att_type.lower().split("""|""" )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = kwargs.get("""pooler_hidden_size""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = pooler_dropout SCREAMING_SNAKE_CASE : Any = pooler_hidden_act class UpperCamelCase__ ( lowercase_ ): """simple docstring""" @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE : Union[str, Any] = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return 12 def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : int = -1 , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional["TensorType"] = None , lowerCamelCase_ : int = 3 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : int = 40 , lowerCamelCase_ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = super().generate_dummy_inputs(preprocessor=lowerCamelCase_ , framework=lowerCamelCase_ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
79
1
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def __A ( lowerCamelCase_="" ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = tempfile.mkdtemp() return os.path.join(lowerCamelCase_ , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = torch.rand(12 , dtype=torch.floataa ) - 0.5 SCREAMING_SNAKE_CASE : Union[str, Any] = AgentAudio(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(lowerCamelCase_ , agent_type.to_raw() , atol=1e-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(lowerCamelCase_ ) ) # Ensure that the file contains the same value as the original tensor SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = sf.read(lowerCamelCase_ ) self.assertTrue(torch.allclose(lowerCamelCase_ , torch.tensor(lowerCamelCase_ ) , atol=1e-4 ) ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = torch.rand(12 , dtype=torch.floataa ) - 0.5 SCREAMING_SNAKE_CASE : List[str] = get_new_path(suffix=""".wav""" ) sf.write(lowerCamelCase_ , lowerCamelCase_ , 1_60_00 ) SCREAMING_SNAKE_CASE : Optional[int] = AgentAudio(lowerCamelCase_ ) self.assertTrue(torch.allclose(lowerCamelCase_ , agent_type.to_raw() , atol=1e-4 ) ) self.assertEqual(agent_type.to_string() , lowerCamelCase_ ) @require_vision @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = torch.randint(0 , 2_56 , (64, 64, 3) ) SCREAMING_SNAKE_CASE : Union[str, Any] = AgentImage(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(lowerCamelCase_ , agent_type._tensor , atol=1e-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase_ ) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" SCREAMING_SNAKE_CASE : Optional[int] = Image.open(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = AgentImage(lowerCamelCase_ ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase_ ) ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" SCREAMING_SNAKE_CASE : List[str] = Image.open(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = AgentImage(lowerCamelCase_ ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase_ ) ) class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = """Hey!""" SCREAMING_SNAKE_CASE : Tuple = AgentText(lowerCamelCase_ ) self.assertEqual(lowerCamelCase_ , agent_type.to_string() ) self.assertEqual(lowerCamelCase_ , agent_type.to_raw() ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ )
79
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = {} def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: SCREAMING_SNAKE_CASE : str = [[w, v]] if not self.graph.get(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Tuple = [] def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : str ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[str, Any]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Tuple = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Any = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[int]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : str = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : Union[str, Any] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Any=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = deque() SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : int = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Optional[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [] if s == -2: SCREAMING_SNAKE_CASE : Union[str, Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : List[str] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[Any] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : int = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return sorted_nodes def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Union[str, Any] = s SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : Union[str, Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Any = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : int = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : int = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = s SCREAMING_SNAKE_CASE : List[Any] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = -2 SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Tuple = s SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : str = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Dict = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : List[str] = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = s SCREAMING_SNAKE_CASE : Optional[int] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str=-2 , lowerCamelCase_ : int=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin def lowerCamelCase_ ( self : int , lowerCamelCase_ : Tuple=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = time() return end - begin class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any]=1 ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, v]] # add the other way if self.graph.get(lowerCamelCase_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist SCREAMING_SNAKE_CASE : Any = [[w, u]] def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any ): '''simple docstring''' if self.graph.get(lowerCamelCase_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCamelCase_ ) # the other way round if self.graph.get(lowerCamelCase_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowerCamelCase_ ) def lowerCamelCase_ ( self : int , lowerCamelCase_ : str=-2 , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] if s == -2: SCREAMING_SNAKE_CASE : List[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Union[str, Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCamelCase_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : Any = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : List[str] = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return visited def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[str]=-1 ): '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE : Any = floor(random() * 1_00_00 ) + 10 for i in range(lowerCamelCase_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_02 ) + 1 ): SCREAMING_SNAKE_CASE : List[str] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCamelCase_ , lowerCamelCase_ , 1 ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[Any]=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = deque() SCREAMING_SNAKE_CASE : Tuple = [] if s == -2: SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] d.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) while d: SCREAMING_SNAKE_CASE : List[Any] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' return len(self.graph[u] ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Optional[Any] = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = -2 SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Optional[Any] = False SCREAMING_SNAKE_CASE : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : str = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Optional[int] = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : int = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Union[str, Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = s SCREAMING_SNAKE_CASE : str = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return list(lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Any = list(self.graph )[0] stack.append(lowerCamelCase_ ) visited.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = -2 SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = s SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCamelCase_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE : Any = True if len(lowerCamelCase_ ) != 0: SCREAMING_SNAKE_CASE : str = stack[len(lowerCamelCase_ ) - 1] else: SCREAMING_SNAKE_CASE : Optional[Any] = False indirect_parents.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = s SCREAMING_SNAKE_CASE : Tuple = ss # check if se have reached the starting point if len(lowerCamelCase_ ) == 0: return False def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return list(self.graph ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[str]=-2 , lowerCamelCase_ : str=-1 ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = time() self.dfs(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = time() return end - begin def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Dict=-2 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = time() self.bfs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = time() return end - begin
79
1
'''simple docstring''' from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 class UpperCamelCase__ ( lowercase_ , lowercase_ ): """simple docstring""" @register_to_config def __init__( self : Optional[int] , lowerCamelCase_ : int = 32 , lowerCamelCase_ : int = 64 , lowerCamelCase_ : int = 20 , lowerCamelCase_ : int = 7_68 , lowerCamelCase_ : Union[str, Any]=77 , lowerCamelCase_ : List[Any]=4 , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : str = "silu" , lowerCamelCase_ : Optional[str] = None , lowerCamelCase_ : Optional[str] = None , lowerCamelCase_ : Optional[str] = "linear" , lowerCamelCase_ : Optional[str] = "prd" , lowerCamelCase_ : Optional[int] = None , lowerCamelCase_ : Optional[int] = None , lowerCamelCase_ : Optional[int] = None , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = attention_head_dim SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads * attention_head_dim SCREAMING_SNAKE_CASE : Dict = additional_embeddings SCREAMING_SNAKE_CASE : int = time_embed_dim or inner_dim SCREAMING_SNAKE_CASE : Any = embedding_proj_dim or embedding_dim SCREAMING_SNAKE_CASE : Tuple = clip_embed_dim or embedding_dim SCREAMING_SNAKE_CASE : Union[str, Any] = Timesteps(lowerCamelCase_ , lowerCamelCase_ , 0 ) SCREAMING_SNAKE_CASE : List[str] = TimestepEmbedding(lowerCamelCase_ , lowerCamelCase_ , out_dim=lowerCamelCase_ , act_fn=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = nn.Linear(lowerCamelCase_ , lowerCamelCase_ ) if embedding_proj_norm_type is None: SCREAMING_SNAKE_CASE : Tuple = None elif embedding_proj_norm_type == "layer": SCREAMING_SNAKE_CASE : str = nn.LayerNorm(lowerCamelCase_ ) else: raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) SCREAMING_SNAKE_CASE : Tuple = nn.Linear(lowerCamelCase_ , lowerCamelCase_ ) if encoder_hid_proj_type is None: SCREAMING_SNAKE_CASE : Dict = None elif encoder_hid_proj_type == "linear": SCREAMING_SNAKE_CASE : int = nn.Linear(lowerCamelCase_ , lowerCamelCase_ ) else: raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , lowerCamelCase_ ) ) if added_emb_type == "prd": SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.zeros(1 , 1 , lowerCamelCase_ ) ) elif added_emb_type is None: SCREAMING_SNAKE_CASE : Any = None else: raise ValueError( f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) SCREAMING_SNAKE_CASE : List[str] = nn.ModuleList( [ BasicTransformerBlock( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , dropout=lowerCamelCase_ , activation_fn="""gelu""" , attention_bias=lowerCamelCase_ , ) for d in range(lowerCamelCase_ ) ] ) if norm_in_type == "layer": SCREAMING_SNAKE_CASE : List[str] = nn.LayerNorm(lowerCamelCase_ ) elif norm_in_type is None: SCREAMING_SNAKE_CASE : List[str] = None else: raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.''' ) SCREAMING_SNAKE_CASE : Optional[int] = nn.LayerNorm(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = nn.Linear(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10_000.0 ) causal_attention_mask.triu_(1 ) SCREAMING_SNAKE_CASE : Optional[int] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , lowerCamelCase_ , persistent=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.zeros(1 , lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.zeros(1 , lowerCamelCase_ ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = {} def fn_recursive_add_processors(lowerCamelCase_ : str , lowerCamelCase_ : torch.nn.Module , lowerCamelCase_ : Dict[str, AttentionProcessor] ): if hasattr(lowerCamelCase_ , """set_processor""" ): SCREAMING_SNAKE_CASE : Tuple = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'''{name}.{sub_name}''' , lowerCamelCase_ , lowerCamelCase_ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return processors def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = len(self.attn_processors.keys() ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(lowerCamelCase_ ) != count: raise ValueError( f'''A dict of processors was passed, but the number of processors {len(lowerCamelCase_ )} does not match the''' f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(lowerCamelCase_ : str , lowerCamelCase_ : torch.nn.Module , lowerCamelCase_ : Optional[Any] ): if hasattr(lowerCamelCase_ , """set_processor""" ): if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): module.set_processor(lowerCamelCase_ ) else: module.set_processor(processor.pop(f'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f'''{name}.{sub_name}''' , lowerCamelCase_ , lowerCamelCase_ ) for name, module in self.named_children(): fn_recursive_attn_processor(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Union[torch.Tensor, float, int] , lowerCamelCase_ : torch.FloatTensor , lowerCamelCase_ : Optional[torch.FloatTensor] = None , lowerCamelCase_ : Optional[torch.BoolTensor] = None , lowerCamelCase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = hidden_states.shape[0] SCREAMING_SNAKE_CASE : str = timestep if not torch.is_tensor(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(lowerCamelCase_ ) and len(timesteps.shape ) == 0: SCREAMING_SNAKE_CASE : Optional[Any] = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML SCREAMING_SNAKE_CASE : List[str] = timesteps * torch.ones(lowerCamelCase_ , dtype=timesteps.dtype , device=timesteps.device ) SCREAMING_SNAKE_CASE : List[str] = self.time_proj(lowerCamelCase_ ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. SCREAMING_SNAKE_CASE : Any = timesteps_projected.to(dtype=self.dtype ) SCREAMING_SNAKE_CASE : str = self.time_embedding(lowerCamelCase_ ) if self.embedding_proj_norm is not None: SCREAMING_SNAKE_CASE : Tuple = self.embedding_proj_norm(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self.embedding_proj(lowerCamelCase_ ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: SCREAMING_SNAKE_CASE : Tuple = self.encoder_hidden_states_proj(lowerCamelCase_ ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) SCREAMING_SNAKE_CASE : List[str] = self.proj_in(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.positional_embedding.to(hidden_states.dtype ) SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : Tuple = 0 if encoder_hidden_states is not None: additional_embeds.append(lowerCamelCase_ ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: SCREAMING_SNAKE_CASE : Tuple = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: SCREAMING_SNAKE_CASE : Tuple = hidden_states[:, None, :] SCREAMING_SNAKE_CASE : List[Any] = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: SCREAMING_SNAKE_CASE : Optional[int] = self.prd_embedding.to(hidden_states.dtype ).expand(lowerCamelCase_ , -1 , -1 ) additional_embeds.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat( lowerCamelCase_ , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens SCREAMING_SNAKE_CASE : Optional[int] = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: SCREAMING_SNAKE_CASE : Dict = F.pad( lowerCamelCase_ , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) SCREAMING_SNAKE_CASE : Optional[int] = hidden_states + positional_embeddings if attention_mask is not None: SCREAMING_SNAKE_CASE : Optional[int] = (1 - attention_mask.to(hidden_states.dtype )) * -10_000.0 SCREAMING_SNAKE_CASE : Union[str, Any] = F.pad(lowerCamelCase_ , (0, self.additional_embeddings) , value=0.0 ) SCREAMING_SNAKE_CASE : Dict = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) SCREAMING_SNAKE_CASE : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: SCREAMING_SNAKE_CASE : Any = self.norm_in(lowerCamelCase_ ) for block in self.transformer_blocks: SCREAMING_SNAKE_CASE : Optional[int] = block(lowerCamelCase_ , attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = self.norm_out(lowerCamelCase_ ) if self.prd_embedding is not None: SCREAMING_SNAKE_CASE : Optional[Any] = hidden_states[:, -1] else: SCREAMING_SNAKE_CASE : List[Any] = hidden_states[:, additional_embeddings_len:] SCREAMING_SNAKE_CASE : Dict = self.proj_to_clip_embeddings(lowerCamelCase_ ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
79
'''simple docstring''' import os 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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} __UpperCAmelCase = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } __UpperCAmelCase = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } __UpperCAmelCase = """▁""" class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple="<s>" , lowerCamelCase_ : Union[str, Any]="</s>" , lowerCamelCase_ : Tuple="</s>" , lowerCamelCase_ : str="<s>" , lowerCamelCase_ : Optional[int]="<unk>" , lowerCamelCase_ : List[Any]="<pad>" , lowerCamelCase_ : Optional[Any]="<mask>" , lowerCamelCase_ : Optional[Dict[str, Any]] = None , **lowerCamelCase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Dict = vocab_file SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} SCREAMING_SNAKE_CASE : str = len(self.sp_model ) - 1 SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1, 1] + ([0] * len(lowerCamelCase_ )) + [1] def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [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] @property def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return len(self.sp_model ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = {self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str ): '''simple docstring''' return self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : str ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.PieceToId(lowerCamelCase_ ) return spm_id if spm_id else self.unk_token_id def lowerCamelCase_ ( self : int , lowerCamelCase_ : List[str] ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Tuple = """""" SCREAMING_SNAKE_CASE : Dict = 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(lowerCamelCase_ ) + token SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(lowerCamelCase_ ) return out_string.strip() def __getstate__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE : List[Any] = None return state def __setstate__( self : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowerCamelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Dict = os.path.join( lowerCamelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCamelCase_ , """wb""" ) as fi: SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_ ) return (out_vocab_file,)
79
1
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __A ( *lowerCamelCase_ ): """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = list(lowerCamelCase_ ) for i in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : Union[str, Any] = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def __A ( lowerCamelCase_ = None , lowerCamelCase_ = 1_28 ): """simple docstring""" if function is None: return functools.partial(lowerCamelCase_ , starting_batch_size=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = starting_batch_size def decorator(*lowerCamelCase_ , **lowerCamelCase_ ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() SCREAMING_SNAKE_CASE : int = list(inspect.signature(lowerCamelCase_ ).parameters.keys() ) # Guard against user error if len(lowerCamelCase_ ) < (len(lowerCamelCase_ ) + 1): SCREAMING_SNAKE_CASE : str = """, """.join([f'''{arg}={value}''' for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( f'''Batch size was passed into `{function.__name__}` as the first argument when called.''' f'''Remove this as the decorator already does so: `{function.__name__}({arg_str})`''' ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ ) except Exception as e: if should_reduce_batch_size(lowerCamelCase_ ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
79
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) SCREAMING_SNAKE_CASE : Dict = { """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 ), } SCREAMING_SNAKE_CASE : List[str] = model(lowerCamelCase_ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 6, 7_68) ) self.assertEqual(output.shape , lowerCamelCase_ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
79
1
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase = logging.get_logger(__name__) def __A ( lowerCamelCase_=None , lowerCamelCase_=None ): """simple docstring""" return field(default_factory=lambda: default , metadata=lowerCamelCase_ ) @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = list_field( default=[] , metadata={ '''help''': ( '''Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version''' ''' of all available models''' ) } , ) SCREAMING_SNAKE_CASE__ = list_field( default=[8] , metadata={'''help''': '''List of batch sizes for which memory and time performance will be evaluated'''} ) SCREAMING_SNAKE_CASE__ = list_field( default=[8, 32, 128, 512] , metadata={'''help''': '''List of sequence lengths for which memory and time performance will be evaluated'''} , ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Whether to benchmark inference of model. Inference can be disabled via --no-inference.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'''} ) SCREAMING_SNAKE_CASE__ = field(default=lowercase_ , metadata={'''help''': '''Use FP16 to accelerate inference.'''} ) SCREAMING_SNAKE_CASE__ = field(default=lowercase_ , metadata={'''help''': '''Benchmark training of model'''} ) SCREAMING_SNAKE_CASE__ = field(default=lowercase_ , metadata={'''help''': '''Verbose memory tracing'''} ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={ '''help''': '''Whether to perform memory measurements. Memory measurements can be disabled via --no-memory''' } , ) SCREAMING_SNAKE_CASE__ = field(default=lowercase_ , metadata={'''help''': '''Trace memory line by line'''} ) SCREAMING_SNAKE_CASE__ = field(default=lowercase_ , metadata={'''help''': '''Save result to a CSV file'''} ) SCREAMING_SNAKE_CASE__ = field(default=lowercase_ , metadata={'''help''': '''Save all print statements in a log file'''} ) SCREAMING_SNAKE_CASE__ = field(default=lowercase_ , metadata={'''help''': '''Whether to print environment information'''} ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={ '''help''': ( '''Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use''' ''' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled''' ''' for debugging / testing and on TPU.''' ) } , ) SCREAMING_SNAKE_CASE__ = field( default=f"inference_time_{round(time() )}.csv" , metadata={'''help''': '''CSV filename used if saving time results to csv.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=f"inference_memory_{round(time() )}.csv" , metadata={'''help''': '''CSV filename used if saving memory results to csv.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=f"train_time_{round(time() )}.csv" , metadata={'''help''': '''CSV filename used if saving time results to csv for training.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=f"train_memory_{round(time() )}.csv" , metadata={'''help''': '''CSV filename used if saving memory results to csv for training.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=f"env_info_{round(time() )}.csv" , metadata={'''help''': '''CSV filename used if saving environment information.'''} , ) SCREAMING_SNAKE_CASE__ = field( default=f"log_{round(time() )}.csv" , metadata={'''help''': '''Log filename used if print statements are saved in log.'''} , ) SCREAMING_SNAKE_CASE__ = field(default=3 , metadata={'''help''': '''Times an experiment will be run.'''} ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={ '''help''': ( '''Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain''' ''' model weights.''' ) } , ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' warnings.warn( f'''The class {self.__class__} is deprecated. Hugging Face Benchmarking utils''' """ are deprecated in general and it is advised to use external Benchmarking libraries """ """ to benchmark Transformer models.""" , lowerCamelCase_ , ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' if len(self.models ) <= 0: raise ValueError( """Please make sure you provide at least one model name / model identifier, *e.g.* `--models""" """ bert-base-cased` or `args.models = ['bert-base-cased'].""" ) return self.models @property def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' if not self.multi_process: return False elif self.is_tpu: logger.info("""Multiprocessing is currently not possible on TPU.""" ) return False else: return True
79
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''Translation''' , init=lowercase_ , repr=lowercase_ ) def __call__( self : int ): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # Automatically constructed SCREAMING_SNAKE_CASE__ = "dict" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = field(default='''TranslationVariableLanguages''' , init=lowercase_ , repr=lowercase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = sorted(set(self.languages ) ) if self.languages else None SCREAMING_SNAKE_CASE : str = len(self.languages ) if self.languages else None def __call__( self : Tuple ): '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = set(self.languages ) if self.languages and set(lowerCamelCase_ ) - lang_set: raise ValueError( f'''Some languages in example ({", ".join(sorted(set(lowerCamelCase_ ) - lang_set ) )}) are not in valid set ({", ".join(lowerCamelCase_ )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE : List[Any] = [] for lang, text in translation_dict.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = zip(*sorted(lowerCamelCase_ ) ) return {"language": languages, "translation": translations} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
79
1
'''simple docstring''' import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str=0 ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 1_28, 1_28) , rng=random.Random(lowerCamelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = np.random.RandomState(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """strength""": 0.75, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Tuple = pipe(**lowerCamelCase_ ).images SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 1_28, 1_28, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) SCREAMING_SNAKE_CASE : str = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Tuple = pipe(**lowerCamelCase_ ).images SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) SCREAMING_SNAKE_CASE : int = np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) SCREAMING_SNAKE_CASE : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) # warmup pass to apply optimizations SCREAMING_SNAKE_CASE : Optional[int] = pipe(**self.get_dummy_inputs() ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Dict = pipe(**lowerCamelCase_ ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) SCREAMING_SNAKE_CASE : Tuple = np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) SCREAMING_SNAKE_CASE : Optional[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : int = pipe(**lowerCamelCase_ ).images SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) SCREAMING_SNAKE_CASE : Optional[Any] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = pipe(**lowerCamelCase_ ).images SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) SCREAMING_SNAKE_CASE : int = np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) SCREAMING_SNAKE_CASE : List[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : List[Any] = pipe(**lowerCamelCase_ ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) SCREAMING_SNAKE_CASE : Dict = np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = ort.SessionOptions() SCREAMING_SNAKE_CASE : Dict = False return options def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) SCREAMING_SNAKE_CASE : Dict = init_image.resize((7_68, 5_12) ) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE : Optional[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=lowerCamelCase_ , feature_extractor=lowerCamelCase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = """A fantasy landscape, trending on artstation""" SCREAMING_SNAKE_CASE : str = np.random.RandomState(0 ) SCREAMING_SNAKE_CASE : str = pipe( prompt=lowerCamelCase_ , image=lowerCamelCase_ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=lowerCamelCase_ , output_type="""np""" , ) SCREAMING_SNAKE_CASE : List[str] = output.images SCREAMING_SNAKE_CASE : int = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 7_68, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) SCREAMING_SNAKE_CASE : int = init_image.resize((7_68, 5_12) ) SCREAMING_SNAKE_CASE : Union[str, Any] = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) SCREAMING_SNAKE_CASE : int = OnnxStableDiffusionImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=lowerCamelCase_ , safety_checker=lowerCamelCase_ , feature_extractor=lowerCamelCase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = """A fantasy landscape, trending on artstation""" SCREAMING_SNAKE_CASE : str = np.random.RandomState(0 ) SCREAMING_SNAKE_CASE : List[str] = pipe( prompt=lowerCamelCase_ , image=lowerCamelCase_ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=lowerCamelCase_ , output_type="""np""" , ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images SCREAMING_SNAKE_CASE : Dict = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 7_68, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
79
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , *lowerCamelCase_ : List[str] , **lowerCamelCase_ : Dict ): '''simple docstring''' warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , lowerCamelCase_ , ) super().__init__(*lowerCamelCase_ , **lowerCamelCase_ )
79
1
'''simple docstring''' __UpperCAmelCase = {} def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on SCREAMING_SNAKE_CASE : Optional[int] = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one SCREAMING_SNAKE_CASE : List[Any] = _calculate(days - 1 , lowerCamelCase_ , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 SCREAMING_SNAKE_CASE : Optional[int] = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter SCREAMING_SNAKE_CASE : Any = _calculate(days - 1 , lowerCamelCase_ , 0 ) SCREAMING_SNAKE_CASE : Optional[Any] = state_late + state_absent + state_ontime SCREAMING_SNAKE_CASE : Optional[int] = prizestrings return prizestrings def __A ( lowerCamelCase_ = 30 ): """simple docstring""" return _calculate(lowerCamelCase_ , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
79
'''simple docstring''' 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 UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : str ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : int , lowerCamelCase_ : Dict ): '''simple docstring''' raise NotImplementedError def lowerCamelCase_ ( self : Optional[int] ): '''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 lowerCamelCase_ ( cls : Any ): '''simple docstring''' return f'''`pip install {cls.pip_package or cls.name}`''' class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''optuna''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_optuna_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Dict ): '''simple docstring''' return run_hp_search_optuna(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Any ): '''simple docstring''' return default_hp_space_optuna(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''ray''' SCREAMING_SNAKE_CASE__ = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_ray_available() def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_ray(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Optional[int] ): '''simple docstring''' return default_hp_space_ray(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''sigopt''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_sigopt_available() def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : int ): '''simple docstring''' return run_hp_search_sigopt(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return default_hp_space_sigopt(lowerCamelCase_ ) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''wandb''' @staticmethod def lowerCamelCase_ ( ): '''simple docstring''' return is_wandb_available() def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : str , **lowerCamelCase_ : Optional[Any] ): '''simple docstring''' return run_hp_search_wandb(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' return default_hp_space_wandb(lowerCamelCase_ ) __UpperCAmelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCamelCase_ ) > 0: SCREAMING_SNAKE_CASE : List[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() ) )
79
1
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } __UpperCAmelCase = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" for attribute in key.split(""".""" ): SCREAMING_SNAKE_CASE : Dict = getattr(lowerCamelCase_ , lowerCamelCase_ ) if weight_type is not None: SCREAMING_SNAKE_CASE : Optional[int] = getattr(lowerCamelCase_ , lowerCamelCase_ ).shape else: SCREAMING_SNAKE_CASE : Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": SCREAMING_SNAKE_CASE : Any = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE : Dict = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE : Optional[int] = value elif weight_type == "bias": SCREAMING_SNAKE_CASE : Tuple = value else: SCREAMING_SNAKE_CASE : Dict = value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : str = fairseq_model.state_dict() SCREAMING_SNAKE_CASE : Optional[Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight SCREAMING_SNAKE_CASE : Any = None for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE : int = False if "conv_layers" in name: load_conv_layer( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , hf_model.config.feat_extract_norm == """group""" , ) SCREAMING_SNAKE_CASE : int = True elif name.split(""".""" )[0] == "proj": SCREAMING_SNAKE_CASE : Union[str, Any] = fairseq_model.proj SCREAMING_SNAKE_CASE : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: SCREAMING_SNAKE_CASE : Any = True if "*" in mapped_key: SCREAMING_SNAKE_CASE : Optional[Any] = name.split(lowerCamelCase_ )[0].split(""".""" )[-2] SCREAMING_SNAKE_CASE : str = mapped_key.replace("""*""" , lowerCamelCase_ ) if "weight_g" in name: SCREAMING_SNAKE_CASE : List[str] = """weight_g""" elif "weight_v" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = """weight_v""" elif "bias" in name: SCREAMING_SNAKE_CASE : Optional[Any] = """bias""" elif "weight" in name: SCREAMING_SNAKE_CASE : str = """weight""" else: SCREAMING_SNAKE_CASE : List[Any] = None set_recursively(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) continue if not is_used: unused_weights.append(lowerCamelCase_ ) logger.warning(f'''Unused weights: {unused_weights}''' ) return proj_weight def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = full_name.split("""conv_layers.""" )[-1] SCREAMING_SNAKE_CASE : Optional[int] = name.split(""".""" ) SCREAMING_SNAKE_CASE : Tuple = int(items[0] ) SCREAMING_SNAKE_CASE : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) SCREAMING_SNAKE_CASE : Any = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE : List[str] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) SCREAMING_SNAKE_CASE : Optional[Any] = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowerCamelCase_ ) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = emb.weight.shape SCREAMING_SNAKE_CASE : Any = nn.Linear(lowerCamelCase_ , lowerCamelCase_ , bias=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = emb.weight.data return lin_layer def __A ( lowerCamelCase_ ): """simple docstring""" with open(lowerCamelCase_ , """r""" , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE : int = f.readlines() SCREAMING_SNAKE_CASE : int = [line.split(""" """ )[0] for line in lines] SCREAMING_SNAKE_CASE : List[Any] = len(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(lowerCamelCase_ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ): """simple docstring""" SCREAMING_SNAKE_CASE : str = WavaVecaConfig.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = SpeechaTextaConfig.from_pretrained( lowerCamelCase_ , vocab_size=lowerCamelCase_ , decoder_layers=lowerCamelCase_ , do_stable_layer_norm=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) SCREAMING_SNAKE_CASE : Tuple = model[0].eval() # set weights for wav2vec2 encoder SCREAMING_SNAKE_CASE : Union[str, Any] = WavaVecaModel(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = recursively_load_weights_wavaveca(model.encoder , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = SpeechaTextaForCausalLM(lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=lowerCamelCase_ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f'''The following keys are missing when loading the decoder weights: {missing_keys}''' ) logger.warning(f'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}''' ) SCREAMING_SNAKE_CASE : List[str] = SpeechEncoderDecoderModel(encoder=lowerCamelCase_ , decoder=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = False # add projection layer SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(projection_layer.weight ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(projection_layer.bias ) SCREAMING_SNAKE_CASE : List[str] = create_vocab_dict(lowerCamelCase_ ) with open(os.path.join(lowerCamelCase_ , """vocab.json""" ) , """w""" ) as fp: json.dump(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = SpeechaTextaTokenizer(os.path.join(lowerCamelCase_ , """vocab.json""" ) ) tokenizer.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = hf_wavavec.config.to_dict() SCREAMING_SNAKE_CASE : Dict = tokenizer.pad_token_id SCREAMING_SNAKE_CASE : List[str] = tokenizer.bos_token_id SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.eos_token_id SCREAMING_SNAKE_CASE : Union[str, Any] = """speech_to_text_2""" SCREAMING_SNAKE_CASE : List[Any] = """wav2vec2""" SCREAMING_SNAKE_CASE : Dict = SpeechEncoderDecoderConfig.from_dict(lowerCamelCase_ ) hf_wavavec.save_pretrained(lowerCamelCase_ ) feature_extractor.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument( """--encoder_config_path""", default="""facebook/wav2vec2-large-lv60""", type=str, help="""Path to hf encoder wav2vec2 checkpoint config""", ) parser.add_argument( """--decoder_config_path""", default="""facebook/s2t-small-mustc-en-fr-st""", type=str, help="""Path to hf decoder s2t checkpoint config""", ) parser.add_argument("""--vocab_size""", default=10224, type=int, help="""Vocab size of decoder""") parser.add_argument("""--num_decoder_layers""", default=7, type=int, help="""Number of decoder layers""") __UpperCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
79
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = """""" __UpperCAmelCase = 1 # (0 is vertical, 1 is horizontal) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = get_dataset(lowerCamelCase_ , lowerCamelCase_ ) print("""Processing...""" ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = update_image_and_anno(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for index, image in enumerate(lowerCamelCase_ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Optional[int] = random_chars(32 ) SCREAMING_SNAKE_CASE : Optional[Any] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE : Dict = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , lowerCamelCase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(lowerCamelCase_ )} with {file_name}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE : Optional[Any] = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(lowerCamelCase_ ) with open(f'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Any = [] for label_file in glob.glob(os.path.join(lowerCamelCase_ , """*.txt""" ) ): SCREAMING_SNAKE_CASE : str = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(lowerCamelCase_ ) as in_file: SCREAMING_SNAKE_CASE : Any = in_file.readlines() SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowerCamelCase_ , f'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE : Tuple = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : Union[str, Any] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(lowerCamelCase_ ) labels.append(lowerCamelCase_ ) return img_paths, labels def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [] for idx in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Dict = img_list[idx] path_list.append(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = anno_list[idx] SCREAMING_SNAKE_CASE : Optional[Any] = cva.imread(lowerCamelCase_ ) if flip_type == 1: SCREAMING_SNAKE_CASE : List[str] = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE : Any = cva.flip(lowerCamelCase_ , lowerCamelCase_ ) for bbox in img_annos: SCREAMING_SNAKE_CASE : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(lowerCamelCase_ ) new_imgs_list.append(lowerCamelCase_ ) return new_imgs_list, new_annos_lists, path_list def __A ( lowerCamelCase_ = 32 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : Dict = ascii_lowercase + digits return "".join(random.choice(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
79
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """weiweishi/roc-bert-base-zh""": """https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json""", } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''roc_bert''' def __init__( self : int , lowerCamelCase_ : str=3_05_22 , lowerCamelCase_ : List[str]=7_68 , lowerCamelCase_ : Optional[Any]=12 , lowerCamelCase_ : str=12 , lowerCamelCase_ : Dict=30_72 , lowerCamelCase_ : Dict="gelu" , lowerCamelCase_ : Tuple=0.1 , lowerCamelCase_ : Optional[int]=0.1 , lowerCamelCase_ : Union[str, Any]=5_12 , lowerCamelCase_ : int=2 , lowerCamelCase_ : Union[str, Any]=0.02 , lowerCamelCase_ : Any=1e-12 , lowerCamelCase_ : Any=True , lowerCamelCase_ : Dict=0 , lowerCamelCase_ : Union[str, Any]="absolute" , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : Union[str, Any]=True , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Optional[Any]=9_10 , lowerCamelCase_ : Optional[Any]=5_12 , lowerCamelCase_ : Optional[Any]=2_48_58 , lowerCamelCase_ : str=True , **lowerCamelCase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : List[str] = type_vocab_size SCREAMING_SNAKE_CASE : Any = layer_norm_eps SCREAMING_SNAKE_CASE : str = use_cache SCREAMING_SNAKE_CASE : Optional[int] = enable_pronunciation SCREAMING_SNAKE_CASE : Dict = enable_shape SCREAMING_SNAKE_CASE : Optional[int] = pronunciation_embed_dim SCREAMING_SNAKE_CASE : List[str] = pronunciation_vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = shape_embed_dim SCREAMING_SNAKE_CASE : Tuple = shape_vocab_size SCREAMING_SNAKE_CASE : List[str] = concat_input SCREAMING_SNAKE_CASE : Dict = position_embedding_type SCREAMING_SNAKE_CASE : List[str] = classifier_dropout super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ )
79
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''vivit''' def __init__( self : Tuple , lowerCamelCase_ : str=2_24 , lowerCamelCase_ : List[Any]=32 , lowerCamelCase_ : Tuple=[2, 16, 16] , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Dict=7_68 , lowerCamelCase_ : Dict=12 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : List[Any]=30_72 , lowerCamelCase_ : List[str]="gelu_fast" , lowerCamelCase_ : str=0.0 , lowerCamelCase_ : Any=0.0 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : List[Any]=1e-06 , lowerCamelCase_ : Tuple=True , **lowerCamelCase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Dict = num_frames SCREAMING_SNAKE_CASE : Optional[Any] = tubelet_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : int = qkv_bias super().__init__(**lowerCamelCase_ )
79
1
'''simple docstring''' 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 UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = DDIMPipeline SCREAMING_SNAKE_CASE__ = UNCONDITIONAL_IMAGE_GENERATION_PARAMS SCREAMING_SNAKE_CASE__ = PipelineTesterMixin.required_optional_params - { '''num_images_per_prompt''', '''latents''', '''callback''', '''callback_steps''', } SCREAMING_SNAKE_CASE__ = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS SCREAMING_SNAKE_CASE__ = False def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = 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""") , ) SCREAMING_SNAKE_CASE : str = DDIMScheduler() SCREAMING_SNAKE_CASE : Optional[Any] = {"""unet""": unet, """scheduler""": scheduler} return components def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str]=0 ): '''simple docstring''' if str(lowerCamelCase_ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE : int = torch.manual_seed(lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device=lowerCamelCase_ ).manual_seed(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = { """batch_size""": 1, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = """cpu""" SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = self.pipeline_class(**lowerCamelCase_ ) pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**lowerCamelCase_ ).images SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) SCREAMING_SNAKE_CASE : Optional[int] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase_ , 1e-3 ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' super().test_save_load_local(expected_max_difference=3e-3 ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=3e-3 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = """google/ddpm-cifar10-32""" SCREAMING_SNAKE_CASE : Union[str, Any] = UNetaDModel.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = DDIMScheduler() SCREAMING_SNAKE_CASE : Union[str, Any] = DDIMPipeline(unet=lowerCamelCase_ , scheduler=lowerCamelCase_ ) ddim.to(lowerCamelCase_ ) ddim.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = ddim(generator=lowerCamelCase_ , eta=0.0 , output_type="""numpy""" ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.1_723, 0.1_617, 0.1_600, 0.1_626, 0.1_497, 0.1_513, 0.1_505, 0.1_442, 0.1_453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = """google/ddpm-ema-bedroom-256""" SCREAMING_SNAKE_CASE : int = UNetaDModel.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = DDIMPipeline(unet=lowerCamelCase_ , scheduler=lowerCamelCase_ ) ddpm.to(lowerCamelCase_ ) ddpm.set_progress_bar_config(disable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = ddpm(generator=lowerCamelCase_ , output_type="""numpy""" ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.0_060, 0.0_201, 0.0_344, 0.0_024, 0.0_018, 0.0_002, 0.0_022, 0.0_000, 0.0_069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
79
'''simple docstring''' import math class UpperCamelCase__ : """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : Tuple=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' SCREAMING_SNAKE_CASE : Any = n SCREAMING_SNAKE_CASE : Optional[int] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # adjacency matrix for weight SCREAMING_SNAKE_CASE : Union[str, Any] = [ [math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ ) ] # dp[i][j] stores minimum distance from i to j def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = w def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): SCREAMING_SNAKE_CASE : Union[str, Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": __UpperCAmelCase = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
79
1