code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
def lowercase ( __A : int ) -> int: '''simple docstring''' if divisor % 5 == 0 or divisor % 2 == 0: return 0 snake_case : Tuple = 1 snake_case : Union[str, Any] = 1 while repunit: snake_case : Tuple = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def lowercase ( __A : int = 100_0000 ) -> int: '''simple docstring''' snake_case : Union[str, Any] = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(__A ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f'''{solution() = }''')
36
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Dict , __lowercase : Any , __lowercase : str=13 , __lowercase : Optional[Any]=7 , __lowercase : Tuple=True , __lowercase : Optional[int]=True , __lowercase : List[str]=True , __lowercase : Dict=True , __lowercase : Any=99 , __lowercase : Any=32 , __lowercase : List[Any]=5 , __lowercase : Any=4 , __lowercase : List[str]=37 , __lowercase : Union[str, Any]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : str=0.1 , __lowercase : List[str]=5_12 , __lowercase : Tuple=16 , __lowercase : List[str]=2 , __lowercase : Tuple=0.02 , __lowercase : Optional[Any]=False , __lowercase : Optional[int]=True , __lowercase : Union[str, Any]="None" , __lowercase : Union[str, Any]=3 , __lowercase : int=4 , __lowercase : Tuple=None , ): """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = num_choices snake_case_ = relative_attention snake_case_ = position_biased_input snake_case_ = pos_att_type snake_case_ = scope def snake_case__ ( self : str ): """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case__ ( self : Optional[int] ): """simple docstring""" return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def snake_case__ ( self : int ): """simple docstring""" snake_case_ = self.get_config() snake_case_ = 3_00 return config def snake_case__ ( self : List[Any] , __lowercase : List[Any] ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def snake_case__ ( self : List[str] , __lowercase : Tuple , __lowercase : Union[str, Any] , __lowercase : Tuple , __lowercase : Dict , __lowercase : str , __lowercase : Optional[int] , __lowercase : int ): """simple docstring""" snake_case_ = DebertaModel(config=__lowercase ) model.to(__lowercase ) model.eval() snake_case_ = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase )[0] snake_case_ = model(__lowercase , token_type_ids=__lowercase )[0] snake_case_ = model(__lowercase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def snake_case__ ( self : Any , __lowercase : Any , __lowercase : Dict , __lowercase : Any , __lowercase : Any , __lowercase : Tuple , __lowercase : Union[str, Any] , __lowercase : List[str] ): """simple docstring""" snake_case_ = DebertaForMaskedLM(config=__lowercase ) model.to(__lowercase ) model.eval() snake_case_ = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case__ ( self : List[str] , __lowercase : Tuple , __lowercase : List[str] , __lowercase : Dict , __lowercase : str , __lowercase : Optional[Any] , __lowercase : Optional[Any] , __lowercase : Union[str, Any] ): """simple docstring""" snake_case_ = self.num_labels snake_case_ = DebertaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() snake_case_ = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowercase ) def snake_case__ ( self : List[Any] , __lowercase : List[str] , __lowercase : Any , __lowercase : List[Any] , __lowercase : str , __lowercase : List[str] , __lowercase : Optional[Any] , __lowercase : Optional[int] ): """simple docstring""" snake_case_ = self.num_labels snake_case_ = DebertaForTokenClassification(config=__lowercase ) model.to(__lowercase ) model.eval() snake_case_ = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def snake_case__ ( self : List[str] , __lowercase : str , __lowercase : List[str] , __lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : Optional[Any] , __lowercase : Optional[Any] , __lowercase : Union[str, Any] ): """simple docstring""" snake_case_ = DebertaForQuestionAnswering(config=__lowercase ) model.to(__lowercase ) model.eval() snake_case_ = model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , start_positions=__lowercase , end_positions=__lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def snake_case__ ( self : Tuple ): """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase_ = ( { '''feature-extraction''': DebertaModel, '''fill-mask''': DebertaForMaskedLM, '''question-answering''': DebertaForQuestionAnswering, '''text-classification''': DebertaForSequenceClassification, '''token-classification''': DebertaForTokenClassification, '''zero-shot''': DebertaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = True lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def snake_case__ ( self : int ): """simple docstring""" snake_case_ = DebertaModelTester(self ) snake_case_ = ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def snake_case__ ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def snake_case__ ( self : Dict ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowercase ) def snake_case__ ( self : str ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowercase ) def snake_case__ ( self : str ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowercase ) def snake_case__ ( self : Optional[Any] ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowercase ) def snake_case__ ( self : Optional[Any] ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowercase ) @slow def snake_case__ ( self : str ): """simple docstring""" for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = DebertaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason="Model not available yet" ) def snake_case__ ( self : str ): """simple docstring""" pass @slow def snake_case__ ( self : Optional[int] ): """simple docstring""" snake_case_ = DebertaModel.from_pretrained("microsoft/deberta-base" ) snake_case_ = torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] ) snake_case_ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case_ = model(__lowercase , attention_mask=__lowercase )[0] # compare the actual values for a slice. snake_case_ = torch.tensor( [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowercase , atol=1E-4 ) , f"{output[:, 1:4, 1:4]}" )
376
0
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def lowerCamelCase__ ( snake_case_ : List[Any] ) -> List[str]: __snake_case = args.pruning_method __snake_case = args.threshold __snake_case = args.model_name_or_path.rstrip('''/''' ) __snake_case = args.target_model_path print(f"""Load fine-pruned model from {model_name_or_path}""" ) __snake_case = torch.load(os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) __snake_case = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __snake_case = tensor print(f"""Copied layer {name}""" ) elif "classifier" in name or "qa_output" in name: __snake_case = tensor print(f"""Copied layer {name}""" ) elif "bias" in name: __snake_case = tensor print(f"""Copied layer {name}""" ) else: if pruning_method == "magnitude": __snake_case = MagnitudeBinarizer.apply(inputs=lowercase_ , threshold=lowercase_ ) __snake_case = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "topK": if "mask_scores" in name: continue __snake_case = name[:-6] __snake_case = model[f"""{prefix_}mask_scores"""] __snake_case = TopKBinarizer.apply(lowercase_ , lowercase_ ) __snake_case = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __snake_case = name[:-6] __snake_case = model[f"""{prefix_}mask_scores"""] __snake_case = ThresholdBinarizer.apply(lowercase_ , lowercase_ , lowercase_ ) __snake_case = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "l0": if "mask_scores" in name: continue __snake_case = name[:-6] __snake_case = model[f"""{prefix_}mask_scores"""] __snake_case = -0.1, 1.1 __snake_case = torch.sigmoid(lowercase_ ) __snake_case = s * (r - l) + l __snake_case = s_bar.clamp(min=0.0 , max=1.0 ) __snake_case = tensor * mask print(f"""Pruned layer {name}""" ) else: raise ValueError('''Unknown pruning method''' ) if target_model_path is None: __snake_case = os.path.join( os.path.dirname(lowercase_ ) , f"""bertarized_{os.path.basename(lowercase_ )}""" ) if not os.path.isdir(lowercase_ ): shutil.copytree(lowercase_ , lowercase_ ) print(f"""\nCreated folder {target_model_path}""" ) torch.save(lowercase_ , os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) print('''\nPruned model saved! See you later!''' ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) snake_case_ = parser.parse_args() main(args)
707
import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'nvidia/segformer-b0-finetuned-ade-512-512': ( 'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): A_ : str = 'segformer' def __init__(self : List[Any] , a__ : int=3 , a__ : Optional[Any]=4 , a__ : Any=[2, 2, 2, 2] , a__ : Union[str, Any]=[8, 4, 2, 1] , a__ : str=[32, 64, 160, 256] , a__ : Optional[Any]=[7, 3, 3, 3] , a__ : Tuple=[4, 2, 2, 2] , a__ : Tuple=[1, 2, 5, 8] , a__ : List[Any]=[4, 4, 4, 4] , a__ : Dict="gelu" , a__ : Union[str, Any]=0.0 , a__ : List[str]=0.0 , a__ : Dict=0.1 , a__ : Any=0.0_2 , a__ : Optional[int]=0.1 , a__ : Tuple=1E-6 , a__ : Any=256 , a__ : Optional[Any]=255 , **a__ : Optional[Any] , ): """simple docstring""" super().__init__(**a__ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( '''Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be''' ''' removed, as the behaviour will default to that of reshape_last_stage = True.''' , a__ , ) __snake_case = num_channels __snake_case = num_encoder_blocks __snake_case = depths __snake_case = sr_ratios __snake_case = hidden_sizes __snake_case = patch_sizes __snake_case = strides __snake_case = mlp_ratios __snake_case = num_attention_heads __snake_case = hidden_act __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = classifier_dropout_prob __snake_case = initializer_range __snake_case = drop_path_rate __snake_case = layer_norm_eps __snake_case = decoder_hidden_size __snake_case = kwargs.get('''reshape_last_stage''' , a__ ) __snake_case = semantic_loss_ignore_index class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): A_ : Dict = version.parse('1.11' ) @property def a (self : List[str] ): """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def a (self : Tuple ): """simple docstring""" return 1E-4 @property def a (self : int ): """simple docstring""" return 12
388
0
import warnings from functools import wraps from typing import Callable def __lowerCAmelCase ( A_ : Callable ) -> Callable: @wraps(A_ ) def _inner_fn(*A_ : List[Any] , **A_ : Union[str, Any] ): warnings.warn( (F'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , A_ , ) return fn(*A_ , **A_ ) return _inner_fn
221
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def __lowerCAmelCase ( A_ : Union[str, Any] , A_ : Optional[Any]=10 ) -> Optional[int]: __UpperCAmelCase = [] for _ in range(A_ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def __lowerCAmelCase ( A_ : str , A_ : List[Any]=10 ) -> List[Any]: __UpperCAmelCase = [] for step in range(A_ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: __UpperCAmelCase = os.path.join(A_ , "schedule.bin" ) torch.save(scheduler.state_dict() , A_ ) __UpperCAmelCase = torch.load(A_ ) scheduler.load_state_dict(A_ ) return lrs @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self: List[str] , __lowerCAmelCase: List[str] , __lowerCAmelCase: Optional[Any] , __lowerCAmelCase: Dict ) -> str: '''simple docstring''' self.assertEqual(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) for a, b in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertAlmostEqual(__lowerCAmelCase , __lowerCAmelCase , delta=__lowerCAmelCase ) def _UpperCAmelCase ( self: Optional[int] ) -> str: '''simple docstring''' __UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=__lowerCAmelCase ) __UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) __UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping __UpperCAmelCase = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(100 ): __UpperCAmelCase = criterion(__lowerCAmelCase , __lowerCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def _UpperCAmelCase ( self: Optional[int] ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=__lowerCAmelCase ) __UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) __UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping __UpperCAmelCase = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=__lowerCAmelCase , weight_decay=0.0 , relative_step=__lowerCAmelCase , scale_parameter=__lowerCAmelCase , warmup_init=__lowerCAmelCase , ) for _ in range(1_000 ): __UpperCAmelCase = criterion(__lowerCAmelCase , __lowerCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ : Tuple = nn.Linear(50 , 50 ) if is_torch_available() else None lowerCAmelCase__ : Optional[int] = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None lowerCAmelCase__ : Optional[int] = 10 def _UpperCAmelCase ( self: Optional[int] , __lowerCAmelCase: List[str] , __lowerCAmelCase: Any , __lowerCAmelCase: List[Any] , __lowerCAmelCase: int=None ) -> List[Any]: '''simple docstring''' self.assertEqual(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) for a, b in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertAlmostEqual(__lowerCAmelCase , __lowerCAmelCase , delta=__lowerCAmelCase , msg=__lowerCAmelCase ) def _UpperCAmelCase ( self: Union[str, Any] ) -> Any: '''simple docstring''' __UpperCAmelCase = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) __UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): __UpperCAmelCase , __UpperCAmelCase = data __UpperCAmelCase = scheduler_func(self.optimizer , **__lowerCAmelCase ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) __UpperCAmelCase = unwrap_schedule(__lowerCAmelCase , self.num_steps ) self.assertListAlmostEqual( __lowerCAmelCase , __lowerCAmelCase , tol=1E-2 , msg=F'''failed for {scheduler_func} in normal scheduler''' , ) __UpperCAmelCase = scheduler_func(self.optimizer , **__lowerCAmelCase ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(__lowerCAmelCase ) # wrap to test picklability of the schedule __UpperCAmelCase = unwrap_and_save_reload_schedule(__lowerCAmelCase , self.num_steps ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase , msg=F'''failed for {scheduler_func} in save and reload''' ) class UpperCAmelCase__ : """simple docstring""" def __init__( self: Union[str, Any] , __lowerCAmelCase: Tuple ) -> List[Any]: '''simple docstring''' __UpperCAmelCase = fn def __call__( self: int , *__lowerCAmelCase: List[str] , **__lowerCAmelCase: Any ) -> List[Any]: '''simple docstring''' return self.fn(*__lowerCAmelCase , **__lowerCAmelCase ) @classmethod def _UpperCAmelCase ( self: Optional[Any] , __lowerCAmelCase: List[Any] ) -> List[str]: '''simple docstring''' __UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
221
1
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _lowercase (a_ , unittest.TestCase ): '''simple docstring''' lowercase__ = TransfoXLTokenizer lowercase__ = False lowercase__ = False def _lowerCamelCase ( self ): '''simple docstring''' super().setUp() UpperCamelCase_ = [ "<unk>", "[CLS]", "[SEP]", "want", "unwanted", "wa", "un", "running", ",", "low", "l", ] UpperCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _lowerCamelCase ( self , **snake_case__ ): '''simple docstring''' UpperCamelCase_ = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **snake_case__ ) def _lowerCamelCase ( self , snake_case__ ): '''simple docstring''' UpperCamelCase_ = "<unk> UNwanted , running" UpperCamelCase_ = "<unk> unwanted, running" return input_text, output_text def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=snake_case__ ) UpperCamelCase_ = tokenizer.tokenize("<unk> UNwanted , running" ) self.assertListEqual(snake_case__ , ["<unk>", "unwanted", ",", "running"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) , [0, 4, 8, 7] ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = TransfoXLTokenizer(lower_case=snake_case__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo ! how \n Are yoU ? " ) , ["hello", "!", "how", "are", "you", "?"] ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = TransfoXLTokenizer(lower_case=snake_case__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo ! how \n Are yoU ? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = TransfoXLTokenizer(lower_case=snake_case__ ) UpperCamelCase_ = "Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?" UpperCamelCase_ = [ "Hello", "(", "bracket", ")", "and", "side", "@-@", "scrolled", "[", "and", "]", "Henry", "'s", "$", "5", "@,@", "000", "with", "3", "@.@", "34", "m", ".", "What", "'s", "up", "!", "?", ] self.assertListEqual(tokenizer.tokenize(snake_case__ ) , snake_case__ ) self.assertEqual(tokenizer.convert_tokens_to_string(snake_case__ ) , snake_case__ ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = self.get_tokenizer() UpperCamelCase_ = len(snake_case__ ) tokenizer.add_tokens(["new1", "new2"] ) tokenizer.move_added_token("new1" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(snake_case__ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("new1" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , "new1" )
504
import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib UpperCAmelCase : int =threading.Lock() UpperCAmelCase : Optional[logging.Handler] =None UpperCAmelCase : List[Any] ={ """debug""": logging.DEBUG, """info""": logging.INFO, """warning""": logging.WARNING, """error""": logging.ERROR, """critical""": logging.CRITICAL, } UpperCAmelCase : Any =logging.WARNING UpperCAmelCase : List[Any] =True def _lowerCAmelCase (): UpperCamelCase_ = os.getenv("TRANSFORMERS_VERBOSITY" , _lowerCAmelCase) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f"""Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, """ f"""has to be one of: { ', '.join(log_levels.keys()) }""") return _default_log_level def _lowerCAmelCase (): return __name__.split(".")[0] def _lowerCAmelCase (): return logging.getLogger(_get_library_name()) def _lowerCAmelCase (): global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return UpperCamelCase_ = logging.StreamHandler() # Set sys.stderr as stream. UpperCamelCase_ = sys.stderr.flush # Apply our default configuration to the library root logger. UpperCamelCase_ = _get_library_root_logger() library_root_logger.addHandler(_default_handler) library_root_logger.setLevel(_get_default_logging_level()) UpperCamelCase_ = False def _lowerCAmelCase (): global _default_handler with _lock: if not _default_handler: return UpperCamelCase_ = _get_library_root_logger() library_root_logger.removeHandler(_default_handler) library_root_logger.setLevel(logging.NOTSET) UpperCamelCase_ = None def _lowerCAmelCase (): return log_levels def _lowerCAmelCase (_lowerCAmelCase = None): if name is None: UpperCamelCase_ = _get_library_name() _configure_library_root_logger() return logging.getLogger(_lowerCAmelCase) def _lowerCAmelCase (): _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def _lowerCAmelCase (_lowerCAmelCase): _configure_library_root_logger() _get_library_root_logger().setLevel(_lowerCAmelCase) def _lowerCAmelCase (): return set_verbosity(_lowerCAmelCase) def _lowerCAmelCase (): return set_verbosity(_lowerCAmelCase) def _lowerCAmelCase (): return set_verbosity(_lowerCAmelCase) def _lowerCAmelCase (): return set_verbosity(_lowerCAmelCase) def _lowerCAmelCase (): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler) def _lowerCAmelCase (): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler) def _lowerCAmelCase (_lowerCAmelCase): _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(_lowerCAmelCase) def _lowerCAmelCase (_lowerCAmelCase): _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(_lowerCAmelCase) def _lowerCAmelCase (): _configure_library_root_logger() UpperCamelCase_ = False def _lowerCAmelCase (): _configure_library_root_logger() UpperCamelCase_ = True def _lowerCAmelCase (): UpperCamelCase_ = _get_library_root_logger().handlers for handler in handlers: UpperCamelCase_ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s") handler.setFormatter(_lowerCAmelCase) def _lowerCAmelCase (): UpperCamelCase_ = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(_lowerCAmelCase) def _lowerCAmelCase (self , *_lowerCAmelCase , **_lowerCAmelCase): UpperCamelCase_ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , _lowerCAmelCase) if no_advisory_warnings: return self.warning(*_lowerCAmelCase , **_lowerCAmelCase) UpperCAmelCase : Dict =warning_advice @functools.lru_cache(_lowerCAmelCase) def _lowerCAmelCase (self , *_lowerCAmelCase , **_lowerCAmelCase): self.warning(*_lowerCAmelCase , **_lowerCAmelCase) UpperCAmelCase : Optional[Any] =warning_once class _lowercase : '''simple docstring''' def __init__( self , *snake_case__ , **snake_case__ ): # pylint: disable=unused-argument '''simple docstring''' UpperCamelCase_ = args[0] if args else None def __iter__( self ): '''simple docstring''' return iter(self._iterator ) def __getattr__( self , snake_case__ ): '''simple docstring''' def empty_fn(*snake_case__ , **snake_case__ ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ): '''simple docstring''' return self def __exit__( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' return class _lowercase : '''simple docstring''' def __call__( self , *snake_case__ , **snake_case__ ): '''simple docstring''' if _tqdm_active: return tqdm_lib.tqdm(*snake_case__ , **snake_case__ ) else: return EmptyTqdm(*snake_case__ , **snake_case__ ) def _lowerCamelCase ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' UpperCamelCase_ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*snake_case__ , **snake_case__ ) def _lowerCamelCase ( self ): '''simple docstring''' if _tqdm_active: return tqdm_lib.tqdm.get_lock() UpperCAmelCase : Tuple =_tqdm_cls() def _lowerCAmelCase (): global _tqdm_active return bool(_tqdm_active) def _lowerCAmelCase (): global _tqdm_active UpperCamelCase_ = True hf_hub_utils.enable_progress_bars() def _lowerCAmelCase (): global _tqdm_active UpperCamelCase_ = False hf_hub_utils.disable_progress_bars()
504
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'gpt_neox_japanese' def __init__( self : Any , a_ : Optional[int]=3_2000 , a_ : List[Any]=2560 , a_ : Any=32 , a_ : Union[str, Any]=32 , a_ : Any=4 , a_ : List[Any]="gelu" , a_ : Optional[int]=1.00 , a_ : int=1_0000 , a_ : Optional[int]=2048 , a_ : str=0.02 , a_ : Any=1e-5 , a_ : Dict=True , a_ : Tuple=3_1996 , a_ : Any=3_1999 , a_ : str=0.1 , a_ : Optional[int]=0.0 , **a_ : List[Any] , )-> List[str]: """simple docstring""" super().__init__(bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_multiple_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : int = rotary_pct SCREAMING_SNAKE_CASE__ : Tuple = rotary_emb_base SCREAMING_SNAKE_CASE__ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = use_cache SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : int = hidden_dropout
85
"""simple docstring""" from __future__ import annotations def __UpperCAmelCase ( __UpperCamelCase = 4 ): __lowercase : Dict = abs(__UpperCamelCase ) or 4 return [[1 + x + y * row_size for x in range(__UpperCamelCase )] for y in range(__UpperCamelCase )] def __UpperCAmelCase ( __UpperCamelCase ): return reverse_row(transpose(__UpperCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def __UpperCAmelCase ( __UpperCamelCase ): return reverse_row(reverse_column(__UpperCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def __UpperCAmelCase ( __UpperCamelCase ): return reverse_column(transpose(__UpperCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Dict = [list(__UpperCamelCase ) for x in zip(*__UpperCamelCase )] return matrix def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Union[str, Any] = matrix[::-1] return matrix def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Dict = [x[::-1] for x in matrix] return matrix def __UpperCAmelCase ( __UpperCamelCase ): for i in matrix: print(*__UpperCamelCase ) if __name__ == "__main__": a_ = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 90 counterclockwise:\n') print_matrix(rotate_aa(matrix)) a_ = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 180:\n') print_matrix(rotate_aaa(matrix)) a_ = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 270 counterclockwise:\n') print_matrix(rotate_aaa(matrix))
76
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all BART models at https://huggingface.co/models?filter=bart __A = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, } __A = { "facebook/bart-base": 10_24, "facebook/bart-large": 10_24, "facebook/bart-large-mnli": 10_24, "facebook/bart-large-cnn": 10_24, "facebook/bart-large-xsum": 10_24, "yjernite/bart_eli5": 10_24, } @lru_cache() def lowerCamelCase_ ( ) -> str: """simple docstring""" __lowerCamelCase = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) __lowerCamelCase = bs[:] __lowerCamelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(UpperCamelCase__ ) cs.append(2**8 + n ) n += 1 __lowerCamelCase = [chr(UpperCamelCase__ ) for n in cs] return dict(zip(UpperCamelCase__ , UpperCamelCase__ ) ) def lowerCamelCase_ ( UpperCamelCase__ : Tuple ) -> Optional[Any]: """simple docstring""" __lowerCamelCase = set() __lowerCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCamelCase = char return pairs class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ['''input_ids''', '''attention_mask'''] def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__="replace" , lowerCamelCase__="<s>" , lowerCamelCase__="</s>" , lowerCamelCase__="</s>" , lowerCamelCase__="<s>" , lowerCamelCase__="<unk>" , lowerCamelCase__="<pad>" , lowerCamelCase__="<mask>" , lowerCamelCase__=False , **lowerCamelCase__ , ) -> str: '''simple docstring''' __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else bos_token __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else eos_token __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else sep_token __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else cls_token __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else unk_token __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else mask_token super().__init__( errors=lowerCamelCase__ , bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , add_prefix_space=lowerCamelCase__ , **lowerCamelCase__ , ) with open(lowerCamelCase__ , encoding='utf-8' ) as vocab_handle: __lowerCamelCase = json.load(lowerCamelCase__ ) __lowerCamelCase = {v: k for k, v in self.encoder.items()} __lowerCamelCase = errors # how to handle errors in decoding __lowerCamelCase = bytes_to_unicode() __lowerCamelCase = {v: k for k, v in self.byte_encoder.items()} with open(lowerCamelCase__ , encoding='utf-8' ) as merges_handle: __lowerCamelCase = merges_handle.read().split('\n' )[1:-1] __lowerCamelCase = [tuple(merge.split() ) for merge in bpe_merges] __lowerCamelCase = dict(zip(lowerCamelCase__ , range(len(lowerCamelCase__ ) ) ) ) __lowerCamelCase = {} __lowerCamelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __lowerCamelCase = re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def lowercase_ ( self ) -> List[Any]: '''simple docstring''' return len(self.encoder ) def lowercase_ ( self ) -> str: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def lowercase_ ( self , lowerCamelCase__ ) -> Dict: '''simple docstring''' if token in self.cache: return self.cache[token] __lowerCamelCase = tuple(lowerCamelCase__ ) __lowerCamelCase = get_pairs(lowerCamelCase__ ) if not pairs: return token while True: __lowerCamelCase = min(lowerCamelCase__ , key=lambda lowerCamelCase__ : self.bpe_ranks.get(lowerCamelCase__ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break __lowerCamelCase , __lowerCamelCase = bigram __lowerCamelCase = [] __lowerCamelCase = 0 while i < len(lowerCamelCase__ ): try: __lowerCamelCase = word.index(lowerCamelCase__ , lowerCamelCase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowerCamelCase = 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 __lowerCamelCase = tuple(lowerCamelCase__ ) __lowerCamelCase = new_word if len(lowerCamelCase__ ) == 1: break else: __lowerCamelCase = get_pairs(lowerCamelCase__ ) __lowerCamelCase = ' '.join(lowerCamelCase__ ) __lowerCamelCase = word return word def lowercase_ ( self , lowerCamelCase__ ) -> Tuple: '''simple docstring''' __lowerCamelCase = [] for token in re.findall(self.pat , lowerCamelCase__ ): __lowerCamelCase = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase__ ).split(' ' ) ) return bpe_tokens def lowercase_ ( self , lowerCamelCase__ ) -> List[Any]: '''simple docstring''' return self.encoder.get(lowerCamelCase__ , self.encoder.get(self.unk_token ) ) def lowercase_ ( self , lowerCamelCase__ ) -> Dict: '''simple docstring''' return self.decoder.get(lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ ) -> Dict: '''simple docstring''' __lowerCamelCase = ''.join(lowerCamelCase__ ) __lowerCamelCase = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowerCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( lowerCamelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase = 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' ) __lowerCamelCase = 0 with open(lowerCamelCase__ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda lowerCamelCase__ : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) __lowerCamelCase = token_index writer.write(' '.join(lowerCamelCase__ ) + '\n' ) index += 1 return vocab_file, merge_file def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = False ) -> List[int]: '''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 lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> List[int]: '''simple docstring''' __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__=False , **lowerCamelCase__ ) -> Tuple: '''simple docstring''' __lowerCamelCase = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(lowerCamelCase__ ) > 0 and not text[0].isspace()): __lowerCamelCase = ' ' + text return (text, kwargs)
167
def lowerCamelCase_ ( UpperCamelCase__ : int ) -> int: """simple docstring""" assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), F"""The input value of [n={number}] is not an integer""" if number == 1: return 2 elif number < 1: __lowerCamelCase = F"""The input value of [n={number}] has to be > 0""" raise ValueError(UpperCamelCase__ ) else: __lowerCamelCase = sylvester(number - 1 ) __lowerCamelCase = num - 1 __lowerCamelCase = num return lower * upper + 1 if __name__ == "__main__": print(f'''The 8th number in Sylvester\'s sequence: {sylvester(8)}''')
167
1
"""simple docstring""" from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , ) -> Any: _lowerCamelCase : Dict = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : Optional[Any] = image_size _lowerCamelCase : Any = num_channels _lowerCamelCase : Any = embeddings_size _lowerCamelCase : Optional[int] = hidden_sizes _lowerCamelCase : Tuple = depths _lowerCamelCase : List[Any] = is_training _lowerCamelCase : int = use_labels _lowerCamelCase : str = hidden_act _lowerCamelCase : Dict = num_labels _lowerCamelCase : int = scope _lowerCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _lowerCamelCase : Dict = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_labels) _lowerCamelCase : Tuple = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self) -> Dict: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : Optional[int] = TFRegNetModel(config=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : List[str] = TFRegNetForImageClassification(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[int] = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = config_and_inputs _lowerCamelCase : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : str = TFRegNetModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: return @unittest.skip(reason="""RegNet does not use inputs_embeds""") def UpperCamelCase_ ( self) -> List[str]: pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""")) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def UpperCamelCase_ ( self) -> List[str]: super().test_keras_fit() @unittest.skip(reason="""RegNet does not support input and output embeddings""") def UpperCamelCase_ ( self) -> Optional[Any]: pass def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : int = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) , training=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowerCamelCase : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE) , expected_num_stages + 1) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : Any = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: _lowerCamelCase : Union[str, Any] = layer_type _lowerCamelCase : List[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCamelCase : Tuple = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase , _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE={}): _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE).to_tuple() def recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): if isinstance(SCREAMING_SNAKE_CASE , (List, Tuple)): for tuple_iterable_value, dict_iterable_value in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) , msg=( """Tuple and dict output are not equal. Difference:""" F' {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}' ) , ) recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) for model_class in self.all_model_classes: _lowerCamelCase : Tuple = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True}) _lowerCamelCase : int = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True}) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : List[str] = TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def _snake_case ( ): """simple docstring""" _lowerCamelCase : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> Any: return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) _lowerCamelCase : Optional[int] = self.default_image_processor _lowerCamelCase : int = prepare_img() _lowerCamelCase : List[Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""tf""") # forward pass _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) # verify the logits _lowerCamelCase : Tuple = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tf.constant([-0.41_80, -1.50_51, -3.48_36]) tf.debugging.assert_near(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4)
88
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCamelCase = { "configuration_convnext": ["CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvNextConfig", "ConvNextOnnxConfig"] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ["ConvNextFeatureExtractor"] UpperCamelCase = ["ConvNextImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ "CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ "TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure)
66
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE__ ( snake_case__ , snake_case__ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase = StableDiffusionPanoramaPipeline _lowerCamelCase = TEXT_TO_IMAGE_PARAMS _lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS _lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase ( self : int ) -> str: """simple docstring""" torch.manual_seed(0 ) _UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _UpperCAmelCase = DDIMScheduler() torch.manual_seed(0 ) _UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) _UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _UpperCAmelCase = CLIPTextModel(_A ) _UpperCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _UpperCAmelCase = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def lowerCamelCase ( self : Tuple , lowerCamelCase : Tuple , lowerCamelCase : str=0 ) -> int: """simple docstring""" _UpperCAmelCase = torch.manual_seed(_A ) _UpperCAmelCase = { 'prompt': 'a photo of the dolomites', 'generator': generator, # Setting height and width to None to prevent OOMs on CPU. 'height': None, 'width': None, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def lowerCamelCase ( self : Any ) -> int: """simple docstring""" _UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCAmelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCAmelCase = self.get_dummy_inputs(_A ) _UpperCAmelCase = sd_pipe(**_A ).images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCamelCase ( self : int ) -> Optional[Any]: """simple docstring""" super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def lowerCamelCase ( self : str ) -> str: """simple docstring""" _UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCAmelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCAmelCase = self.get_dummy_inputs(_A ) _UpperCAmelCase = 'french fries' _UpperCAmelCase = sd_pipe(**_A , negative_prompt=_A ) _UpperCAmelCase = output.images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase ( self : str ) -> Tuple: """simple docstring""" _UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCAmelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCAmelCase = self.get_dummy_inputs(_A ) _UpperCAmelCase = sd_pipe(**_A , view_batch_size=2 ) _UpperCAmelCase = output.images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase ( self : Optional[Any] ) -> Any: """simple docstring""" _UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" ) _UpperCAmelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCAmelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCAmelCase = self.get_dummy_inputs(_A ) _UpperCAmelCase = sd_pipe(**_A ).images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" _UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = PNDMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , skip_prk_steps=_A ) _UpperCAmelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCAmelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCAmelCase = self.get_dummy_inputs(_A ) _UpperCAmelCase = sd_pipe(**_A ).images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : Any ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self : str , lowerCamelCase : Tuple=0 ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = torch.manual_seed(_A ) _UpperCAmelCase = { 'prompt': 'a photo of the dolomites', 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def lowerCamelCase ( self : Union[str, Any] ) -> str: """simple docstring""" _UpperCAmelCase = 'stabilityai/stable-diffusion-2-base' _UpperCAmelCase = DDIMScheduler.from_pretrained(_A , subfolder="""scheduler""" ) _UpperCAmelCase = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() _UpperCAmelCase = self.get_inputs() _UpperCAmelCase = pipe(**_A ).images _UpperCAmelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _UpperCAmelCase = np.array( [ 0.3696_8392, 0.2702_5372, 0.3244_6766, 0.2837_9387, 0.3636_3274, 0.3073_3347, 0.2710_0027, 0.2705_4125, 0.2553_6096, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def lowerCamelCase ( self : List[Any] ) -> List[str]: """simple docstring""" _UpperCAmelCase = StableDiffusionPanoramaPipeline.from_pretrained( """stabilityai/stable-diffusion-2-base""" , safety_checker=_A ) _UpperCAmelCase = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() _UpperCAmelCase = self.get_inputs() _UpperCAmelCase = pipe(**_A ).images _UpperCAmelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _UpperCAmelCase = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCamelCase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = 0 def callback_fn(lowerCamelCase : Union[str, Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[Any] ) -> None: _UpperCAmelCase = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _UpperCAmelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _UpperCAmelCase = latents[0, -3:, -3:, -1] _UpperCAmelCase = np.array( [ 0.1868_1869, 0.3390_7816, 0.536_1276, 0.1443_2865, -0.0285_6611, -0.7394_1123, 0.2339_7987, 0.4732_2682, -0.3782_3164, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: _UpperCAmelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _UpperCAmelCase = latents[0, -3:, -3:, -1] _UpperCAmelCase = np.array( [ 0.1853_9645, 0.3398_7248, 0.537_8559, 0.1443_7142, -0.0245_5261, -0.733_8317, 0.2399_0755, 0.4735_6272, -0.378_6505, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 _UpperCAmelCase = False _UpperCAmelCase = 'stabilityai/stable-diffusion-2-base' _UpperCAmelCase = DDIMScheduler.from_pretrained(_A , subfolder="""scheduler""" ) _UpperCAmelCase = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) _UpperCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() _UpperCAmelCase = self.get_inputs() pipe(**_A , callback=_A , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowerCamelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _UpperCAmelCase = 'stabilityai/stable-diffusion-2-base' _UpperCAmelCase = DDIMScheduler.from_pretrained(_A , subfolder="""scheduler""" ) _UpperCAmelCase = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) _UpperCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _UpperCAmelCase = self.get_inputs() _UpperCAmelCase = pipe(**_A ) _UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
711
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> list[int]: _UpperCAmelCase = [0 for i in range(len(__snake_case ) )] # initialize interval's left pointer and right pointer _UpperCAmelCase , _UpperCAmelCase = 0, 0 for i in range(1 , len(__snake_case ) ): # case when current index is inside the interval if i <= right_pointer: _UpperCAmelCase = min(right_pointer - i + 1 , z_result[i - left_pointer] ) _UpperCAmelCase = min_edge while go_next(__snake_case , __snake_case , __snake_case ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: _UpperCAmelCase , _UpperCAmelCase = i, i + z_result[i] - 1 return z_result def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> bool: return i + z_result[i] < len(__snake_case ) and s[z_result[i]] == s[i + z_result[i]] def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> int: _UpperCAmelCase = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string _UpperCAmelCase = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(__snake_case ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
402
0
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def a__ ( A__ ): # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def a__ ( ): with parallel_backend('spark' ): assert ParallelBackendConfig.backend_name == "spark" SCREAMING_SNAKE_CASE_ : Tuple = [1, 2, 3] with pytest.raises(lowerCAmelCase_ ): with parallel_backend('unsupported backend' ): map_nested(lowerCAmelCase_, lowerCAmelCase_, num_proc=2 ) with pytest.raises(lowerCAmelCase_ ): with parallel_backend('unsupported backend' ): map_nested(lowerCAmelCase_, lowerCAmelCase_, num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('num_proc', [2, -1] ) def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = [1, 2] SCREAMING_SNAKE_CASE_ : Any = {"a": 1, "b": 2} SCREAMING_SNAKE_CASE_ : List[Any] = {"a": [1, 2], "b": [3, 4]} SCREAMING_SNAKE_CASE_ : Any = {"a": {"1": 1}, "b": 2} SCREAMING_SNAKE_CASE_ : Tuple = {"a": 1, "b": 2, "c": 3, "d": 4} SCREAMING_SNAKE_CASE_ : Any = [2, 3] SCREAMING_SNAKE_CASE_ : str = {"a": 2, "b": 3} SCREAMING_SNAKE_CASE_ : str = {"a": [2, 3], "b": [4, 5]} SCREAMING_SNAKE_CASE_ : Union[str, Any] = {"a": {"1": 2}, "b": 3} SCREAMING_SNAKE_CASE_ : Optional[int] = {"a": 2, "b": 3, "c": 4, "d": 5} with parallel_backend('spark' ): assert map_nested(lowerCAmelCase_, lowerCAmelCase_, num_proc=lowerCAmelCase_ ) == expected_map_nested_sa assert map_nested(lowerCAmelCase_, lowerCAmelCase_, num_proc=lowerCAmelCase_ ) == expected_map_nested_sa assert map_nested(lowerCAmelCase_, lowerCAmelCase_, num_proc=lowerCAmelCase_ ) == expected_map_nested_sa assert map_nested(lowerCAmelCase_, lowerCAmelCase_, num_proc=lowerCAmelCase_ ) == expected_map_nested_sa assert map_nested(lowerCAmelCase_, lowerCAmelCase_, num_proc=lowerCAmelCase_ ) == expected_map_nested_sa
101
import math def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): snake_case_ : Any = [] snake_case_ : List[str] = 2 snake_case_ : Optional[int] = int(math.sqrt(lowerCAmelCase_ ) ) # Size of every segment snake_case_ : str = [True] * (end + 1) snake_case_ : Any = [] while start <= end: if temp[start] is True: in_prime.append(lowerCAmelCase_ ) for i in range(start * start , end + 1 , lowerCAmelCase_ ): snake_case_ : Union[str, Any] = False start += 1 prime += in_prime snake_case_ : Dict = end + 1 snake_case_ : Dict = min(2 * end , lowerCAmelCase_ ) while low <= n: snake_case_ : Any = [True] * (high - low + 1) for each in in_prime: snake_case_ : Optional[Any] = math.floor(low / each ) * each if t < low: t += each for j in range(lowerCAmelCase_ , high + 1 , lowerCAmelCase_ ): snake_case_ : List[Any] = False for j in range(len(lowerCAmelCase_ ) ): if temp[j] is True: prime.append(j + low ) snake_case_ : int = high + 1 snake_case_ : Union[str, Any] = min(high + end , lowerCAmelCase_ ) return prime print(sieve(1_0**6))
666
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class __snake_case ( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase_ = XGLMTokenizer UpperCamelCase_ = XGLMTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = True def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase_ : Dict = XGLMTokenizer(lowerCAmelCase__ ,keep_accents=lowerCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' lowerCAmelCase_ : Union[str, Any] = "<pad>" lowerCAmelCase_ : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ) ,lowerCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ) ,lowerCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> str: '''simple docstring''' lowerCAmelCase_ : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,"<s>" ) self.assertEqual(vocab_keys[1] ,"<pad>" ) self.assertEqual(len(lowerCAmelCase__ ) ,10_08 ) def UpperCAmelCase_ ( self : Any ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size ,10_08 ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ : str = XGLMTokenizer(lowerCAmelCase__ ,keep_accents=lowerCAmelCase__ ) lowerCAmelCase_ : Optional[int] = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowerCAmelCase__ ,["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) ,[value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] ,) lowerCAmelCase_ : Union[str, Any] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowerCAmelCase__ ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] ,) lowerCAmelCase_ : Any = tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ ,[ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] ,) lowerCAmelCase_ : Optional[Any] = tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] ,) @cached_property def UpperCAmelCase_ ( self : int ) -> List[Any]: '''simple docstring''' return XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) def UpperCAmelCase_ ( self : Optional[int] ) -> Any: '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCAmelCase__ ,f.name ) lowerCAmelCase_ : str = XGLMTokenizer(f.name ,keep_accents=lowerCAmelCase__ ) lowerCAmelCase_ : Union[str, Any] = pickle.dumps(lowerCAmelCase__ ) pickle.loads(lowerCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase_ : int = self.get_tokenizer() lowerCAmelCase_ : List[Any] = self.get_rust_tokenizer() lowerCAmelCase_ : Tuple = "I was born in 92000, and this is falsé." lowerCAmelCase_ : Dict = tokenizer.tokenize(lowerCAmelCase__ ) lowerCAmelCase_ : Tuple = rust_tokenizer.tokenize(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ ) lowerCAmelCase_ : List[Any] = tokenizer.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ) lowerCAmelCase_ : Optional[Any] = rust_tokenizer.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ ) lowerCAmelCase_ : Optional[Any] = self.get_rust_tokenizer() lowerCAmelCase_ : Optional[int] = tokenizer.encode(lowerCAmelCase__ ) lowerCAmelCase_ : Optional[Any] = rust_tokenizer.encode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ ) @slow def UpperCAmelCase_ ( self : str ) -> int: '''simple docstring''' lowerCAmelCase_ : List[str] = "Hello World!" lowerCAmelCase_ : Tuple = [2, 3_12_27, 44_47, 35] self.assertListEqual(lowerCAmelCase__ ,self.big_tokenizer.encode(lowerCAmelCase__ ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> int: '''simple docstring''' lowerCAmelCase_ : Union[str, Any] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth" ) # fmt: off lowerCAmelCase_ : Dict = [2, 10_18, 67, 11, 19_88, 26_17, 56_31, 2_78, 11, 34_07, 48, 7_16_30, 2_80_85, 4, 32_34, 1_57, 13, 6, 5, 6, 4, 35_26, 7_68, 15, 6_59, 57, 2_98, 39_83, 8_64, 1_29, 21, 6, 5, 1_36_75, 3_77, 6_52, 75_80, 1_03_41, 1_55, 28_17, 4_22, 16_66, 7, 16_74, 53, 1_13, 20_22_77, 1_78_92, 33, 60, 87, 4, 32_34, 1_57, 61, 26_67, 5_23_76, 19, 88, 23, 7_35] # fmt: on self.assertListEqual(lowerCAmelCase__ ,self.big_tokenizer.encode(lowerCAmelCase__ ) ) @slow def UpperCAmelCase_ ( self : Tuple ) -> str: '''simple docstring''' lowerCAmelCase_ : Union[str, Any] = { "input_ids": [[2, 10_88_25, 11_63, 15, 8_80_10, 4_73, 1_58_98, 1_57, 1_36_72, 18_57, 3_12, 8, 23_80_21, 11_63, 53, 1_36_72, 18_57, 3_12, 8, 5_32_83, 18_23_96, 8, 1_85_66, 16, 3_67_33, 41_01, 8, 2_30, 24_40_17, 12_25_53, 7, 15, 13_25_97, 4, 2_93, 1_25_11, 76_10, 4, 34_14, 13_25_97, 9, 4, 3_23_61, 3_62, 4, 7_34, 2_85_12, 3_25_69, 18, 4, 3_23_61, 2_60_96, 1_49_82, 73, 1_87_15, 2_14_33, 23_52_61, 15, 4_92, 1_24_27, 16, 53, 1_87_15, 2_14_33, 6_54_54, 15, 2_36_59, 5_63, 16, 2_78, 5_97, 28_43, 5_95, 79_31, 18_23_96, 6_41_86, 22, 8_86, 5_95, 13_29_81, 53, 2_55_40, 34_49, 4_39_82, 3_99_01, 59_51, 8_78, 3_30, 4, 2_76_94, 8_02_69, 3_12, 53, 65_17, 1_17_80, 6_11, 2_04_08, 5], [2, 6, 13_25_97, 67, 4_28_97, 33, 5_92, 8, 16_37_29, 2_55_40, 3_61, 13_69_97, 10_95_14, 17_32_30, 7, 5_01, 60, 10_29_13, 1_96, 56_31, 2_35, 6_32_43, 4_73, 6, 23_17_57, 74, 52_77, 79_05, 53, 30_95, 3_73_17, 22, 4_54, 18_38_74, 5], [2, 2_68, 3_12_98, 4_65_30, 6, 13_29_35, 4_38_31, 7, 5_97, 32, 24, 36_88, 98_65, 5]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase__ ,model_name="facebook/xglm-564M" ,padding=lowerCAmelCase__ ,)
715
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer _lowercase = logging.get_logger(__name__) _lowercase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowercase = [ '''small''', '''small-base''', '''medium''', '''medium-base''', '''intermediate''', '''intermediate-base''', '''large''', '''large-base''', '''xlarge''', '''xlarge-base''', ] _lowercase = { '''vocab_file''': { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt''', '''funnel-transformer/small-base''': '''https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt''', '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt''', '''funnel-transformer/medium-base''': ( '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt''' ), '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt''', '''funnel-transformer/large-base''': '''https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt''', '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt''', '''funnel-transformer/xlarge-base''': ( '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json''', '''funnel-transformer/small-base''': ( '''https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json''', '''funnel-transformer/medium-base''': ( '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json''', '''funnel-transformer/large-base''': ( '''https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json''', '''funnel-transformer/xlarge-base''': ( '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json''' ), }, } _lowercase = {f"funnel-transformer/{name}": 512 for name in _model_names} _lowercase = {f"funnel-transformer/{name}": {'''do_lower_case''': True} for name in _model_names} class __snake_case ( snake_case__ ): """simple docstring""" UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ = FunnelTokenizer UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = 2 def __init__( self : Optional[Any] ,lowerCAmelCase__ : Any=None ,lowerCAmelCase__ : Optional[int]=None ,lowerCAmelCase__ : Optional[Any]=True ,lowerCAmelCase__ : List[str]="<unk>" ,lowerCAmelCase__ : int="<sep>" ,lowerCAmelCase__ : Union[str, Any]="<pad>" ,lowerCAmelCase__ : List[str]="<cls>" ,lowerCAmelCase__ : Optional[int]="<mask>" ,lowerCAmelCase__ : Union[str, Any]="<s>" ,lowerCAmelCase__ : List[str]="</s>" ,lowerCAmelCase__ : Optional[int]=True ,lowerCAmelCase__ : Tuple=True ,lowerCAmelCase__ : Any=None ,lowerCAmelCase__ : List[Any]="##" ,**lowerCAmelCase__ : int ,) -> List[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__ ,bos_token=lowerCAmelCase__ ,eos_token=lowerCAmelCase__ ,clean_text=lowerCAmelCase__ ,tokenize_chinese_chars=lowerCAmelCase__ ,strip_accents=lowerCAmelCase__ ,wordpieces_prefix=lowerCAmelCase__ ,**lowerCAmelCase__ ,) lowerCAmelCase_ : str = 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 ): lowerCAmelCase_ : Optional[int] = getattr(lowerCAmelCase__ ,normalizer_state.pop("type" ) ) lowerCAmelCase_ : List[Any] = do_lower_case lowerCAmelCase_ : List[str] = strip_accents lowerCAmelCase_ : Any = tokenize_chinese_chars lowerCAmelCase_ : List[Any] = normalizer_class(**lowerCAmelCase__ ) lowerCAmelCase_ : int = do_lower_case def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : int ,lowerCAmelCase__ : str=None ) -> List[Any]: '''simple docstring''' lowerCAmelCase_ : Union[str, 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 UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' lowerCAmelCase_ : str = [self.sep_token_id] lowerCAmelCase_ : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' lowerCAmelCase_ : str = self._tokenizer.model.save(lowerCAmelCase__ ,name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
683
0
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = AutoencoderKL __UpperCAmelCase : Optional[Any] = "sample" __UpperCAmelCase : Optional[int] = 1e-2 @property def __snake_case ( self : Dict ) -> Optional[Any]: __snake_case : Optional[Any] = 4 __snake_case : Tuple = 3 __snake_case : List[str] = (32, 32) __snake_case : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase ) return {"sample": image} @property def __snake_case ( self : Union[str, Any] ) -> Tuple: return (3, 32, 32) @property def __snake_case ( self : int ) -> int: return (3, 32, 32) def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Optional[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __snake_case : Any = self.dummy_input return init_dict, inputs_dict def __snake_case ( self : str ) -> Dict: pass def __snake_case ( self : Tuple ) -> List[str]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def __snake_case ( self : Any ) -> Optional[Any]: # enable deterministic behavior for gradient checkpointing __snake_case , __snake_case : int = self.prepare_init_args_and_inputs_for_common() __snake_case : str = self.model_class(**lowerCamelCase ) model.to(lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training __snake_case : str = model(**lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __snake_case : Any = torch.randn_like(lowerCamelCase ) __snake_case : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case : Optional[int] = self.model_class(**lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case : int = model_a(**lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __snake_case : Union[str, Any] = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case : Optional[int] = dict(model.named_parameters() ) __snake_case : List[Any] = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case , __snake_case : Optional[Any] = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowerCamelCase ) __snake_case : Optional[Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __snake_case ( self : Optional[Any] ) -> Union[str, Any]: __snake_case : Tuple = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __snake_case : Dict = model.to(lowerCamelCase ) model.eval() if torch_device == "mps": __snake_case : int = torch.manual_seed(0 ) else: __snake_case : str = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : List[str] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case : Union[str, Any] = image.to(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample __snake_case : List[Any] = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __snake_case : Union[str, Any] = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __snake_case : Tuple = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: __snake_case : List[str] = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1E-2 ) ) @slow class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : int , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] ) -> List[str]: return F'gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy' def __snake_case ( self : List[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Tuple , lowerCamelCase : List[Any]=0 , lowerCamelCase : Tuple=(4, 3, 512, 512) , lowerCamelCase : Optional[int]=False ) -> str: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa __snake_case : Tuple = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase ) return image def __snake_case ( self : Optional[Any] , lowerCamelCase : int="CompVis/stable-diffusion-v1-4" , lowerCamelCase : int=False ) -> int: __snake_case : str = "fp16" if fpaa else None __snake_case : int = torch.floataa if fpaa else torch.floataa __snake_case : int = AutoencoderKL.from_pretrained( lowerCamelCase , subfolder="vae" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , ) model.to(lowerCamelCase ).eval() return model def __snake_case ( self : str , lowerCamelCase : int=0 ) -> Optional[Any]: if torch_device == "mps": return torch.manual_seed(lowerCamelCase ) return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] ) -> List[Any]: __snake_case : Optional[Any] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) __snake_case : Tuple = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : List[Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : int = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : Any , lowerCamelCase : List[str] , lowerCamelCase : List[str] ) -> Tuple: __snake_case : Any = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Any = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Any , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) with torch.no_grad(): __snake_case : int = model(lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Union[str, Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : List[str] = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : List[str] , lowerCamelCase : Tuple , lowerCamelCase : Any ) -> Optional[Any]: __snake_case : List[str] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : str = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case : Optional[int] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : str , lowerCamelCase : Optional[int] , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[str] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : Union[str, Any] = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Optional[Any] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> Tuple: __snake_case : Dict = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : Any = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Any = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : List[Any] , lowerCamelCase : Any ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : Union[str, Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : List[Any] = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Dict = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : int = self.get_sd_image(lowerCamelCase ) __snake_case : int = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model.encode(lowerCamelCase ).latent_dist __snake_case : Dict = dist.sample(generator=lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case : List[str] = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case : Dict = torch.tensor(lowerCamelCase ) __snake_case : Dict = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
81
from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING a_ : str = logging.get_logger(__name__) @add_end_docstrings(_lowercase ) class __UpperCamelCase ( _lowercase ): """simple docstring""" def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> int: super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) self.check_model_type(SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> Union[str, Any]: a__ , a__ = {}, {} if padding is not None: a__ = padding if truncation is not None: a__ = truncation if top_k is not None: a__ = top_k return preprocess_params, {}, postprocess_params def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE ) -> Optional[int]: if isinstance(SCREAMING_SNAKE_CASE , (Image.Image, str) ) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ = {'''image''': image, '''question''': question} else: a__ = image a__ = super().__call__(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) return results def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False ) -> Dict: a__ = load_image(inputs['''image'''] ) a__ = self.tokenizer( inputs['''question'''] , return_tensors=self.framework , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE ) a__ = self.image_processor(images=SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(SCREAMING_SNAKE_CASE ) return model_inputs def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: a__ = self.model(**SCREAMING_SNAKE_CASE ) return model_outputs def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=5 ) -> Optional[Any]: if top_k > self.model.config.num_labels: a__ = self.model.config.num_labels if self.framework == "pt": a__ = model_outputs.logits.sigmoid()[0] a__ , a__ = probs.topk(SCREAMING_SNAKE_CASE ) else: raise ValueError(f"Unsupported framework: {self.framework}" ) a__ = scores.tolist() a__ = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )]
194
0
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class lowercase ( __lowerCamelCase): __lowerCAmelCase : Union[List[PIL.Image.Image], np.ndarray] __lowerCAmelCase : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class lowercase ( __lowerCamelCase): __lowerCAmelCase : np.ndarray __lowerCAmelCase : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
707
"""simple docstring""" import random from .binary_exp_mod import bin_exp_mod def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase=1000 ): """simple docstring""" if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd A_ : List[Any] = n - 1 A_ : Dict = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) A_ : Optional[Any] = 0 while count < prec: A_ : Optional[int] = random.randint(2 , n - 1 ) A_ : Any = bin_exp_mod(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if b != 1: A_ : Dict = True for _ in range(_UpperCAmelCase ): if b == n - 1: A_ : Optional[int] = False break A_ : Any = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": _lowerCamelCase : List[str] = 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)))
361
0
"""simple docstring""" import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class __UpperCAmelCase ( _a, _a ): '''simple docstring''' @register_to_config def __init__( self , _A = 1_2_8 , _A = 2_5_6 , _A = 2000.0 , _A = 7_6_8 , _A = 1_2 , _A = 1_2 , _A = 6_4 , _A = 2_0_4_8 , _A = 0.1 , ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Sequential( nn.Linear(__lowerCAmelCase , d_model * 4 , bias=__lowerCAmelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__lowerCAmelCase ) , nn.SiLU() , ) _SCREAMING_SNAKE_CASE =nn.Embedding(__lowerCAmelCase , __lowerCAmelCase ) _SCREAMING_SNAKE_CASE =False _SCREAMING_SNAKE_CASE =nn.Linear(__lowerCAmelCase , __lowerCAmelCase , bias=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Dropout(p=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.ModuleList() for lyr_num in range(__lowerCAmelCase ): # FiLM conditional T5 decoder _SCREAMING_SNAKE_CASE =DecoderLayer(d_model=__lowerCAmelCase , d_kv=__lowerCAmelCase , num_heads=__lowerCAmelCase , d_ff=__lowerCAmelCase , dropout_rate=__lowerCAmelCase ) self.decoders.append(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =TaLayerNorm(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Dropout(p=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Linear(__lowerCAmelCase , __lowerCAmelCase , bias=__lowerCAmelCase ) def UpperCamelCase_ ( self , _A , _A ): '''simple docstring''' _SCREAMING_SNAKE_CASE =torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def UpperCamelCase_ ( self , _A , _A , _A ): '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _SCREAMING_SNAKE_CASE =get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) _SCREAMING_SNAKE_CASE =self.conditioning_emb(__lowerCAmelCase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _SCREAMING_SNAKE_CASE =decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _SCREAMING_SNAKE_CASE =torch.broadcast_to( torch.arange(__lowerCAmelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) _SCREAMING_SNAKE_CASE =self.position_encoding(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =self.continuous_inputs_projection(__lowerCAmelCase ) inputs += position_encodings _SCREAMING_SNAKE_CASE =self.dropout(__lowerCAmelCase ) # decoder: No padding present. _SCREAMING_SNAKE_CASE =torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. _SCREAMING_SNAKE_CASE =[(x, self.encoder_decoder_mask(__lowerCAmelCase , __lowerCAmelCase )) for x, y in encodings_and_masks] # cross attend style: concat encodings _SCREAMING_SNAKE_CASE =torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) _SCREAMING_SNAKE_CASE =torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: _SCREAMING_SNAKE_CASE =lyr( __lowerCAmelCase , conditioning_emb=__lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , encoder_attention_mask=__lowerCAmelCase , )[0] _SCREAMING_SNAKE_CASE =self.decoder_norm(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =self.post_dropout(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =self.spec_out(__lowerCAmelCase ) return spec_out class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _A , _A , _A , _A , _A , _A=1E-6 ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=__lowerCAmelCase , d_kv=__lowerCAmelCase , num_heads=__lowerCAmelCase , dropout_rate=__lowerCAmelCase ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=__lowerCAmelCase , d_kv=__lowerCAmelCase , num_heads=__lowerCAmelCase , dropout_rate=__lowerCAmelCase , layer_norm_epsilon=__lowerCAmelCase , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=__lowerCAmelCase , d_ff=__lowerCAmelCase , dropout_rate=__lowerCAmelCase , layer_norm_epsilon=__lowerCAmelCase ) ) def UpperCamelCase_ ( self , _A , _A=None , _A=None , _A=None , _A=None , _A=None , ): '''simple docstring''' _SCREAMING_SNAKE_CASE =self.layer[0]( __lowerCAmelCase , conditioning_emb=__lowerCAmelCase , attention_mask=__lowerCAmelCase , ) if encoder_hidden_states is not None: _SCREAMING_SNAKE_CASE =torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) _SCREAMING_SNAKE_CASE =self.layer[1]( __lowerCAmelCase , key_value_states=__lowerCAmelCase , attention_mask=__lowerCAmelCase , ) # Apply Film Conditional Feed Forward layer _SCREAMING_SNAKE_CASE =self.layer[-1](__lowerCAmelCase , __lowerCAmelCase ) return (hidden_states,) class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _A , _A , _A , _A ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =TaLayerNorm(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =Attention(query_dim=__lowerCAmelCase , heads=__lowerCAmelCase , dim_head=__lowerCAmelCase , out_bias=__lowerCAmelCase , scale_qk=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Dropout(__lowerCAmelCase ) def UpperCamelCase_ ( self , _A , _A=None , _A=None , ): '''simple docstring''' _SCREAMING_SNAKE_CASE =self.layer_norm(__lowerCAmelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE =self.FiLMLayer(__lowerCAmelCase , __lowerCAmelCase ) # Self-attention block _SCREAMING_SNAKE_CASE =self.attention(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =hidden_states + self.dropout(__lowerCAmelCase ) return hidden_states class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _A , _A , _A , _A , _A ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =Attention(query_dim=__lowerCAmelCase , heads=__lowerCAmelCase , dim_head=__lowerCAmelCase , out_bias=__lowerCAmelCase , scale_qk=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =TaLayerNorm(__lowerCAmelCase , eps=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Dropout(__lowerCAmelCase ) def UpperCamelCase_ ( self , _A , _A=None , _A=None , ): '''simple docstring''' _SCREAMING_SNAKE_CASE =self.layer_norm(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =self.attention( __lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , attention_mask=attention_mask.squeeze(1 ) , ) _SCREAMING_SNAKE_CASE =hidden_states + self.dropout(__lowerCAmelCase ) return layer_output class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _A , _A , _A , _A ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =TaDenseGatedActDense(d_model=__lowerCAmelCase , d_ff=__lowerCAmelCase , dropout_rate=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =TaLayerNorm(__lowerCAmelCase , eps=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Dropout(__lowerCAmelCase ) def UpperCamelCase_ ( self , _A , _A=None ): '''simple docstring''' _SCREAMING_SNAKE_CASE =self.layer_norm(__lowerCAmelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE =self.film(__lowerCAmelCase , __lowerCAmelCase ) _SCREAMING_SNAKE_CASE =self.DenseReluDense(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =hidden_states + self.dropout(__lowerCAmelCase ) return hidden_states class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _A , _A , _A ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Linear(__lowerCAmelCase , __lowerCAmelCase , bias=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Linear(__lowerCAmelCase , __lowerCAmelCase , bias=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Linear(__lowerCAmelCase , __lowerCAmelCase , bias=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =nn.Dropout(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =NewGELUActivation() def UpperCamelCase_ ( self , _A ): '''simple docstring''' _SCREAMING_SNAKE_CASE =self.act(self.wi_a(__lowerCAmelCase ) ) _SCREAMING_SNAKE_CASE =self.wi_a(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =hidden_gelu * hidden_linear _SCREAMING_SNAKE_CASE =self.dropout(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =self.wo(__lowerCAmelCase ) return hidden_states class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _A , _A=1E-6 ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Parameter(torch.ones(__lowerCAmelCase ) ) _SCREAMING_SNAKE_CASE =eps def UpperCamelCase_ ( self , _A ): '''simple docstring''' _SCREAMING_SNAKE_CASE =hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE =hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _SCREAMING_SNAKE_CASE =hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def UpperCamelCase_ ( self , _A ): '''simple docstring''' return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044715 * torch.pow(__lowerCAmelCase , 3.0 )) )) class __UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _A , _A ): '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Linear(__lowerCAmelCase , out_features * 2 , bias=__lowerCAmelCase ) def UpperCamelCase_ ( self , _A , _A ): '''simple docstring''' _SCREAMING_SNAKE_CASE =self.scale_bias(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =torch.chunk(__lowerCAmelCase , 2 , -1 ) _SCREAMING_SNAKE_CASE =x * (1 + scale) + shift return x
255
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case : List[str] = VQModel snake_case : Dict = """sample""" @property def _lowerCamelCase ( self , __lowerCAmelCase=(32, 32) ): UpperCamelCase__ = 4 UpperCamelCase__ = 3 UpperCamelCase__ = floats_tensor((batch_size, num_channels) + sizes ).to(__lowerCAmelCase ) return {"sample": image} @property def _lowerCamelCase ( self ): return (3, 32, 32) @property def _lowerCamelCase ( self ): return (3, 32, 32) def _lowerCamelCase ( self ): UpperCamelCase__ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } UpperCamelCase__ = self.dummy_input return init_dict, inputs_dict def _lowerCamelCase ( self ): pass def _lowerCamelCase ( self ): pass def _lowerCamelCase ( self ): UpperCamelCase__ , UpperCamelCase__ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(__lowerCAmelCase ) UpperCamelCase__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowerCamelCase ( self ): UpperCamelCase__ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(__lowerCAmelCase ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) UpperCamelCase__ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) UpperCamelCase__ = image.to(__lowerCAmelCase ) with torch.no_grad(): UpperCamelCase__ = model(__lowerCAmelCase ).sample UpperCamelCase__ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off UpperCamelCase__ = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) )
619
0
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging A : Any = '''\ ''' A : int = ''' Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity ''' A : Any = ''' Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to \'cuda\' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] >>> results = perplexity.compute(model_id=\'gpt2\', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 78.22 >>> print(round(results["perplexities"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = datasets.load_dataset("wikitext", ... "wikitext-2-raw-v1", ... split="test")["text"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=\'\'] >>> results = perplexity.compute(model_id=\'gpt2\', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 60.35 >>> print(round(results["perplexities"][0], 2)) 81.12 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A (datasets.Metric ): '''simple docstring''' def a_ ( self : Union[str, Any] ) -> Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """input_texts""": datasets.Value("""string""" ), } ) , reference_urls=["""https://huggingface.co/docs/transformers/perplexity"""] , ) def a_ ( self : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : int = 16 , __lowerCAmelCase : bool = True , __lowerCAmelCase : List[Any]=None ) -> Dict: """simple docstring""" if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": A__ = """cuda""" else: A__ = """cuda""" if torch.cuda.is_available() else """cpu""" A__ = AutoModelForCausalLM.from_pretrained(__lowerCAmelCase ) A__ = model.to(__lowerCAmelCase ) A__ = AutoTokenizer.from_pretrained(__lowerCAmelCase ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: A__ = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(__lowerCAmelCase ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"""pad_token""": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" A__ = model.config.max_length - 1 else: A__ = model.config.max_length A__ = tokenizer( __lowerCAmelCase , add_special_tokens=__lowerCAmelCase , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase , return_tensors="""pt""" , return_attention_mask=__lowerCAmelCase , ).to(__lowerCAmelCase ) A__ = encodings["""input_ids"""] A__ = encodings["""attention_mask"""] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." A__ = [] A__ = CrossEntropyLoss(reduction="""none""" ) for start_index in logging.tqdm(range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ): A__ = min(start_index + batch_size , len(__lowerCAmelCase ) ) A__ = encoded_texts[start_index:end_index] A__ = attn_masks[start_index:end_index] if add_start_token: A__ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(__lowerCAmelCase ) A__ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) A__ = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(__lowerCAmelCase ), attn_mask] , dim=1 ) A__ = encoded_batch with torch.no_grad(): A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase ).logits A__ = out_logits[..., :-1, :].contiguous() A__ = labels[..., 1:].contiguous() A__ = attn_mask[..., 1:].contiguous() A__ = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , __lowerCAmelCase ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(__lowerCAmelCase )}
247
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets A : Dict = datasets.logging.get_logger(__name__) A : Optional[Any] = '''\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric", author = "Moosavi, Nafise Sadat and Strube, Michael", booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)", month = aug, year = "2016", address = "Berlin, Germany", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/P16-1060", doi = "10.18653/v1/P16-1060", pages = "632--642", } ''' A : int = '''\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. ''' A : Union[str, Any] = ''' Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting \'keep_singletons=False\', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs. min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: \'mentions\': mentions \'muc\': MUC metric [Vilain et al, 1995] \'bcub\': B-cubed [Bagga and Baldwin, 1998] \'ceafe\': CEAFe [Luo et al., 2005] \'lea\': LEA [Moosavi and Strube, 2016] \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric(\'coval\') >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\', ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\', ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\', ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\', ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\', ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0} ''' def __lowerCamelCase ( __a :Dict , __a :int , __a :int=False , __a :Optional[Any]=False , __a :int=True , __a :Optional[int]=False , __a :Dict="dummy_doc" ) -> Any: """simple docstring""" A__ = {doc: key_lines} A__ = {doc: sys_lines} A__ = {} A__ = 0 A__ = 0 A__ = 0 A__ = 0 A__ = 0 A__ = 0 A__ , A__ = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: A__ = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) A__ , A__ = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: A__ = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: A__ , A__ = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters A__ , A__ = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters A__ = reader.get_mention_assignments(__a , __a ) A__ = reader.get_mention_assignments(__a , __a ) A__ = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( """Number of removed nested coreferring mentions in the key """ F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( """Number of resulting singleton clusters in the key """ F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' """files, respectively""" ) return doc_coref_infos def __lowerCamelCase ( __a :Any , __a :Union[str, Any] , __a :List[str] , __a :Dict , __a :str , __a :Tuple , __a :Union[str, Any] ) -> Optional[int]: """simple docstring""" A__ = get_coref_infos(__a , __a , __a , __a , __a , __a ) A__ = {} A__ = 0 A__ = 0 for name, metric in metrics: A__ , A__ , A__ = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(1_0 ) , F'Recall: {recall * 1_0_0:.2f}' , F' Precision: {precision * 1_0_0:.2f}' , F' F1: {fa * 1_0_0:.2f}' , ) if conll_subparts_num == 3: A__ = (conll / 3) * 1_0_0 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({"""conll_score""": conll} ) return output_scores def __lowerCamelCase ( __a :int ) -> List[Any]: """simple docstring""" A__ = False for line in key_lines: if not line.startswith("""#""" ): if len(line.split() ) > 6: A__ = line.split()[5] if not parse_col == "-": A__ = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A (datasets.Metric ): '''simple docstring''' def a_ ( self : int ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Sequence(datasets.Value("""string""" ) ), } ) , codebase_urls=["""https://github.com/ns-moosavi/coval"""] , reference_urls=[ """https://github.com/ns-moosavi/coval""", """https://www.aclweb.org/anthology/P16-1060""", """http://www.conll.cemantix.org/2012/data.html""", ] , ) def a_ ( self : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int=True , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : int=False ) -> Optional[int]: """simple docstring""" A__ = [ ("""mentions""", evaluator.mentions), ("""muc""", evaluator.muc), ("""bcub""", evaluator.b_cubed), ("""ceafe""", evaluator.ceafe), ("""lea""", evaluator.lea), ] if min_span: A__ = util.check_gold_parse_annotation(__lowerCAmelCase ) if not has_gold_parse: raise NotImplementedError("""References should have gold parse annotation to use 'min_span'.""" ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" A__ = evaluate( key_lines=__lowerCAmelCase , sys_lines=__lowerCAmelCase , metrics=__lowerCAmelCase , NP_only=__lowerCAmelCase , remove_nested=__lowerCAmelCase , keep_singletons=__lowerCAmelCase , min_span=__lowerCAmelCase , ) return score
247
1
"""simple docstring""" import pytest import datasets # Import fixture modules as plugins A = ['''tests.fixtures.files''', '''tests.fixtures.hub''', '''tests.fixtures.fsspec'''] def __A ( a_ :Dict , a_ :Optional[Any]) -> Optional[Any]: # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit") for item in items: if any(marker in item.keywords for marker in ['''integration''', '''unit''']): continue item.add_marker(pytest.mark.unit) def __A ( a_ :Dict) -> Union[str, Any]: config.addinivalue_line('''markers''' , '''torchaudio_latest: mark test to run with torchaudio>=0.12''') @pytest.fixture(autouse=a_) def __A ( a_ :Union[str, Any] , a_ :int) -> Any: # test_hf_cache_home = tmp_path_factory.mktemp("cache") # TODO: why a cache dir per test function does not work? __a : List[str] = tmp_path_factory.getbasetemp() / '''cache''' __a : Union[str, Any] = test_hf_cache_home / '''datasets''' __a : Tuple = test_hf_cache_home / '''metrics''' __a : Tuple = test_hf_cache_home / '''modules''' monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE''' , str(a_)) monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE''' , str(a_)) monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE''' , str(a_)) __a : List[str] = test_hf_datasets_cache / '''downloads''' monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH''' , str(a_)) __a : str = test_hf_datasets_cache / '''downloads''' / '''extracted''' monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(a_)) @pytest.fixture(autouse=a_ , scope='''session''') def __A ( ) -> Optional[int]: datasets.disable_progress_bar() @pytest.fixture(autouse=a_) def __A ( a_ :int) -> Any: # don't take tests into account when counting downloads monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS''' , a_) @pytest.fixture def __A ( a_ :Optional[int]) -> Optional[int]: # Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0 # To be removed once SQLAlchemy 2.0 supported monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING''' , a_)
52
'''simple docstring''' import math import flax.linen as nn import jax.numpy as jnp def _lowerCAmelCase ( __magic_name__ : jnp.ndarray , __magic_name__ : int , __magic_name__ : float = 1 , __magic_name__ : float = 1 , __magic_name__ : float = 1.0E4 , __magic_name__ : bool = False , __magic_name__ : float = 1.0 , ) -> jnp.ndarray: assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, f'''Embedding dimension {embedding_dim} should be even''' lowercase : int =float(embedding_dim // 2 ) lowercase : Optional[int] =math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) lowercase : Any =min_timescale * jnp.exp(jnp.arange(__magic_name__ , dtype=jnp.floataa ) * -log_timescale_increment ) lowercase : List[Any] =jnp.expand_dims(__magic_name__ , 1 ) * jnp.expand_dims(__magic_name__ , 0 ) # scale embeddings lowercase : Tuple =scale * emb if flip_sin_to_cos: lowercase : Dict =jnp.concatenate([jnp.cos(__magic_name__ ), jnp.sin(__magic_name__ )] , axis=1 ) else: lowercase : Any =jnp.concatenate([jnp.sin(__magic_name__ ), jnp.cos(__magic_name__ )] , axis=1 ) lowercase : List[str] =jnp.reshape(__magic_name__ , [jnp.shape(__magic_name__ )[0], embedding_dim] ) return signal class __SCREAMING_SNAKE_CASE ( nn.Module ): lowerCamelCase_ = 32 lowerCamelCase_ = jnp.floataa @nn.compact def __call__( self : Tuple , UpperCAmelCase__ : int ): '''simple docstring''' lowercase : List[Any] =nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_1''' )(UpperCAmelCase__ ) lowercase : Any =nn.silu(UpperCAmelCase__ ) lowercase : int =nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_2''' )(UpperCAmelCase__ ) return temb class __SCREAMING_SNAKE_CASE ( nn.Module ): lowerCamelCase_ = 32 lowerCamelCase_ = False lowerCamelCase_ = 1 @nn.compact def __call__( self : int , UpperCAmelCase__ : str ): '''simple docstring''' return get_sinusoidal_embeddings( UpperCAmelCase__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
92
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Any = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : Dict = '''big_bird''' def __init__(self , SCREAMING_SNAKE_CASE__=5_03_58 , SCREAMING_SNAKE_CASE__=7_68 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=30_72 , SCREAMING_SNAKE_CASE__="gelu_new" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=40_96 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=66 , SCREAMING_SNAKE_CASE__="block_sparse" , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ , ) -> Any: """simple docstring""" super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , sep_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : int = type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = use_cache SCREAMING_SNAKE_CASE__ : List[Any] = rescale_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = attention_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_bias SCREAMING_SNAKE_CASE__ : int = block_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_random_blocks SCREAMING_SNAKE_CASE__ : List[str] = classifier_dropout class lowerCAmelCase_ (a__ ): """simple docstring""" @property def __magic_name__ (self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Optional[Any] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ : List[Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
545
"""simple docstring""" UpperCAmelCase__ : Dict = [ (1_0_0_0, 'M'), (9_0_0, 'CM'), (5_0_0, 'D'), (4_0_0, 'CD'), (1_0_0, 'C'), (9_0, 'XC'), (5_0, 'L'), (4_0, 'XL'), (1_0, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1_000} SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 while place < len(_snake_case ): if (place + 1 < len(_snake_case )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : List[Any] = divmod(_snake_case ,_snake_case ) result.append(roman * factor ) if number == 0: break return "".join(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
545
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer _lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCAmelCase : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _lowerCAmelCase : str = [ "small", "small-base", "medium", "medium-base", "intermediate", "intermediate-base", "large", "large-base", "xlarge", "xlarge-base", ] _lowerCAmelCase : str = { "vocab_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json", "funnel-transformer/small-base": ( "https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json" ), "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json", "funnel-transformer/large-base": ( "https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json" ), "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json" ), }, } _lowerCAmelCase : List[str] = {f'''funnel-transformer/{name}''': 512 for name in _model_names} _lowerCAmelCase : Union[str, Any] = {f'''funnel-transformer/{name}''': {"do_lower_case": True} for name in _model_names} class __magic_name__ ( lowerCAmelCase_ ): SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE = FunnelTokenizer SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE = 2 def __init__( self , __snake_case=None , __snake_case=None , __snake_case=True , __snake_case="<unk>" , __snake_case="<sep>" , __snake_case="<pad>" , __snake_case="<cls>" , __snake_case="<mask>" , __snake_case="<s>" , __snake_case="</s>" , __snake_case=True , __snake_case=True , __snake_case=None , __snake_case="##" , **__snake_case , ) -> Tuple: '''simple docstring''' super().__init__( __snake_case , tokenizer_file=__snake_case , do_lower_case=__snake_case , unk_token=__snake_case , sep_token=__snake_case , pad_token=__snake_case , cls_token=__snake_case , mask_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , clean_text=__snake_case , tokenize_chinese_chars=__snake_case , strip_accents=__snake_case , wordpieces_prefix=__snake_case , **__snake_case , ) __a =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __snake_case ) != do_lower_case or normalizer_state.get('strip_accents' , __snake_case ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __snake_case ) != tokenize_chinese_chars ): __a =getattr(__snake_case , normalizer_state.pop('type' ) ) __a =do_lower_case __a =strip_accents __a =tokenize_chinese_chars __a =normalizer_class(**__snake_case ) __a =do_lower_case def __magic_name__ ( self , __snake_case , __snake_case=None ) -> Optional[Any]: '''simple docstring''' __a =[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 __magic_name__ ( self , __snake_case , __snake_case = None ) -> List[int]: '''simple docstring''' __a =[self.sep_token_id] __a =[self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self , __snake_case , __snake_case = None ) -> Tuple[str]: '''simple docstring''' __a =self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case )
242
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _lowerCAmelCase : Dict = logging.get_logger(__name__) class __magic_name__ ( lowerCAmelCase_ ): SCREAMING_SNAKE_CASE = ['pixel_values'] def __init__( self , __snake_case = True , __snake_case = None , __snake_case = PILImageResampling.BILINEAR , __snake_case = True , __snake_case = None , __snake_case = True , __snake_case = 1 / 255 , __snake_case = True , __snake_case = None , __snake_case = None , **__snake_case , ) -> None: '''simple docstring''' super().__init__(**__snake_case ) __a =size if size is not None else {'shortest_edge': 256} __a =get_size_dict(__snake_case , default_to_square=__snake_case ) __a =crop_size if crop_size is not None else {'height': 224, 'width': 224} __a =get_size_dict(__snake_case , param_name='crop_size' ) __a =do_resize __a =size __a =resample __a =do_center_crop __a =crop_size __a =do_rescale __a =rescale_factor __a =do_normalize __a =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __a =image_std if image_std is not None else IMAGENET_STANDARD_STD def __magic_name__ ( self , __snake_case , __snake_case , __snake_case = PILImageResampling.BICUBIC , __snake_case = None , **__snake_case , ) -> np.ndarray: '''simple docstring''' __a =get_size_dict(__snake_case , default_to_square=__snake_case ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __a =get_resize_output_image_size(__snake_case , size=size['shortest_edge'] , default_to_square=__snake_case ) return resize(__snake_case , size=__snake_case , resample=__snake_case , data_format=__snake_case , **__snake_case ) def __magic_name__ ( self , __snake_case , __snake_case , __snake_case = None , **__snake_case , ) -> np.ndarray: '''simple docstring''' __a =get_size_dict(__snake_case ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(__snake_case , size=(size['height'], size['width']) , data_format=__snake_case , **__snake_case ) def __magic_name__ ( self , __snake_case , __snake_case , __snake_case = None , **__snake_case ) -> np.ndarray: '''simple docstring''' return rescale(__snake_case , scale=__snake_case , data_format=__snake_case , **__snake_case ) def __magic_name__ ( self , __snake_case , __snake_case , __snake_case , __snake_case = None , **__snake_case , ) -> np.ndarray: '''simple docstring''' return normalize(__snake_case , mean=__snake_case , std=__snake_case , data_format=__snake_case , **__snake_case ) def __magic_name__ ( self , __snake_case , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = None , __snake_case = ChannelDimension.FIRST , **__snake_case , ) -> str: '''simple docstring''' __a =do_resize if do_resize is not None else self.do_resize __a =size if size is not None else self.size __a =get_size_dict(__snake_case , default_to_square=__snake_case ) __a =resample if resample is not None else self.resample __a =do_center_crop if do_center_crop is not None else self.do_center_crop __a =crop_size if crop_size is not None else self.crop_size __a =get_size_dict(__snake_case , param_name='crop_size' ) __a =do_rescale if do_rescale is not None else self.do_rescale __a =rescale_factor if rescale_factor is not None else self.rescale_factor __a =do_normalize if do_normalize is not None else self.do_normalize __a =image_mean if image_mean is not None else self.image_mean __a =image_std if image_std is not None else self.image_std __a =make_list_of_images(__snake_case ) if not valid_images(__snake_case ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. __a =[to_numpy_array(__snake_case ) for image in images] if do_resize: __a =[self.resize(image=__snake_case , size=__snake_case , resample=__snake_case ) for image in images] if do_center_crop: __a =[self.center_crop(image=__snake_case , size=__snake_case ) for image in images] if do_rescale: __a =[self.rescale(image=__snake_case , scale=__snake_case ) for image in images] if do_normalize: __a =[self.normalize(image=__snake_case , mean=__snake_case , std=__snake_case ) for image in images] __a =[to_channel_dimension_format(__snake_case , __snake_case ) for image in images] __a ={'pixel_values': images} return BatchFeature(data=__snake_case , tensor_type=__snake_case ) def __magic_name__ ( self , __snake_case , __snake_case = None ) -> Tuple: '''simple docstring''' __a =outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__snake_case ) != len(__snake_case ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(__snake_case ): __a =target_sizes.numpy() __a =[] for idx in range(len(__snake_case ) ): __a =torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='bilinear' , align_corners=__snake_case ) __a =resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__snake_case ) else: __a =logits.argmax(dim=1 ) __a =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
242
1
'''simple docstring''' import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __magic_name__ : """simple docstring""" def __init__( self , _lowercase , _lowercase=3 , _lowercase=32 , _lowercase=3 , _lowercase=10 , _lowercase=[8, 16, 32, 64] , _lowercase=[1, 1, 2, 1] , _lowercase=True , _lowercase=True , _lowercase="relu" , _lowercase=3 , _lowercase=None , _lowercase=["stage2", "stage3", "stage4"] , _lowercase=[2, 3, 4] , _lowercase=1 , ) -> str: lowercase_ : List[Any] = parent lowercase_ : str = batch_size lowercase_ : Optional[int] = image_size lowercase_ : Union[str, Any] = num_channels lowercase_ : Any = embeddings_size lowercase_ : List[Any] = hidden_sizes lowercase_ : str = depths lowercase_ : Optional[Any] = is_training lowercase_ : Any = use_labels lowercase_ : Tuple = hidden_act lowercase_ : Optional[Any] = num_labels lowercase_ : Union[str, Any] = scope lowercase_ : Union[str, Any] = len(_lowercase ) lowercase_ : str = out_features lowercase_ : Optional[Any] = out_indices lowercase_ : List[Any] = num_groups def lowerCamelCase__ ( self ) -> Optional[Any]: lowercase_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase_ : List[str] = None if self.use_labels: lowercase_ : Any = ids_tensor([self.batch_size] , self.num_labels ) lowercase_ : Any = self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self ) -> Any: return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def lowerCamelCase__ ( self , _lowercase , _lowercase , _lowercase ) -> int: lowercase_ : List[str] = BitModel(config=_lowercase ) model.to(_lowercase ) model.eval() lowercase_ : Tuple = model(_lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCamelCase__ ( self , _lowercase , _lowercase , _lowercase ) -> Union[str, Any]: lowercase_ : Any = self.num_labels lowercase_ : List[Any] = BitForImageClassification(_lowercase ) model.to(_lowercase ) model.eval() lowercase_ : Optional[Any] = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self , _lowercase , _lowercase , _lowercase ) -> Optional[Any]: lowercase_ : int = BitBackbone(config=_lowercase ) model.to(_lowercase ) model.eval() lowercase_ : str = model(_lowercase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None lowercase_ : int = None lowercase_ : int = BitBackbone(config=_lowercase ) model.to(_lowercase ) model.eval() lowercase_ : Optional[Any] = model(_lowercase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCamelCase__ ( self ) -> Optional[Any]: lowercase_ : Tuple = self.prepare_config_and_inputs() lowercase_ : Optional[Any] = config_and_inputs lowercase_ : int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __magic_name__ ( UpperCAmelCase_, UpperCAmelCase_, unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( {'feature-extraction': BitModel, 'image-classification': BitForImageClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ : Any = False SCREAMING_SNAKE_CASE_ : List[Any] = False SCREAMING_SNAKE_CASE_ : List[Any] = False SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : str = False def lowerCamelCase__ ( self ) -> str: lowercase_ : List[Any] = BitModelTester(self ) lowercase_ : Optional[Any] = ConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase ) def lowerCamelCase__ ( self ) -> str: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCamelCase__ ( self ) -> List[Any]: return @unittest.skip(reason='Bit does not output attentions' ) def lowerCamelCase__ ( self ) -> str: pass @unittest.skip(reason='Bit does not use inputs_embeds' ) def lowerCamelCase__ ( self ) -> Any: pass @unittest.skip(reason='Bit does not support input and output embeddings' ) def lowerCamelCase__ ( self ) -> Any: pass def lowerCamelCase__ ( self ) -> Any: lowercase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ : Dict = model_class(_lowercase ) lowercase_ : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase_ : Union[str, Any] = [*signature.parameters.keys()] lowercase_ : Tuple = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCamelCase__ ( self ) -> int: lowercase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def lowerCamelCase__ ( self ) -> Dict: lowercase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowercase ) def lowerCamelCase__ ( self ) -> Any: lowercase_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ : Optional[int] = model_class(config=_lowercase ) for name, module in model.named_modules(): if isinstance(_lowercase , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) def lowerCamelCase__ ( self ) -> str: def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): lowercase_ : int = model_class(_lowercase ) model.to(_lowercase ) model.eval() with torch.no_grad(): lowercase_ : Optional[Any] = model(**self._prepare_for_class(_lowercase , _lowercase ) ) lowercase_ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowercase_ : Dict = self.model_tester.num_stages self.assertEqual(len(_lowercase ) , expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowercase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ : List[str] = ['preactivation', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: lowercase_ : Dict = layer_type lowercase_ : Optional[int] = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase_ : Union[str, Any] = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) @unittest.skip(reason='Bit does not use feedforward chunking' ) def lowerCamelCase__ ( self ) -> Tuple: pass def lowerCamelCase__ ( self ) -> Tuple: lowercase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) @slow def lowerCamelCase__ ( self ) -> Dict: for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ : Optional[Any] = BitModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def _UpperCAmelCase ( ) -> str: """simple docstring""" lowercase_ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): """simple docstring""" @cached_property def lowerCamelCase__ ( self ) -> Any: return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCamelCase__ ( self ) -> Optional[int]: lowercase_ : Union[str, Any] = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_lowercase ) lowercase_ : Optional[int] = self.default_image_processor lowercase_ : List[Any] = prepare_img() lowercase_ : List[Any] = image_processor(images=_lowercase , return_tensors='pt' ).to(_lowercase ) # forward pass with torch.no_grad(): lowercase_ : Union[str, Any] = model(**_lowercase ) # verify the logits lowercase_ : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) lowercase_ : Dict = torch.tensor([[-0.65_26, -0.52_63, -1.43_98]] ).to(_lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowercase , atol=1E-4 ) ) @require_torch class __magic_name__ ( UpperCAmelCase_, unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = (BitBackbone,) if is_torch_available() else () SCREAMING_SNAKE_CASE_ : List[Any] = BitConfig SCREAMING_SNAKE_CASE_ : Optional[Any] = False def lowerCamelCase__ ( self ) -> Tuple: lowercase_ : str = BitModelTester(self )
707
'''simple docstring''' def _UpperCAmelCase ( a : str ) -> str: """simple docstring""" lowercase_ : Dict = 0 # if input_string is "aba" than new_input_string become "a|b|a" lowercase_ : Dict = '' lowercase_ : Any = '' # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(a ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring lowercase_ , lowercase_ : Dict = 0, 0 # length[i] shows the length of palindromic substring with center i lowercase_ : List[Any] = [1 for i in range(len(a ) )] # for each character in new_string find corresponding palindromic string lowercase_ : Dict = 0 for j in range(len(a ) ): lowercase_ : Tuple = 1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(a ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 lowercase_ : int = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: lowercase_ : Tuple = j - k + 1 # noqa: E741 lowercase_ : Tuple = j + k - 1 # update max_length and start position if max_length < length[j]: lowercase_ : Tuple = length[j] lowercase_ : List[Any] = j # create that string lowercase_ : str = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
7
0
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 lowercase_: Any = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' lowercase_: Optional[Any] = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' lowercase_: int = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' lowercase_: Tuple = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' lowercase_: Tuple = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase__ (datasets.Metric ): """simple docstring""" def lowercase ( self : str ): 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 lowercase ( self : str , __a : Optional[int] , __a : Optional[Any] , __a : str=[1, 1_0, 1_0_0] , __a : List[str]=4 , __a : int=3.0 ): 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=__a ) as executor: snake_case__ : List[str] = [] snake_case__ : Any = Counter() snake_case__ : str = 0 snake_case__ : int = defaultdict(__a ) for task_id, (candidates, test_case) in enumerate(zip(__a , __a ) ): for candidate in candidates: snake_case__ : List[Any] = candidate + """\n""" + test_case snake_case__ : Tuple = (test_program, timeout, task_id, completion_id[task_id]) snake_case__ : Optional[int] = executor.submit(__a , *__a ) futures.append(__a ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(__a ): snake_case__ : Any = future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) snake_case__ , snake_case__ : str = [], [] for result in results.values(): result.sort() snake_case__ : List[str] = [r[1]["""passed"""] for r in result] total.append(len(__a ) ) correct.append(sum(__a ) ) snake_case__ : Dict = np.array(__a ) snake_case__ : Optional[int] = np.array(__a ) snake_case__ : Union[str, Any] = k snake_case__ : Tuple = {f'pass@{k}': estimate_pass_at_k(__a , __a , __a ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_): """simple docstring""" def estimator(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) -> 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(UpperCAmelCase_ , UpperCAmelCase_): snake_case__ : Union[str, Any] = itertools.repeat(UpperCAmelCase_ , len(UpperCAmelCase_)) else: assert len(UpperCAmelCase_) == len(UpperCAmelCase_) snake_case__ : int = iter(UpperCAmelCase_) return np.array([estimator(int(UpperCAmelCase_) , int(UpperCAmelCase_) , UpperCAmelCase_) for n, c in zip(UpperCAmelCase_ , UpperCAmelCase_)])
648
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_: Any = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_: Dict = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_: List[str] = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys lowercase_: List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
648
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase_ = { """configuration_nllb_moe""": [ """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NllbMoeConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ """NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST""", """NllbMoeForConditionalGeneration""", """NllbMoeModel""", """NllbMoePreTrainedModel""", """NllbMoeTop2Router""", """NllbMoeSparseMLP""", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
715
'''simple docstring''' import mpmath # for roots of unity import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[Any]=None ): '''simple docstring''' # Input as list lowercase : Optional[int] =list(poly_a or [0] )[:] lowercase : Optional[Any] =list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() lowercase : Any =len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() lowercase : Dict =len(self.polyB ) # Add 0 to make lengths equal a power of 2 lowercase : int =int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform lowercase : Union[str, Any] =complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product lowercase : Tuple =self.__multiply() def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple ): '''simple docstring''' lowercase : Union[str, Any] =[[x] for x in self.polyA] if which == '''A''' else [[x] for x in self.polyB] # Corner case if len(UpperCAmelCase__ ) <= 1: return dft[0] # lowercase : Any =self.c_max_length // 2 while next_ncol > 0: lowercase : Optional[int] =[[] for i in range(UpperCAmelCase__ )] lowercase : Tuple =self.root**next_ncol # First half of next step lowercase : str =1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(UpperCAmelCase__ ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step lowercase : int =1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(UpperCAmelCase__ ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update lowercase : Dict =new_dft lowercase : Tuple =next_ncol // 2 return dft[0] def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Any =self.__dft('''A''' ) lowercase : Any =self.__dft('''B''' ) lowercase : Optional[int] =[[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT lowercase : Optional[int] =2 while next_ncol <= self.c_max_length: lowercase : Optional[int] =[[] for i in range(UpperCAmelCase__ )] lowercase : List[str] =self.root ** (next_ncol // 2) lowercase : Optional[int] =1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update lowercase : List[Any] =new_inverse_c next_ncol *= 2 # Unpack lowercase : Tuple =[round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1J for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self : Any ): '''simple docstring''' lowercase : Any ='''A = ''' + ''' + '''.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) ) lowercase : Tuple ='''B = ''' + ''' + '''.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) ) lowercase : List[str] ='''A*B = ''' + ''' + '''.join( F'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) ) return F'''{a}\n{b}\n{c}''' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
0
import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType _A = logging.get_logger(__name__) class A ( __UpperCAmelCase ): __snake_case = 'vision-encoder-decoder' __snake_case = True def __init__( self, **UpperCamelCase__ ): """simple docstring""" super().__init__(**UpperCamelCase__ ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( f"A configuraton of type {self.model_type} cannot be instantiated because " f"not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}" ) lowerCAmelCase_ = kwargs.pop('''encoder''' ) lowerCAmelCase_ = encoder_config.pop('''model_type''' ) lowerCAmelCase_ = kwargs.pop('''decoder''' ) lowerCAmelCase_ = decoder_config.pop('''model_type''' ) lowerCAmelCase_ = AutoConfig.for_model(UpperCamelCase__, **UpperCamelCase__ ) lowerCAmelCase_ = AutoConfig.for_model(UpperCamelCase__, **UpperCamelCase__ ) lowerCAmelCase_ = True @classmethod def SCREAMING_SNAKE_CASE__ ( cls, UpperCamelCase__, UpperCamelCase__, **UpperCamelCase__ ): """simple docstring""" logger.info('''Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) lowerCAmelCase_ = True lowerCAmelCase_ = True return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = copy.deepcopy(self.__dict__ ) lowerCAmelCase_ = self.encoder.to_dict() lowerCAmelCase_ = self.decoder.to_dict() lowerCAmelCase_ = self.__class__.model_type return output class A ( __UpperCAmelCase ): __snake_case = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" return 1E-4 @property def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" return OrderedDict({'''last_hidden_state''': {0: '''batch''', 1: '''encoder_sequence'''}} ) class A ( __UpperCAmelCase ): @property def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = OrderedDict() lowerCAmelCase_ = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} lowerCAmelCase_ = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} lowerCAmelCase_ = {0: '''batch''', 1: '''encoder_sequence'''} return common_inputs def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__ = -1, UpperCamelCase__ = -1, UpperCamelCase__ = False, UpperCamelCase__ = None, ): """simple docstring""" import torch lowerCAmelCase_ = OrderedDict() lowerCAmelCase_ = super().generate_dummy_inputs( UpperCamelCase__, batch_size=UpperCamelCase__, seq_length=UpperCamelCase__, is_pair=UpperCamelCase__, framework=UpperCamelCase__ ) lowerCAmelCase_ , lowerCAmelCase_ = dummy_input['''input_ids'''].shape lowerCAmelCase_ = (batch, encoder_sequence, self._config.encoder_hidden_size) lowerCAmelCase_ = dummy_input.pop('''input_ids''' ) lowerCAmelCase_ = dummy_input.pop('''attention_mask''' ) lowerCAmelCase_ = torch.zeros(UpperCamelCase__ ) return common_inputs class A ( __UpperCAmelCase ): @property def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" pass def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ): """simple docstring""" return VisionEncoderDecoderEncoderOnnxConfig(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ = "default" ): """simple docstring""" lowerCAmelCase_ = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(UpperCamelCase__, UpperCamelCase__ )
431
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _A = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
431
1
"""simple docstring""" def _lowerCAmelCase ( __lowerCamelCase:list , __lowerCamelCase:list ): '''simple docstring''' _validate_point(__lowerCamelCase ) _validate_point(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(a - b ) for a, b in zip(__lowerCamelCase , __lowerCamelCase ) ) ) def _lowerCAmelCase ( __lowerCamelCase:list[float] ): '''simple docstring''' if point: if isinstance(__lowerCamelCase , __lowerCamelCase ): for item in point: if not isinstance(__lowerCamelCase , (int, float) ): __magic_name__ = ( "Expected a list of numbers as input, found " f'''{type(__lowerCamelCase ).__name__}''' ) raise TypeError(__lowerCamelCase ) else: __magic_name__ = f'''Expected a list of numbers as input, found {type(__lowerCamelCase ).__name__}''' raise TypeError(__lowerCamelCase ) else: raise ValueError("Missing an input" ) def _lowerCAmelCase ( __lowerCamelCase:list , __lowerCamelCase:list ): '''simple docstring''' _validate_point(__lowerCamelCase ) _validate_point(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(x - y ) for x, y in zip(__lowerCamelCase , __lowerCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
702
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( snake_case_ ): UpperCAmelCase__ = ['''image_processor''', '''tokenizer'''] UpperCAmelCase__ = '''BlipImageProcessor''' UpperCAmelCase__ = '''AutoTokenizer''' def __init__( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : int ) -> str: __magic_name__ = False super().__init__(__lowerCamelCase , __lowerCamelCase ) __magic_name__ = self.image_processor def __call__( self : List[Any] , __lowerCamelCase : ImageInput = None , __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 : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Union[str, TensorType]] = None , **__lowerCamelCase : Optional[int] , ) -> BatchEncoding: if images is None and text is None: raise ValueError("You have to specify either images or text." ) # Get only text if images is None: __magic_name__ = self.tokenizer __magic_name__ = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) return text_encoding # add pixel_values __magic_name__ = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) if text is not None: __magic_name__ = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) else: __magic_name__ = None if text_encoding is not None: encoding_image_processor.update(__lowerCamelCase ) return encoding_image_processor def _snake_case ( self : Union[str, Any] , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : Dict ) -> Dict: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def _snake_case ( self : str , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Tuple ) -> Optional[Any]: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _snake_case ( self : List[str] ) -> Optional[Any]: __magic_name__ = self.tokenizer.model_input_names __magic_name__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
468
0
"""simple docstring""" from __future__ import annotations def _lowerCAmelCase ( UpperCamelCase_ = 4 ): __SCREAMING_SNAKE_CASE = abs(UpperCamelCase_ ) or 4 return [[1 + x + y * row_size for x in range(UpperCamelCase_ )] for y in range(UpperCamelCase_ )] def _lowerCAmelCase ( UpperCamelCase_ ): return reverse_row(transpose(UpperCamelCase_ ) ) # OR.. transpose(reverse_column(matrix)) def _lowerCAmelCase ( UpperCamelCase_ ): return reverse_row(reverse_column(UpperCamelCase_ ) ) # OR.. reverse_column(reverse_row(matrix)) def _lowerCAmelCase ( UpperCamelCase_ ): return reverse_column(transpose(UpperCamelCase_ ) ) # OR.. transpose(reverse_row(matrix)) def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [list(UpperCamelCase_ ) for x in zip(*UpperCamelCase_ )] return matrix def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = matrix[::-1] return matrix def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [x[::-1] for x in matrix] return matrix def _lowerCAmelCase ( UpperCamelCase_ ): for i in matrix: print(*UpperCamelCase_ ) if __name__ == "__main__": __magic_name__ = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_aa(matrix)) __magic_name__ = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_aaa(matrix)) __magic_name__ = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_aaa(matrix))
155
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __magic_name__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" def __init__( self , lowerCAmelCase__): super().__init__() __SCREAMING_SNAKE_CASE = nn.ModuleList(lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = True , ): for i, (image, scale, controlnet) in enumerate(zip(lowerCAmelCase__ , lowerCAmelCase__ , self.nets)): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = controlnet( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) # merge samples if i == 0: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = down_samples, mid_sample else: __SCREAMING_SNAKE_CASE = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(lowerCAmelCase__ , lowerCAmelCase__) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , ): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = save_directory for controlnet in self.nets: controlnet.save_pretrained( lowerCAmelCase__ , is_main_process=lowerCAmelCase__ , save_function=lowerCAmelCase__ , safe_serialization=lowerCAmelCase__ , variant=lowerCAmelCase__ , ) idx += 1 __SCREAMING_SNAKE_CASE = model_path_to_save + f"_{idx}" @classmethod def snake_case_ ( cls , lowerCAmelCase__ , **lowerCAmelCase__): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __SCREAMING_SNAKE_CASE = pretrained_model_path while os.path.isdir(lowerCAmelCase__): __SCREAMING_SNAKE_CASE = ControlNetModel.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__) controlnets.append(lowerCAmelCase__) idx += 1 __SCREAMING_SNAKE_CASE = pretrained_model_path + f"_{idx}" logger.info(f"{len(lowerCAmelCase__)} controlnets loaded from {pretrained_model_path}.") if len(lowerCAmelCase__) == 0: raise ValueError( f"No ControlNets found under {os.path.dirname(lowerCAmelCase__)}. Expected at least {pretrained_model_path + '_0'}.") return cls(lowerCAmelCase__)
155
1
'''simple docstring''' from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket" ) @patch("builtins.open" ) def UpperCAmelCase_ ( lowercase__ , lowercase__ ): '''simple docstring''' a_ =Mock() a_ =conn, Mock() a_ =iter([1, None] ) a_ =lambda lowercase__ : next(lowercase__ ) # ===== invoke ===== send_file(filename="mytext.txt" , testing=lowercase__ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
41
'''simple docstring''' from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, require_torch_min_version, require_tpu, require_xpu, skip, slow, ) from .training import RegressionDataset, RegressionModel, RegressionModelaXPU from .scripts import test_script, test_sync, test_ops # isort: skip
41
1
"""simple docstring""" import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures lowerCAmelCase__ = logging.get_logger(__name__) @dataclass class _lowerCAmelCase : SCREAMING_SNAKE_CASE_: str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys() )} ) SCREAMING_SNAKE_CASE_: str = field( metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} ) SCREAMING_SNAKE_CASE_: int = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) SCREAMING_SNAKE_CASE_: bool = field( default=__UpperCAmelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def A ( self ) -> Dict: _SCREAMING_SNAKE_CASE : str = self.task_name.lower() class _lowerCAmelCase ( __UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Union[str, Any] = 'train' SCREAMING_SNAKE_CASE_: int = 'dev' SCREAMING_SNAKE_CASE_: int = 'test' class _lowerCAmelCase ( __UpperCAmelCase ): SCREAMING_SNAKE_CASE_: GlueDataTrainingArguments SCREAMING_SNAKE_CASE_: str SCREAMING_SNAKE_CASE_: List[InputFeatures] def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = Split.train , lowerCAmelCase_ = None , ) -> Tuple: warnings.warn( 'This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets ' 'library. You can have a look at this example script for pointers: ' 'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py' , lowerCAmelCase_ , ) _SCREAMING_SNAKE_CASE : int = args _SCREAMING_SNAKE_CASE : int = glue_processors[args.task_name]() _SCREAMING_SNAKE_CASE : Optional[Any] = glue_output_modes[args.task_name] if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): try: _SCREAMING_SNAKE_CASE : Dict = Split[mode] except KeyError: raise KeyError('mode is not a valid split name' ) # Load data features from cache or dataset file _SCREAMING_SNAKE_CASE : Tuple = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}""" , ) _SCREAMING_SNAKE_CASE : int = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = label_list[2], label_list[1] _SCREAMING_SNAKE_CASE : List[Any] = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _SCREAMING_SNAKE_CASE : Optional[Any] = cached_features_file + '.lock' with FileLock(lowerCAmelCase_ ): if os.path.exists(lowerCAmelCase_ ) and not args.overwrite_cache: _SCREAMING_SNAKE_CASE : str = time.time() _SCREAMING_SNAKE_CASE : Any = torch.load(lowerCAmelCase_ ) logger.info( F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start ) else: logger.info(F"""Creating features from dataset file at {args.data_dir}""" ) if mode == Split.dev: _SCREAMING_SNAKE_CASE : Tuple = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: _SCREAMING_SNAKE_CASE : int = self.processor.get_test_examples(args.data_dir ) else: _SCREAMING_SNAKE_CASE : Any = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: _SCREAMING_SNAKE_CASE : List[str] = examples[:limit_length] _SCREAMING_SNAKE_CASE : Optional[Any] = glue_convert_examples_to_features( lowerCAmelCase_ , lowerCAmelCase_ , max_length=args.max_seq_length , label_list=lowerCAmelCase_ , output_mode=self.output_mode , ) _SCREAMING_SNAKE_CASE : List[str] = time.time() torch.save(self.features , lowerCAmelCase_ ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" ) def __len__( self ) -> List[Any]: return len(self.features ) def __getitem__( self , lowerCAmelCase_ ) -> InputFeatures: return self.features[i] def A ( self ) -> str: return self.label_list
621
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def lowercase__ ( lowerCamelCase ): # initialize config if "resnet-50" in model_name: _SCREAMING_SNAKE_CASE : Optional[int] = ResNetConfig.from_pretrained('microsoft/resnet-50' ) elif "resnet-101" in model_name: _SCREAMING_SNAKE_CASE : Optional[Any] = ResNetConfig.from_pretrained('microsoft/resnet-101' ) else: raise ValueError('Model name should include either resnet50 or resnet101' ) _SCREAMING_SNAKE_CASE : Optional[Any] = DetrConfig(use_timm_backbone=lowerCamelCase, backbone_config=lowerCamelCase ) # set label attributes _SCREAMING_SNAKE_CASE : Optional[int] = 'panoptic' in model_name if is_panoptic: _SCREAMING_SNAKE_CASE : List[str] = 250 else: _SCREAMING_SNAKE_CASE : Optional[Any] = 91 _SCREAMING_SNAKE_CASE : Union[str, Any] = 'huggingface/label-files' _SCREAMING_SNAKE_CASE : Dict = 'coco-detection-id2label.json' _SCREAMING_SNAKE_CASE : List[str] = json.load(open(hf_hub_download(lowerCamelCase, lowerCamelCase, repo_type='dataset' ), 'r' ) ) _SCREAMING_SNAKE_CASE : Dict = {int(lowerCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : List[Any] = idalabel _SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in idalabel.items()} return config, is_panoptic def lowercase__ ( lowerCamelCase ): # here we list all keys to be renamed (original name on the left, our name on the right) _SCREAMING_SNAKE_CASE : Optional[int] = [] # stem # fmt: off rename_keys.append(('backbone.0.body.conv1.weight', 'backbone.conv_encoder.model.embedder.embedder.convolution.weight') ) rename_keys.append(('backbone.0.body.bn1.weight', 'backbone.conv_encoder.model.embedder.embedder.normalization.weight') ) rename_keys.append(('backbone.0.body.bn1.bias', 'backbone.conv_encoder.model.embedder.embedder.normalization.bias') ) rename_keys.append(('backbone.0.body.bn1.running_mean', 'backbone.conv_encoder.model.embedder.embedder.normalization.running_mean') ) rename_keys.append(('backbone.0.body.bn1.running_var', 'backbone.conv_encoder.model.embedder.embedder.normalization.running_var') ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var""", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var""", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", f"""encoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (f"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", f"""encoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""encoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""encoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""encoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""encoder.layers.{i}.fc2.bias""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm1.weight""", f"""encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm1.bias""", f"""encoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm2.weight""", f"""encoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""encoder.layers.{i}.final_layer_norm.bias""") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""decoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append( ( f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""", f"""decoder.layers.{i}.encoder_attn.out_proj.weight""", ) ) rename_keys.append( ( f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""", f"""decoder.layers.{i}.encoder_attn.out_proj.bias""", ) ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""decoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""decoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""decoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""decoder.layers.{i}.fc2.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm1.weight""", f"""decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm1.bias""", f"""decoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm2.weight""", f"""decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm2.bias""", f"""decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm3.weight""", f"""decoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""decoder.layers.{i}.final_layer_norm.bias""") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('input_proj.weight', 'input_projection.weight'), ('input_proj.bias', 'input_projection.bias'), ('query_embed.weight', 'query_position_embeddings.weight'), ('transformer.decoder.norm.weight', 'decoder.layernorm.weight'), ('transformer.decoder.norm.bias', 'decoder.layernorm.bias'), ('class_embed.weight', 'class_labels_classifier.weight'), ('class_embed.bias', 'class_labels_classifier.bias'), ('bbox_embed.layers.0.weight', 'bbox_predictor.layers.0.weight'), ('bbox_embed.layers.0.bias', 'bbox_predictor.layers.0.bias'), ('bbox_embed.layers.1.weight', 'bbox_predictor.layers.1.weight'), ('bbox_embed.layers.1.bias', 'bbox_predictor.layers.1.bias'), ('bbox_embed.layers.2.weight', 'bbox_predictor.layers.2.weight'), ('bbox_embed.layers.2.bias', 'bbox_predictor.layers.2.bias'), ] ) return rename_keys def lowercase__ ( lowerCamelCase, lowerCamelCase, lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = state_dict.pop(lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = val def lowercase__ ( lowerCamelCase, lowerCamelCase=False ): _SCREAMING_SNAKE_CASE : Optional[int] = '' if is_panoptic: _SCREAMING_SNAKE_CASE : List[Any] = 'detr.' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) _SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) _SCREAMING_SNAKE_CASE : Dict = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE : Any = in_proj_weight[:256, :] _SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[:256] _SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[256:512, :] _SCREAMING_SNAKE_CASE : Tuple = in_proj_bias[256:512] _SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[-256:, :] _SCREAMING_SNAKE_CASE : Optional[int] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention _SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) _SCREAMING_SNAKE_CASE : int = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[:256, :] _SCREAMING_SNAKE_CASE : str = in_proj_bias[:256] _SCREAMING_SNAKE_CASE : str = in_proj_weight[256:512, :] _SCREAMING_SNAKE_CASE : int = in_proj_bias[256:512] _SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[-256:, :] _SCREAMING_SNAKE_CASE : List[str] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention _SCREAMING_SNAKE_CASE : str = state_dict.pop( f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight""" ) _SCREAMING_SNAKE_CASE : List[Any] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) of cross-attention to the state dict _SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight_cross_attn[:256, :] _SCREAMING_SNAKE_CASE : Optional[int] = in_proj_bias_cross_attn[:256] _SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight_cross_attn[256:512, :] _SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias_cross_attn[256:512] _SCREAMING_SNAKE_CASE : int = in_proj_weight_cross_attn[-256:, :] _SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias_cross_attn[-256:] def lowercase__ ( ): _SCREAMING_SNAKE_CASE : List[Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' _SCREAMING_SNAKE_CASE : Dict = Image.open(requests.get(lowerCamelCase, stream=lowerCamelCase ).raw ) return im @torch.no_grad() def lowercase__ ( lowerCamelCase, lowerCamelCase=None, lowerCamelCase=False ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = get_detr_config(lowerCamelCase ) # load original model from torch hub _SCREAMING_SNAKE_CASE : Optional[Any] = { 'detr-resnet-50': 'detr_resnet50', 'detr-resnet-101': 'detr_resnet101', } logger.info(f"""Converting model {model_name}...""" ) _SCREAMING_SNAKE_CASE : int = torch.hub.load('facebookresearch/detr', model_name_to_original_name[model_name], pretrained=lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE : Optional[Any] = detr.state_dict() # rename keys for src, dest in create_rename_keys(lowerCamelCase ): if is_panoptic: _SCREAMING_SNAKE_CASE : int = 'detr.' + src rename_key(lowerCamelCase, lowerCamelCase, lowerCamelCase ) # query, key and value matrices need special treatment read_in_q_k_v(lowerCamelCase, is_panoptic=lowerCamelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them _SCREAMING_SNAKE_CASE : str = 'detr.model.' if is_panoptic else 'model.' for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith('detr' ) and not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ) ): _SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = val elif "class_labels_classifier" in key or "bbox_predictor" in key: _SCREAMING_SNAKE_CASE : Tuple = state_dict.pop(lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = val elif key.startswith('bbox_attention' ) or key.startswith('mask_head' ): continue else: _SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = val else: if not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ): _SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = val # finally, create HuggingFace model and load state dict _SCREAMING_SNAKE_CASE : Dict = DetrForSegmentation(lowerCamelCase ) if is_panoptic else DetrForObjectDetection(lowerCamelCase ) model.load_state_dict(lowerCamelCase ) model.eval() # verify our conversion on an image _SCREAMING_SNAKE_CASE : Optional[Any] = 'coco_panoptic' if is_panoptic else 'coco_detection' _SCREAMING_SNAKE_CASE : int = DetrImageProcessor(format=lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = processor(images=prepare_img(), return_tensors='pt' ) _SCREAMING_SNAKE_CASE : Tuple = encoding['pixel_values'] _SCREAMING_SNAKE_CASE : List[str] = detr(lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = model(lowerCamelCase ) assert torch.allclose(outputs.logits, original_outputs['pred_logits'], atol=1E-3 ) assert torch.allclose(outputs.pred_boxes, original_outputs['pred_boxes'], atol=1E-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks, original_outputs['pred_masks'], atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(lowerCamelCase ).mkdir(exist_ok=lowerCamelCase ) model.save_pretrained(lowerCamelCase ) processor.save_pretrained(lowerCamelCase ) if push_to_hub: # Upload model and image processor to the hub logger.info('Uploading PyTorch model and image processor to the hub...' ) model.push_to_hub(f"""nielsr/{model_name}""" ) processor.push_to_hub(f"""nielsr/{model_name}""" ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') lowerCAmelCase__ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
621
1
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __A : Optional[int] = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class lowercase_ ( unittest.TestCase ): __UpperCamelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCamelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __UpperCamelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __UpperCamelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def _lowercase ( self: List[str], _lowercase: Union[str, Any], _lowercase: Union[str, Any], _lowercase: Tuple): '''simple docstring''' __lowerCAmelCase = ZeroShotClassificationPipeline( model=_lowercase, tokenizer=_lowercase, candidate_labels=["""polics""", """health"""]) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def _lowercase ( self: List[str], _lowercase: Union[str, Any], _lowercase: Optional[int]): '''simple docstring''' __lowerCAmelCase = classifier("""Who are you voting for in 2020?""", candidate_labels="""politics""") self.assertEqual(_lowercase, {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase)], """scores""": [ANY(_lowercase)]}) # No kwarg __lowerCAmelCase = classifier("""Who are you voting for in 2020?""", ["""politics"""]) self.assertEqual(_lowercase, {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase)], """scores""": [ANY(_lowercase)]}) __lowerCAmelCase = classifier("""Who are you voting for in 2020?""", candidate_labels=["""politics"""]) self.assertEqual(_lowercase, {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase)], """scores""": [ANY(_lowercase)]}) __lowerCAmelCase = classifier("""Who are you voting for in 2020?""", candidate_labels="""politics, public health""") self.assertEqual( _lowercase, {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase), ANY(_lowercase)], """scores""": [ANY(_lowercase), ANY(_lowercase)]}) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""])), 1.0) __lowerCAmelCase = classifier("""Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health"""]) self.assertEqual( _lowercase, {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase), ANY(_lowercase)], """scores""": [ANY(_lowercase), ANY(_lowercase)]}) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""])), 1.0) __lowerCAmelCase = classifier( """Who are you voting for in 2020?""", candidate_labels="""politics""", hypothesis_template="""This text is about {}""") self.assertEqual(_lowercase, {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase)], """scores""": [ANY(_lowercase)]}) # https://github.com/huggingface/transformers/issues/13846 __lowerCAmelCase = classifier(["""I am happy"""], ["""positive""", """negative"""]) self.assertEqual( _lowercase, [ {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase), ANY(_lowercase)], """scores""": [ANY(_lowercase), ANY(_lowercase)]} for i in range(1) ], ) __lowerCAmelCase = classifier(["""I am happy""", """I am sad"""], ["""positive""", """negative"""]) self.assertEqual( _lowercase, [ {"""sequence""": ANY(_lowercase), """labels""": [ANY(_lowercase), ANY(_lowercase)], """scores""": [ANY(_lowercase), ANY(_lowercase)]} for i in range(2) ], ) with self.assertRaises(_lowercase): classifier("""""", candidate_labels="""politics""") with self.assertRaises(_lowercase): classifier(_lowercase, candidate_labels="""politics""") with self.assertRaises(_lowercase): classifier("""Who are you voting for in 2020?""", candidate_labels="""""") with self.assertRaises(_lowercase): classifier("""Who are you voting for in 2020?""", candidate_labels=_lowercase) with self.assertRaises(_lowercase): classifier( """Who are you voting for in 2020?""", candidate_labels="""politics""", hypothesis_template="""Not formatting template""", ) with self.assertRaises(_lowercase): classifier( """Who are you voting for in 2020?""", candidate_labels="""politics""", hypothesis_template=_lowercase, ) self.run_entailment_id(_lowercase) def _lowercase ( self: Tuple, _lowercase: Pipeline): '''simple docstring''' __lowerCAmelCase = zero_shot_classifier.model.config __lowerCAmelCase = config.labelaid __lowerCAmelCase = zero_shot_classifier.entailment_id __lowerCAmelCase = {"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2} self.assertEqual(zero_shot_classifier.entailment_id, -1) __lowerCAmelCase = {"""entailment""": 0, """neutral""": 1, """contradiction""": 2} self.assertEqual(zero_shot_classifier.entailment_id, 0) __lowerCAmelCase = {"""ENTAIL""": 0, """NON-ENTAIL""": 1} self.assertEqual(zero_shot_classifier.entailment_id, 0) __lowerCAmelCase = {"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0} self.assertEqual(zero_shot_classifier.entailment_id, 2) __lowerCAmelCase = original_labelaid self.assertEqual(_lowercase, zero_shot_classifier.entailment_id) @require_torch def _lowercase ( self: List[Any]): '''simple docstring''' __lowerCAmelCase = pipeline( """zero-shot-classification""", model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""", framework="""pt""", ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( """Who are you voting for in 2020?""" * 100, candidate_labels=["""politics""", """public health""", """science"""]) @require_torch def _lowercase ( self: str): '''simple docstring''' __lowerCAmelCase = pipeline( """zero-shot-classification""", model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""", framework="""pt""", ) __lowerCAmelCase = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""]) self.assertEqual( nested_simplify(_lowercase), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.333, 0.333, 0.333], }, ) @require_tf def _lowercase ( self: Union[str, Any]): '''simple docstring''' __lowerCAmelCase = pipeline( """zero-shot-classification""", model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""", framework="""tf""", ) __lowerCAmelCase = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""]) self.assertEqual( nested_simplify(_lowercase), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.333, 0.333, 0.333], }, ) @slow @require_torch def _lowercase ( self: Optional[int]): '''simple docstring''' __lowerCAmelCase = pipeline("""zero-shot-classification""", model="""roberta-large-mnli""", framework="""pt""") __lowerCAmelCase = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""]) self.assertEqual( nested_simplify(_lowercase), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.976, 0.015, 0.009], }, ) __lowerCAmelCase = zero_shot_classifier( """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks""" """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder""" """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based""" """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two""" """ machine translation tasks show these models to be superior in quality while being more parallelizable""" """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014""" """ English-to-German translation task, improving over the existing best results, including ensembles by""" """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new""" """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small""" """ fraction of the training costs of the best models from the literature. We show that the Transformer""" """ generalizes well to other tasks by applying it successfully to English constituency parsing both with""" """ large and limited training data.""", candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""], multi_label=_lowercase, ) self.assertEqual( nested_simplify(_lowercase), { """sequence""": ( """The dominant sequence transduction models are based on complex recurrent or convolutional neural""" """ networks in an encoder-decoder configuration. The best performing models also connect the""" """ encoder and decoder through an attention mechanism. We propose a new simple network""" """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence""" """ and convolutions entirely. Experiments on two machine translation tasks show these models to be""" """ superior in quality while being more parallelizable and requiring significantly less time to""" """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,""" """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014""" """ English-to-French translation task, our model establishes a new single-model state-of-the-art""" """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training""" """ costs of the best models from the literature. We show that the Transformer generalizes well to""" """ other tasks by applying it successfully to English constituency parsing both with large and""" """ limited training data.""" ), """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""], """scores""": [0.817, 0.713, 0.018, 0.018], }, ) @slow @require_tf def _lowercase ( self: List[str]): '''simple docstring''' __lowerCAmelCase = pipeline("""zero-shot-classification""", model="""roberta-large-mnli""", framework="""tf""") __lowerCAmelCase = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""]) self.assertEqual( nested_simplify(_lowercase), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.976, 0.015, 0.009], }, ) __lowerCAmelCase = zero_shot_classifier( """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks""" """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder""" """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based""" """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two""" """ machine translation tasks show these models to be superior in quality while being more parallelizable""" """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014""" """ English-to-German translation task, improving over the existing best results, including ensembles by""" """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new""" """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small""" """ fraction of the training costs of the best models from the literature. We show that the Transformer""" """ generalizes well to other tasks by applying it successfully to English constituency parsing both with""" """ large and limited training data.""", candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""], multi_label=_lowercase, ) self.assertEqual( nested_simplify(_lowercase), { """sequence""": ( """The dominant sequence transduction models are based on complex recurrent or convolutional neural""" """ networks in an encoder-decoder configuration. The best performing models also connect the""" """ encoder and decoder through an attention mechanism. We propose a new simple network""" """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence""" """ and convolutions entirely. Experiments on two machine translation tasks show these models to be""" """ superior in quality while being more parallelizable and requiring significantly less time to""" """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,""" """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014""" """ English-to-French translation task, our model establishes a new single-model state-of-the-art""" """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training""" """ costs of the best models from the literature. We show that the Transformer generalizes well to""" """ other tasks by applying it successfully to English constituency parsing both with large and""" """ limited training data.""" ), """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""], """scores""": [0.817, 0.713, 0.018, 0.018], }, )
334
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __A : Tuple = False __A : Optional[int] = True __A : Optional[Any] = False if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument( "--repo_path", default=None, type=str, required=True, help="The config json file corresponding to the architecture.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") __A : List[str] = parser.parse_args() __A : List[Any] = { "image_size": "sample_size", "num_res_blocks": "layers_per_block", "block_channels": "block_out_channels", "down_blocks": "down_block_types", "up_blocks": "up_block_types", "downscale_freq_shift": "freq_shift", "resnet_num_groups": "norm_num_groups", "resnet_act_fn": "act_fn", "resnet_eps": "norm_eps", "num_head_channels": "attention_head_dim", } __A : Optional[int] = { "time_steps": "time_proj", "mid": "mid_block", "downsample_blocks": "down_blocks", "upsample_blocks": "up_blocks", } __A : List[str] = "" if has_file(args.repo_path, "config.json") else "unet" with open(os.path.join(args.repo_path, subfolder, "config.json"), "r", encoding="utf-8") as reader: __A : List[str] = reader.read() __A : int = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, "config.json"): __A : List[str] = UNetaDModel(**config) else: __A : Dict = UNetaDConditionModel if "ldm-text2im-large-256" in args.repo_path else UNetaDModel __A : Optional[int] = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __A : List[Any] = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __A : Optional[Any] = config[key] del config[key] __A : Dict = [k.replace("UNetRes", "") for k in config["down_block_types"]] __A : Tuple = [k.replace("UNetRes", "") for k in config["up_block_types"]] if do_only_weights: __A : Dict = torch.load(os.path.join(args.repo_path, subfolder, "diffusion_pytorch_model.bin")) __A : Tuple = {} for param_key, param_value in state_dict.items(): if param_key.endswith(".op.bias") or param_key.endswith(".op.weight"): continue __A : Dict = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split(".")[0] == key: __A : List[Any] = param_value __A : Optional[Any] = True if not has_changed: __A : List[Any] = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
334
1
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean lowercase = 0 lowercase = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right lowercase = tuple[int, int] class __lowercase : '''simple docstring''' def __init__( self : Optional[int] , _a : int , _a : int , _a : int , _a : int , _a : int , _a : Node | None , ): UpperCamelCase__ = pos_x UpperCamelCase__ = pos_y UpperCamelCase__ = (pos_y, pos_x) UpperCamelCase__ = goal_x UpperCamelCase__ = goal_y UpperCamelCase__ = g_cost UpperCamelCase__ = parent UpperCamelCase__ = self.calculate_heuristic() UpperCamelCase__ = self.g_cost + self.h_cost def A_ ( self : List[Any] ): UpperCamelCase__ = self.pos_x - self.goal_x UpperCamelCase__ = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(_a ) + abs(_a ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[str] , _a : Node ): return self.f_cost < other.f_cost class __lowercase : '''simple docstring''' def __init__( self : List[Any] , _a : TPosition , _a : TPosition ): UpperCamelCase__ = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _a ) UpperCamelCase__ = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99_999 , _a ) UpperCamelCase__ = [self.start] UpperCamelCase__ = [] UpperCamelCase__ = False def A_ ( self : Any ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() UpperCamelCase__ = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(_a ) self.closed_nodes.append(_a ) UpperCamelCase__ = self.get_successors(_a ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_a ) else: # retrieve the best current path UpperCamelCase__ = self.open_nodes.pop(self.open_nodes.index(_a ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_a ) else: self.open_nodes.append(_a ) return [self.start.pos] def A_ ( self : Dict , _a : Node ): UpperCamelCase__ = [] for action in delta: UpperCamelCase__ = parent.pos_x + action[1] UpperCamelCase__ = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_a ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _a , _a , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _a , ) ) return successors def A_ ( self : List[str] , _a : Node | None ): UpperCamelCase__ = node UpperCamelCase__ = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) UpperCamelCase__ = current_node.parent path.reverse() return path class __lowercase : '''simple docstring''' def __init__( self : List[str] , _a : TPosition , _a : TPosition ): UpperCamelCase__ = AStar(_a , _a ) UpperCamelCase__ = AStar(_a , _a ) UpperCamelCase__ = False def A_ ( self : Tuple ): while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() UpperCamelCase__ = self.fwd_astar.open_nodes.pop(0 ) UpperCamelCase__ = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( _a , _a ) self.fwd_astar.closed_nodes.append(_a ) self.bwd_astar.closed_nodes.append(_a ) UpperCamelCase__ = current_bwd_node UpperCamelCase__ = current_fwd_node UpperCamelCase__ = { self.fwd_astar: self.fwd_astar.get_successors(_a ), self.bwd_astar: self.bwd_astar.get_successors(_a ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(_a ) else: # retrieve the best current path UpperCamelCase__ = astar.open_nodes.pop( astar.open_nodes.index(_a ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(_a ) else: astar.open_nodes.append(_a ) return [self.fwd_astar.start.pos] def A_ ( self : Any , _a : Node , _a : Node ): UpperCamelCase__ = self.fwd_astar.retrace_path(_a ) UpperCamelCase__ = self.bwd_astar.retrace_path(_a ) bwd_path.pop() bwd_path.reverse() UpperCamelCase__ = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] lowercase = (0, 0) lowercase = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) lowercase = time.time() lowercase = AStar(init, goal) lowercase = a_star.search() lowercase = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') lowercase = time.time() lowercase = BidirectionalAStar(init, goal) lowercase = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
240
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def lowerCamelCase_ ( UpperCamelCase__ : Dataset, UpperCamelCase__ : Dict[str, str] ): '''simple docstring''' UpperCamelCase__ = args.log_outputs UpperCamelCase__ = '''_'''.join(args.dataset.split('''/''' ) + [args.config, args.split] ) # load metric UpperCamelCase__ = load_metric('''wer''' ) UpperCamelCase__ = load_metric('''cer''' ) # compute metrics UpperCamelCase__ = wer.compute(references=result['''target'''], predictions=result['''prediction'''] ) UpperCamelCase__ = cer.compute(references=result['''target'''], predictions=result['''prediction'''] ) # print & log results UpperCamelCase__ = F"""WER: {wer_result}\nCER: {cer_result}""" print(UpperCamelCase__ ) with open(F"""{dataset_id}_eval_results.txt""", '''w''' ) as f: f.write(UpperCamelCase__ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase__ = F"""log_{dataset_id}_predictions.txt""" UpperCamelCase__ = F"""log_{dataset_id}_targets.txt""" with open(UpperCamelCase__, '''w''' ) as p, open(UpperCamelCase__, '''w''' ) as t: # mapping function to write output def write_to_file(UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Tuple ): p.write(F"""{i}""" + '''\n''' ) p.write(batch['''prediction'''] + '''\n''' ) t.write(F"""{i}""" + '''\n''' ) t.write(batch['''target'''] + '''\n''' ) result.map(UpperCamelCase__, with_indices=UpperCamelCase__ ) def lowerCamelCase_ ( UpperCamelCase__ : str ): '''simple docstring''' UpperCamelCase__ = '''[,?.!\-\;\:"“%‘”�—’…–]''' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase__ = re.sub(UpperCamelCase__, '''''', text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase__ = ['''\n\n''', '''\n''', ''' ''', ''' '''] for t in token_sequences_to_ignore: UpperCamelCase__ = ''' '''.join(text.split(UpperCamelCase__ ) ) return text def lowerCamelCase_ ( UpperCamelCase__ : Tuple ): '''simple docstring''' UpperCamelCase__ = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=UpperCamelCase__ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase__ = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase__ = feature_extractor.sampling_rate # resample audio UpperCamelCase__ = dataset.cast_column('''audio''', Audio(sampling_rate=UpperCamelCase__ ) ) # load eval pipeline if args.device is None: UpperCamelCase__ = 0 if torch.cuda.is_available() else -1 UpperCamelCase__ = pipeline('''automatic-speech-recognition''', model=args.model_id, device=args.device ) # map function to decode audio def map_to_pred(UpperCamelCase__ : Any ): UpperCamelCase__ = asr( batch['''audio''']['''array'''], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s ) UpperCamelCase__ = prediction['''text'''] UpperCamelCase__ = normalize_text(batch['''sentence'''] ) return batch # run inference on all examples UpperCamelCase__ = dataset.map(UpperCamelCase__, remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(UpperCamelCase__, UpperCamelCase__ ) if __name__ == "__main__": lowercase = argparse.ArgumentParser() parser.add_argument( """--model_id""", type=str, required=True, help="""Model identifier. Should be loadable with 🤗 Transformers""" ) parser.add_argument( """--dataset""", type=str, required=True, help="""Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets""", ) parser.add_argument( """--config""", type=str, required=True, help="""Config of the dataset. *E.g.* `'en'` for Common Voice""" ) parser.add_argument("""--split""", type=str, required=True, help="""Split of the dataset. *E.g.* `'test'`""") parser.add_argument( """--chunk_length_s""", type=float, default=None, help="""Chunk length in seconds. Defaults to 5 seconds.""" ) parser.add_argument( """--stride_length_s""", type=float, default=None, help="""Stride of the audio chunks. Defaults to 1 second.""" ) parser.add_argument( """--log_outputs""", action="""store_true""", help="""If defined, write outputs to log file for analysis.""" ) parser.add_argument( """--device""", type=int, default=None, help="""The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.""", ) lowercase = parser.parse_args() main(args)
240
1
"""simple docstring""" from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run __a = True except (ImportError, AttributeError): __a = object def A_ ( *_lowercase, **_lowercase ): '''simple docstring''' pass __a = False __a = logging.get_logger("transformers-cli/serving") def A_ ( _lowercase ): '''simple docstring''' snake_case_ :List[Any] = pipeline( task=args.task, model=args.model if args.model else None, config=args.config, tokenizer=args.tokenizer, device=args.device, ) return ServeCommand(_lowercase, args.host, args.port, args.workers ) class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' _A : dict class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' _A : List[str] _A : Optional[List[int]] class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' _A : str class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' _A : Any class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' @staticmethod def lowerCAmelCase_ ( snake_case: ArgumentParser ) -> Union[str, Any]: snake_case_ :List[Any] = parser.add_parser( """serve""" , help="""CLI tool to run inference requests through REST and GraphQL endpoints.""" ) serve_parser.add_argument( """--task""" , type=snake_case , choices=get_supported_tasks() , help="""The task to run the pipeline on""" , ) serve_parser.add_argument("""--host""" , type=snake_case , default="""localhost""" , help="""Interface the server will listen on.""" ) serve_parser.add_argument("""--port""" , type=snake_case , default=8_888 , help="""Port the serving will listen to.""" ) serve_parser.add_argument("""--workers""" , type=snake_case , default=1 , help="""Number of http workers""" ) serve_parser.add_argument("""--model""" , type=snake_case , help="""Model's name or path to stored model.""" ) serve_parser.add_argument("""--config""" , type=snake_case , help="""Model's config name or path to stored model.""" ) serve_parser.add_argument("""--tokenizer""" , type=snake_case , help="""Tokenizer name to use.""" ) serve_parser.add_argument( """--device""" , type=snake_case , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) serve_parser.set_defaults(func=snake_case ) def __init__( self: Optional[int] , snake_case: Pipeline , snake_case: str , snake_case: int , snake_case: int ) -> Tuple: snake_case_ :Optional[Any] = pipeline snake_case_ :List[Any] = host snake_case_ :int = port snake_case_ :Dict = workers if not _serve_dependencies_installed: raise RuntimeError( """Using serve command requires FastAPI and uvicorn. """ """Please install transformers with [serving]: pip install \"transformers[serving]\".""" """Or install FastAPI and uvicorn separately.""" ) else: logger.info(f"""Serving model over {host}:{port}""" ) snake_case_ :int = FastAPI( routes=[ APIRoute( """/""" , self.model_info , response_model=snake_case , response_class=snake_case , methods=["""GET"""] , ), APIRoute( """/tokenize""" , self.tokenize , response_model=snake_case , response_class=snake_case , methods=["""POST"""] , ), APIRoute( """/detokenize""" , self.detokenize , response_model=snake_case , response_class=snake_case , methods=["""POST"""] , ), APIRoute( """/forward""" , self.forward , response_model=snake_case , response_class=snake_case , methods=["""POST"""] , ), ] , timeout=600 , ) def lowerCAmelCase_ ( self: str ) -> List[str]: run(self._app , host=self.host , port=self.port , workers=self.workers ) def lowerCAmelCase_ ( self: Union[str, Any] ) -> List[str]: return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def lowerCAmelCase_ ( self: str , snake_case: str = Body(snake_case , embed=snake_case ) , snake_case: bool = Body(snake_case , embed=snake_case ) ) -> Dict: try: snake_case_ :Any = self._pipeline.tokenizer.tokenize(snake_case ) if return_ids: snake_case_ :str = self._pipeline.tokenizer.convert_tokens_to_ids(snake_case ) return ServeTokenizeResult(tokens=snake_case , tokens_ids=snake_case ) else: return ServeTokenizeResult(tokens=snake_case ) except Exception as e: raise HTTPException(status_code=500 , detail={"""model""": """""", """error""": str(snake_case )} ) def lowerCAmelCase_ ( self: List[Any] , snake_case: List[int] = Body(snake_case , embed=snake_case ) , snake_case: bool = Body(snake_case , embed=snake_case ) , snake_case: bool = Body(snake_case , embed=snake_case ) , ) -> str: try: snake_case_ :Optional[Any] = self._pipeline.tokenizer.decode(snake_case , snake_case , snake_case ) return ServeDeTokenizeResult(model="""""" , text=snake_case ) except Exception as e: raise HTTPException(status_code=500 , detail={"""model""": """""", """error""": str(snake_case )} ) async def lowerCAmelCase_ ( self: str , snake_case: List[str]=Body(snake_case , embed=snake_case ) ) -> int: # Check we don't have empty string if len(snake_case ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model snake_case_ :List[str] = self._pipeline(snake_case ) return ServeForwardResult(output=snake_case ) except Exception as e: raise HTTPException(500 , {"""error""": str(snake_case )} )
310
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class lowerCamelCase : '''simple docstring''' def __init__( self: Any , snake_case: Dict=2 , snake_case: Union[str, Any]=3 , snake_case: Dict=64 , snake_case: Union[str, Any]=None ) -> Union[str, Any]: snake_case_ :List[Any] = np.random.default_rng(snake_case ) snake_case_ :Optional[Any] = length snake_case_ :str = rng.normal(size=(length,) ).astype(np.floataa ) snake_case_ :Optional[int] = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self: Any ) -> Union[str, Any]: return self.length def __getitem__( self: Optional[int] , snake_case: Union[str, Any] ) -> Optional[Any]: return {"x": self.x[i], "y": self.y[i]} class lowerCamelCase ( torch.nn.Module ): '''simple docstring''' def __init__( self: int , snake_case: Optional[Any]=0 , snake_case: Tuple=0 , snake_case: List[Any]=False ) -> Optional[int]: super().__init__() snake_case_ :str = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) snake_case_ :Any = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) snake_case_ :Tuple = True def lowerCAmelCase_ ( self: Optional[Any] , snake_case: Optional[Any]=None ) -> List[str]: if self.first_batch: print(f"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) snake_case_ :Union[str, Any] = False return x * self.a[0] + self.b[0] class lowerCamelCase ( torch.nn.Module ): '''simple docstring''' def __init__( self: str , snake_case: List[Any]=0 , snake_case: Tuple=0 , snake_case: List[str]=False ) -> int: super().__init__() snake_case_ :int = torch.nn.Parameter(torch.tensor(snake_case ).float() ) snake_case_ :List[str] = torch.nn.Parameter(torch.tensor(snake_case ).float() ) snake_case_ :List[Any] = True def lowerCAmelCase_ ( self: Tuple , snake_case: Optional[int]=None ) -> Union[str, Any]: if self.first_batch: print(f"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) snake_case_ :List[str] = False return x * self.a + self.b def A_ ( _lowercase, _lowercase = 16 ): '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer snake_case_ :Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) snake_case_ :Optional[int] = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} snake_case_ :Union[str, Any] = load_dataset("""csv""", data_files=_lowercase ) snake_case_ :List[str] = datasets["""train"""].unique("""label""" ) snake_case_ :Any = {v: i for i, v in enumerate(_lowercase )} def tokenize_function(_lowercase ): # max_length=None => use the model max length (it's actually the default) snake_case_ :Dict = tokenizer( examples["""sentence1"""], examples["""sentence2"""], truncation=_lowercase, max_length=_lowercase, padding="""max_length""" ) if "label" in examples: snake_case_ :Union[str, Any] = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset snake_case_ :Any = datasets.map( _lowercase, batched=_lowercase, remove_columns=["""sentence1""", """sentence2""", """label"""], ) def collate_fn(_lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_lowercase, padding="""max_length""", max_length=128, return_tensors="""pt""" ) return tokenizer.pad(_lowercase, padding="""longest""", return_tensors="""pt""" ) # Instantiate dataloaders. snake_case_ :str = DataLoader(tokenized_datasets["""train"""], shuffle=_lowercase, collate_fn=_lowercase, batch_size=2 ) snake_case_ :Any = DataLoader(tokenized_datasets["""validation"""], shuffle=_lowercase, collate_fn=_lowercase, batch_size=1 ) return train_dataloader, eval_dataloader
310
1
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline A_ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class _lowerCAmelCase( UpperCamelCase_ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase ): super().__init__() self.register_modules(unet=a__ , scheduler=a__ ) @torch.no_grad() def __call__( self , _lowerCamelCase = 1 , _lowerCamelCase = 1_0_0 , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = True , ): if audio_length_in_s is None: UpperCamelCase_: Tuple = self.unet.config.sample_size / self.unet.config.sample_rate UpperCamelCase_: Tuple = audio_length_in_s * self.unet.config.sample_rate UpperCamelCase_: Optional[Any] = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f'''{audio_length_in_s} is too small. Make sure it\'s bigger or equal to''' f''' {3 * down_scale_factor / self.unet.config.sample_rate}.''' ) UpperCamelCase_: Union[str, Any] = int(a__ ) if sample_size % down_scale_factor != 0: UpperCamelCase_: str = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f'''{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled''' f''' by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising''' ' process.' ) UpperCamelCase_: int = int(a__ ) UpperCamelCase_: Tuple = next(iter(self.unet.parameters() ) ).dtype UpperCamelCase_: Any = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(a__ , a__ ) and len(a__ ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(a__ )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_: Optional[int] = randn_tensor(a__ , generator=a__ , device=self.device , dtype=a__ ) # set step values self.scheduler.set_timesteps(a__ , device=audio.device ) UpperCamelCase_: int = self.scheduler.timesteps.to(a__ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCamelCase_: Dict = self.unet(a__ , a__ ).sample # 2. compute previous image: x_t -> t_t-1 UpperCamelCase_: int = self.scheduler.step(a__ , a__ , a__ ).prev_sample UpperCamelCase_: List[str] = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCamelCase_: Tuple = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=a__ )
57
'''simple docstring''' import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin snake_case = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class lowerCAmelCase ( UpperCamelCase_ , unittest.TestCase ): A_ : List[str] = AlbertTokenizer A_ : List[Any] = AlbertTokenizerFast A_ : List[str] = True A_ : Any = True A_ : List[Any] = True def _A ( self : Optional[int] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ : int = AlbertTokenizer(a__ ) tokenizer.save_pretrained(self.tmpdirname ) def _A ( self : Tuple , a__ : Optional[Any] ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = "this is a test" lowerCAmelCase__ : Optional[Any] = "this is a test" return input_text, output_text def _A ( self : Optional[int] ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = "<pad>" lowerCAmelCase__ : Dict = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def _A ( self : Tuple ): '''simple docstring''' lowerCAmelCase__ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "▁eloquent" ) self.assertEqual(len(a__ ) , 3_0000 ) def _A ( self : Optional[int] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 3_0000 ) def _A ( self : int ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ : List[Any] = self.get_tokenizer() lowerCAmelCase__ : Optional[int] = self.get_rust_tokenizer() lowerCAmelCase__ : List[str] = "I was born in 92000, and this is falsé." lowerCAmelCase__ : Dict = tokenizer.tokenize(a__ ) lowerCAmelCase__ : str = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) lowerCAmelCase__ : List[Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) lowerCAmelCase__ : Tuple = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) lowerCAmelCase__ : Optional[int] = self.get_rust_tokenizer() lowerCAmelCase__ : str = tokenizer.encode(a__ ) lowerCAmelCase__ : Optional[int] = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) def _A ( self : Optional[int] ): '''simple docstring''' lowerCAmelCase__ : List[Any] = AlbertTokenizer(a__ , keep_accents=a__ ) lowerCAmelCase__ : Optional[Any] = tokenizer.tokenize("This is a test" ) self.assertListEqual(a__ , ["▁this", "▁is", "▁a", "▁test"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , [48, 25, 21, 1289] ) lowerCAmelCase__ : Optional[int] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( a__ , ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "."] ) lowerCAmelCase__ : Tuple = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual(a__ , [31, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] ) lowerCAmelCase__ : Optional[int] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "."] , ) def _A ( self : List[str] ): '''simple docstring''' lowerCAmelCase__ : Tuple = AlbertTokenizer(a__ ) lowerCAmelCase__ : List[str] = tokenizer.encode("sequence builders" ) lowerCAmelCase__ : Optional[int] = tokenizer.encode("multi-sequence build" ) lowerCAmelCase__ : Tuple = tokenizer.build_inputs_with_special_tokens(a__ ) lowerCAmelCase__ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(a__ , a__ ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def _A ( self : List[str] ): '''simple docstring''' lowerCAmelCase__ : Any = {"attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "input_ids": [[2, 2_1970, 13, 5, 6092, 167, 28, 7103, 2153, 673, 8, 7028, 1_2051, 18, 17, 7103, 2153, 673, 8, 3515, 1_8684, 8, 4461, 6, 1927, 297, 8, 1_2060, 2607, 18, 13, 5, 4461, 15, 1_0538, 38, 8, 135, 15, 822, 58, 15, 993, 1_0363, 15, 1460, 8005, 4461, 15, 993, 255, 2328, 9, 9, 9, 6, 26, 1112, 816, 3260, 13, 5, 103, 2377, 6, 17, 1112, 816, 2782, 13, 5, 103, 1_0641, 6, 29, 84, 2512, 2430, 782, 1_8684, 2761, 19, 808, 2430, 2556, 17, 855, 1480, 9477, 4091, 128, 1_1712, 15, 7103, 2153, 673, 17, 2_4883, 9990, 9, 3], [2, 1_1502, 25, 1006, 20, 782, 8, 1_1809, 855, 1732, 1_9393, 1_8667, 37, 367, 2_1018, 69, 1854, 34, 1_1860, 1_9124, 27, 156, 225, 17, 193, 4141, 19, 65, 9124, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2231, 886, 2385, 1_7659, 84, 14, 1_6792, 1952, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="albert-base-v2" , revision="6b6560eaf5ff2e250b00c50f380c5389a9c2d82e" , )
378
0
"""simple docstring""" from scipy.stats import spearmanr import datasets lowercase_ = '\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n' lowercase_ = '\nArgs:\n predictions (`List[float]`): Predicted labels, as returned by a model.\n references (`List[float]`): Ground truth labels.\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n only the spearmanr score. Defaults to `False`.\nReturns:\n spearmanr (`float`): Spearman correlation coefficient.\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n Example 1:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n >>> print(results)\n {\'spearmanr\': -0.7}\n\n Example 2:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n ... predictions=[10, 9, 2.5, 6, 4],\n ... return_pvalue=True)\n >>> print(results[\'spearmanr\'])\n -0.7\n >>> print(round(results[\'spearmanr_pvalue\'], 2))\n 0.19\n' lowercase_ = R'\\n@book{kokoska2000crc,\n title={CRC standard probability and statistics tables and formulae},\n author={Kokoska, Stephen and Zwillinger, Daniel},\n year={2000},\n publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\n journal = {Nature Methods},\n year = {2020},\n volume = {17},\n pages = {261--272},\n adsurl = {https://rdcu.be/b08Wh},\n doi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ), reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html'''], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : List[Any], _lowerCamelCase : str, _lowerCamelCase : Dict=False ): '''simple docstring''' __A = spearmanr(_lowerCamelCase, _lowerCamelCase ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
721
"""simple docstring""" import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = LxmertTokenizer A_ : Any = LxmertTokenizerFast A_ : Optional[int] = True A_ : int = True def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' super().setUp() __A = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __A = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file, '''w''', encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Any ): '''simple docstring''' __A = '''UNwant\u00E9d,running''' __A = '''unwanted, running''' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = self.tokenizer_class(self.vocab_file ) __A = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_lowerCamelCase, ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ), [7, 4, 5, 10, 8, 9] ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' if not self.test_rust_tokenizer: return __A = self.get_tokenizer() __A = self.get_rust_tokenizer() __A = '''I was born in 92000, and this is falsé.''' __A = tokenizer.tokenize(_lowerCamelCase ) __A = rust_tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) __A = tokenizer.encode(_lowerCamelCase, add_special_tokens=_lowerCamelCase ) __A = rust_tokenizer.encode(_lowerCamelCase, add_special_tokens=_lowerCamelCase ) self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) __A = self.get_rust_tokenizer() __A = tokenizer.encode(_lowerCamelCase ) __A = rust_tokenizer.encode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase, _lowerCamelCase )
215
0
"""simple docstring""" import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] , *__lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : int=None , **__lowerCamelCase : str ): """simple docstring""" super().__init__(*__lowerCamelCase , **__lowerCamelCase ) _snake_case = eval_examples _snake_case = post_process_function def __UpperCAmelCase ( self : int , __lowerCamelCase : Optional[Dataset] = None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[List[str]] = None , __lowerCamelCase : str = "eval" , **__lowerCamelCase : int , ): """simple docstring""" _snake_case = gen_kwargs.copy() _snake_case = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) _snake_case = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) _snake_case = gen_kwargs _snake_case = self.eval_dataset if eval_dataset is None else eval_dataset _snake_case = self.get_eval_dataloader(__lowerCamelCase ) _snake_case = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _snake_case = self.compute_metrics _snake_case = None _snake_case = time.time() _snake_case = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _snake_case = eval_loop( __lowerCamelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCamelCase , metric_key_prefix=__lowerCamelCase , ) finally: _snake_case = compute_metrics _snake_case = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __lowerCamelCase , __lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _snake_case = self.post_process_function(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _snake_case = self.compute_metrics(__lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): _snake_case = metrics.pop(__lowerCamelCase ) metrics.update(output.metrics ) else: _snake_case = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _snake_case = self.callback_handler.on_evaluate(self.args , self.state , self.control , __lowerCamelCase ) return metrics def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict=None , __lowerCamelCase : str = "test" , **__lowerCamelCase : int ): """simple docstring""" _snake_case = gen_kwargs.copy() _snake_case = self.get_test_dataloader(__lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. _snake_case = self.compute_metrics _snake_case = None _snake_case = time.time() _snake_case = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _snake_case = eval_loop( __lowerCamelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCamelCase , metric_key_prefix=__lowerCamelCase , ) finally: _snake_case = compute_metrics _snake_case = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __lowerCamelCase , __lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _snake_case = self.post_process_function(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , '''predict''' ) _snake_case = self.compute_metrics(__lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): _snake_case = metrics.pop(__lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__lowerCamelCase )
103
'''simple docstring''' def lowercase__( _UpperCamelCase : int = 100 )-> int: """simple docstring""" _UpperCamelCase = set() _UpperCamelCase = 0 _UpperCamelCase = n + 1 # maximum limit for a in range(2 , _UpperCamelCase ): for b in range(2 , _UpperCamelCase ): _UpperCamelCase = a**b # calculates the current power collect_powers.add(_UpperCamelCase ) # adds the result to the set return len(_UpperCamelCase ) if __name__ == "__main__": print('''Number of terms ''', solution(int(str(input()).strip())))
138
0
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer _UpperCamelCase : Dict = logging.get_logger(__name__) _UpperCamelCase : Union[str, Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } _UpperCamelCase : str = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } _UpperCamelCase : int = { 'facebook/blenderbot_small-90M': 5_1_2, } class a ( a_ ): UpperCAmelCase_ : Optional[Any] =VOCAB_FILES_NAMES UpperCAmelCase_ : Dict =PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ : int =BlenderbotSmallTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="<|endoftext|>" , _lowerCamelCase="<|endoftext|>" , _lowerCamelCase="<|endoftext|>" , _lowerCamelCase=False , _lowerCamelCase=True , **_lowerCamelCase , ): super().__init__( ByteLevelBPETokenizer( vocab=_lowerCamelCase , merges=_lowerCamelCase , add_prefix_space=_lowerCamelCase , trim_offsets=_lowerCamelCase , ) , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , **_lowerCamelCase , ) lowercase = add_prefix_space def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase=None ): lowercase = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase = None ): lowercase = [self.sep_token_id] lowercase = [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]
134
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) _UpperCamelCase : str = logging.get_logger(__name__) _UpperCamelCase : Dict = OrderedDict( [ ('audio-spectrogram-transformer', 'ASTFeatureExtractor'), ('beit', 'BeitFeatureExtractor'), ('chinese_clip', 'ChineseCLIPFeatureExtractor'), ('clap', 'ClapFeatureExtractor'), ('clip', 'CLIPFeatureExtractor'), ('clipseg', 'ViTFeatureExtractor'), ('conditional_detr', 'ConditionalDetrFeatureExtractor'), ('convnext', 'ConvNextFeatureExtractor'), ('cvt', 'ConvNextFeatureExtractor'), ('data2vec-audio', 'Wav2Vec2FeatureExtractor'), ('data2vec-vision', 'BeitFeatureExtractor'), ('deformable_detr', 'DeformableDetrFeatureExtractor'), ('deit', 'DeiTFeatureExtractor'), ('detr', 'DetrFeatureExtractor'), ('dinat', 'ViTFeatureExtractor'), ('donut-swin', 'DonutFeatureExtractor'), ('dpt', 'DPTFeatureExtractor'), ('encodec', 'EncodecFeatureExtractor'), ('flava', 'FlavaFeatureExtractor'), ('glpn', 'GLPNFeatureExtractor'), ('groupvit', 'CLIPFeatureExtractor'), ('hubert', 'Wav2Vec2FeatureExtractor'), ('imagegpt', 'ImageGPTFeatureExtractor'), ('layoutlmv2', 'LayoutLMv2FeatureExtractor'), ('layoutlmv3', 'LayoutLMv3FeatureExtractor'), ('levit', 'LevitFeatureExtractor'), ('maskformer', 'MaskFormerFeatureExtractor'), ('mctct', 'MCTCTFeatureExtractor'), ('mobilenet_v1', 'MobileNetV1FeatureExtractor'), ('mobilenet_v2', 'MobileNetV2FeatureExtractor'), ('mobilevit', 'MobileViTFeatureExtractor'), ('nat', 'ViTFeatureExtractor'), ('owlvit', 'OwlViTFeatureExtractor'), ('perceiver', 'PerceiverFeatureExtractor'), ('poolformer', 'PoolFormerFeatureExtractor'), ('regnet', 'ConvNextFeatureExtractor'), ('resnet', 'ConvNextFeatureExtractor'), ('segformer', 'SegformerFeatureExtractor'), ('sew', 'Wav2Vec2FeatureExtractor'), ('sew-d', 'Wav2Vec2FeatureExtractor'), ('speech_to_text', 'Speech2TextFeatureExtractor'), ('speecht5', 'SpeechT5FeatureExtractor'), ('swiftformer', 'ViTFeatureExtractor'), ('swin', 'ViTFeatureExtractor'), ('swinv2', 'ViTFeatureExtractor'), ('table-transformer', 'DetrFeatureExtractor'), ('timesformer', 'VideoMAEFeatureExtractor'), ('tvlt', 'TvltFeatureExtractor'), ('unispeech', 'Wav2Vec2FeatureExtractor'), ('unispeech-sat', 'Wav2Vec2FeatureExtractor'), ('van', 'ConvNextFeatureExtractor'), ('videomae', 'VideoMAEFeatureExtractor'), ('vilt', 'ViltFeatureExtractor'), ('vit', 'ViTFeatureExtractor'), ('vit_mae', 'ViTFeatureExtractor'), ('vit_msn', 'ViTFeatureExtractor'), ('wav2vec2', 'Wav2Vec2FeatureExtractor'), ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'), ('wavlm', 'Wav2Vec2FeatureExtractor'), ('whisper', 'WhisperFeatureExtractor'), ('xclip', 'CLIPFeatureExtractor'), ('yolos', 'YolosFeatureExtractor'), ] ) _UpperCamelCase : str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _SCREAMING_SNAKE_CASE ( __snake_case : str ): '''simple docstring''' for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: lowercase = model_type_to_module_name(__snake_case ) lowercase = importlib.import_module(f'.{module_name}' , 'transformers.models' ) try: return getattr(__snake_case , __snake_case ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(__snake_case , '__name__' , __snake_case ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. lowercase = importlib.import_module('transformers' ) if hasattr(__snake_case , __snake_case ): return getattr(__snake_case , __snake_case ) return None def _SCREAMING_SNAKE_CASE ( __snake_case : Union[str, os.PathLike] , __snake_case : Optional[Union[str, os.PathLike]] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[Dict[str, str]] = None , __snake_case : Optional[Union[bool, str]] = None , __snake_case : Optional[str] = None , __snake_case : bool = False , **__snake_case : int , ): '''simple docstring''' lowercase = get_file_from_repo( __snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , ) if resolved_config_file is None: logger.info( 'Could not locate the feature extractor configuration file, will try to use the model config instead.' ) return {} with open(__snake_case , encoding='utf-8' ) as reader: return json.load(__snake_case ) class a : def __init__( self ): raise EnvironmentError( 'AutoFeatureExtractor is designed to be instantiated ' 'using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(_lowerCamelCase ) def UpperCamelCase_ ( cls , _lowerCamelCase , **_lowerCamelCase ): lowercase = kwargs.pop('config' , _lowerCamelCase ) lowercase = kwargs.pop('trust_remote_code' , _lowerCamelCase ) lowercase = True lowercase , lowercase = FeatureExtractionMixin.get_feature_extractor_dict(_lowerCamelCase , **_lowerCamelCase ) lowercase = config_dict.get('feature_extractor_type' , _lowerCamelCase ) lowercase = None if "AutoFeatureExtractor" in config_dict.get('auto_map' , {} ): lowercase = config_dict['auto_map']['AutoFeatureExtractor'] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(_lowerCamelCase , _lowerCamelCase ): lowercase = AutoConfig.from_pretrained(_lowerCamelCase , **_lowerCamelCase ) # It could be in `config.feature_extractor_type`` lowercase = getattr(_lowerCamelCase , 'feature_extractor_type' , _lowerCamelCase ) if hasattr(_lowerCamelCase , 'auto_map' ) and "AutoFeatureExtractor" in config.auto_map: lowercase = config.auto_map['AutoFeatureExtractor'] if feature_extractor_class is not None: lowercase = feature_extractor_class_from_name(_lowerCamelCase ) lowercase = feature_extractor_auto_map is not None lowercase = feature_extractor_class is not None or type(_lowerCamelCase ) in FEATURE_EXTRACTOR_MAPPING lowercase = resolve_trust_remote_code( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if has_remote_code and trust_remote_code: lowercase = get_class_from_dynamic_module( _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) lowercase = kwargs.pop('code_revision' , _lowerCamelCase ) if os.path.isdir(_lowerCamelCase ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(_lowerCamelCase , **_lowerCamelCase ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(_lowerCamelCase , **_lowerCamelCase ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(_lowerCamelCase ) in FEATURE_EXTRACTOR_MAPPING: lowercase = FEATURE_EXTRACTOR_MAPPING[type(_lowerCamelCase )] return feature_extractor_class.from_dict(_lowerCamelCase , **_lowerCamelCase ) raise ValueError( F'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ' F'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ' F'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}' ) @staticmethod def UpperCamelCase_ ( _lowerCamelCase , _lowerCamelCase ): FEATURE_EXTRACTOR_MAPPING.register(_lowerCamelCase , _lowerCamelCase )
134
1
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin _lowerCamelCase = 1e-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class a : '''simple docstring''' def __init__( self : Optional[Any] , __snake_case : int , __snake_case : List[str]=16 , __snake_case : Union[str, Any]=13 , __snake_case : int=7 , __snake_case : Any=14 , __snake_case : Optional[Any]=10 , __snake_case : Tuple=19 , __snake_case : str=5 , __snake_case : Optional[Any]=4 , __snake_case : str=True , __snake_case : Optional[Any]=16 , __snake_case : Dict=2 , __snake_case : Optional[Any]=4 , __snake_case : Dict=4 , __snake_case : Optional[Any]="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : Dict=0.1 , __snake_case : Optional[int]=[1, 2, 3, 4, 5] , __snake_case : Tuple=25 , __snake_case : Any=5 , ): UpperCAmelCase_ = d_model UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = prediction_length UpperCAmelCase_ = context_length UpperCAmelCase_ = cardinality UpperCAmelCase_ = num_time_features UpperCAmelCase_ = lags_sequence UpperCAmelCase_ = embedding_dimension UpperCAmelCase_ = is_training UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_act UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = context_length UpperCAmelCase_ = prediction_length + label_length UpperCAmelCase_ = label_length UpperCAmelCase_ = moving_average UpperCAmelCase_ = autocorrelation_factor def lowerCamelCase_ ( self : List[str] ): return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def lowerCamelCase_ ( self : str , __snake_case : Tuple ): UpperCAmelCase_ = config.context_length + max(config.lags_sequence ) UpperCAmelCase_ = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) UpperCAmelCase_ = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) UpperCAmelCase_ = floats_tensor([self.batch_size, _past_length] ) UpperCAmelCase_ = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs UpperCAmelCase_ = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) UpperCAmelCase_ = floats_tensor([self.batch_size, config.prediction_length] ) UpperCAmelCase_ = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def lowerCamelCase_ ( self : Dict ): UpperCAmelCase_ = self.get_config() UpperCAmelCase_ = self.prepare_autoformer_inputs_dict(__snake_case ) return config, inputs_dict def lowerCamelCase_ ( self : Tuple ): UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_config_and_inputs() return config, inputs_dict def lowerCamelCase_ ( self : str , __snake_case : Dict , __snake_case : Tuple ): UpperCAmelCase_ = AutoformerModel(config=__snake_case ).to(__snake_case ).eval() UpperCAmelCase_ = model(**__snake_case ) UpperCAmelCase_ = outputs.encoder_last_hidden_state UpperCAmelCase_ = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = model.get_encoder() encoder.save_pretrained(__snake_case ) UpperCAmelCase_ = AutoformerEncoder.from_pretrained(__snake_case ).to(__snake_case ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = model.create_network_inputs(**__snake_case ) UpperCAmelCase_ , UpperCAmelCase_ = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) UpperCAmelCase_ = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) UpperCAmelCase_ = encoder(inputs_embeds=__snake_case )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) UpperCAmelCase_ = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) UpperCAmelCase_ = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) UpperCAmelCase_ = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) UpperCAmelCase_ = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = model.get_decoder() decoder.save_pretrained(__snake_case ) UpperCAmelCase_ = AutoformerDecoder.from_pretrained(__snake_case ).to(__snake_case ) UpperCAmelCase_ = decoder( trend=__snake_case , inputs_embeds=__snake_case , encoder_hidden_states=__snake_case , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class a ( _A , _A , unittest.TestCase ): '''simple docstring''' lowerCAmelCase : List[str] = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () lowerCAmelCase : int = (AutoformerForPrediction,) if is_torch_available() else () lowerCAmelCase : Optional[Any] = {'feature-extraction': AutoformerModel} if is_torch_available() else {} lowerCAmelCase : Optional[Any] = False lowerCAmelCase : Optional[Any] = False lowerCAmelCase : Any = False lowerCAmelCase : int = False lowerCAmelCase : List[Any] = False lowerCAmelCase : Any = False def lowerCamelCase_ ( self : Optional[Any] ): UpperCAmelCase_ = AutoformerModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__snake_case , has_text_modality=__snake_case ) def lowerCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self : Dict ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__snake_case ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__snake_case ) UpperCAmelCase_ , UpperCAmelCase_ = model_class.from_pretrained(__snake_case , output_loading_info=__snake_case ) self.assertEqual(info['''missing_keys'''] , [] ) def lowerCamelCase_ ( self : List[str] ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__snake_case ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def lowerCamelCase_ ( self : str ): pass def lowerCamelCase_ ( self : int ): UpperCAmelCase_ = inspect.signature(getattr(__snake_case , '''forward''' ) ) # The main input is the name of the argument after `self` UpperCAmelCase_ = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , __snake_case ) def lowerCamelCase_ ( self : Dict ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__snake_case ) UpperCAmelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(__snake_case )] , __snake_case ) def lowerCamelCase_ ( self : str ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ = True UpperCAmelCase_ = getattr(self.model_tester , '''seq_length''' , __snake_case ) UpperCAmelCase_ = getattr(self.model_tester , '''decoder_seq_length''' , __snake_case ) UpperCAmelCase_ = getattr(self.model_tester , '''encoder_seq_length''' , __snake_case ) UpperCAmelCase_ = getattr(self.model_tester , '''d_model''' , __snake_case ) UpperCAmelCase_ = getattr(self.model_tester , '''num_attention_heads''' , __snake_case ) UpperCAmelCase_ = d_model // num_attention_heads for model_class in self.all_model_classes: UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = True UpperCAmelCase_ = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): UpperCAmelCase_ = model(**self._prepare_for_class(__snake_case , __snake_case ) ) UpperCAmelCase_ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__snake_case ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCAmelCase_ = True UpperCAmelCase_ = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): UpperCAmelCase_ = model(**self._prepare_for_class(__snake_case , __snake_case ) ) UpperCAmelCase_ = outputs.encoder_attentions self.assertEqual(len(__snake_case ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) UpperCAmelCase_ = len(__snake_case ) UpperCAmelCase_ = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(__snake_case , __snake_case ) # decoder attentions UpperCAmelCase_ = outputs.decoder_attentions self.assertIsInstance(__snake_case , (list, tuple) ) self.assertEqual(len(__snake_case ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions UpperCAmelCase_ = outputs.cross_attentions self.assertIsInstance(__snake_case , (list, tuple) ) self.assertEqual(len(__snake_case ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine UpperCAmelCase_ = True UpperCAmelCase_ = True UpperCAmelCase_ = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): UpperCAmelCase_ = model(**self._prepare_for_class(__snake_case , __snake_case ) ) self.assertEqual(out_len + 2 , len(__snake_case ) ) UpperCAmelCase_ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__snake_case ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def lowerCamelCase_ ( self : Any ): super().test_retain_grad_hidden_states_attentions() def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Optional[Any]="train-batch.pt" ) -> List[str]: UpperCAmelCase_ = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=__UpperCamelCase , repo_type='''dataset''' ) UpperCAmelCase_ = torch.load(__UpperCamelCase , map_location=__UpperCamelCase ) return batch @require_torch @slow class a ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase_ ( self : Tuple ): UpperCAmelCase_ = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__snake_case ) UpperCAmelCase_ = prepare_batch() with torch.no_grad(): UpperCAmelCase_ = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] UpperCAmelCase_ = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , __snake_case ) UpperCAmelCase_ = torch.tensor( [[0.3_593, -1.3_398, 0.6_330], [0.2_279, 1.5_396, -0.1_792], [0.0_450, 1.3_225, -0.2_335]] , device=__snake_case ) self.assertTrue(torch.allclose(output[0, :3, :3] , __snake_case , atol=__snake_case ) ) def lowerCamelCase_ ( self : Optional[Any] ): UpperCAmelCase_ = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__snake_case ) UpperCAmelCase_ = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCAmelCase_ = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state UpperCAmelCase_ = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , __snake_case ) UpperCAmelCase_ = torch.tensor( [[-0.0_734, -0.9_036, 0.8_358], [4.7_186, 2.4_113, 1.9_581], [1.7_953, 2.3_558, 1.2_970]] , device=__snake_case ) self.assertTrue(torch.allclose(output[0, :3, :3] , __snake_case , atol=__snake_case ) ) def lowerCamelCase_ ( self : str ): UpperCAmelCase_ = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__snake_case ) UpperCAmelCase_ = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCAmelCase_ = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) UpperCAmelCase_ = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , __snake_case ) UpperCAmelCase_ = torch.tensor([3_130.6_763, 4_056.5_293, 7_053.0_786] , device=__snake_case ) UpperCAmelCase_ = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , __snake_case , rtol=1E-1 ) )
144
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class a : '''simple docstring''' lowerCAmelCase : Dict = BlenderbotSmallConfig lowerCAmelCase : Optional[Any] = {} lowerCAmelCase : str = 'gelu' def __init__( self : int , __snake_case : Any , __snake_case : str=13 , __snake_case : int=7 , __snake_case : str=True , __snake_case : List[str]=False , __snake_case : Optional[Any]=99 , __snake_case : Optional[Any]=32 , __snake_case : str=2 , __snake_case : Optional[int]=4 , __snake_case : int=37 , __snake_case : Any=0.1 , __snake_case : List[str]=0.1 , __snake_case : Tuple=20 , __snake_case : Dict=2 , __snake_case : str=1 , __snake_case : Any=0 , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = seq_length UpperCAmelCase_ = is_training UpperCAmelCase_ = use_labels UpperCAmelCase_ = vocab_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = eos_token_id UpperCAmelCase_ = pad_token_id UpperCAmelCase_ = bos_token_id def lowerCamelCase_ ( self : Optional[Any] ): UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase_ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase_ = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ = 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 , ) UpperCAmelCase_ = prepare_blenderbot_small_inputs_dict(__snake_case , __snake_case , __snake_case ) return config, inputs_dict def lowerCamelCase_ ( self : str , __snake_case : Tuple , __snake_case : Any ): UpperCAmelCase_ = TFBlenderbotSmallModel(config=__snake_case ).get_decoder() UpperCAmelCase_ = inputs_dict['''input_ids'''] UpperCAmelCase_ = input_ids[:1, :] UpperCAmelCase_ = inputs_dict['''attention_mask'''][:1, :] UpperCAmelCase_ = inputs_dict['''head_mask'''] UpperCAmelCase_ = 1 # first forward pass UpperCAmelCase_ = model(__snake_case , attention_mask=__snake_case , head_mask=__snake_case , use_cache=__snake_case ) UpperCAmelCase_ , UpperCAmelCase_ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase_ = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase_ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase_ = model(__snake_case , attention_mask=__snake_case )[0] UpperCAmelCase_ = model(__snake_case , attention_mask=__snake_case , past_key_values=__snake_case )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase_ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase_ = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase_ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__snake_case , __snake_case , rtol=1E-3 ) def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any , __UpperCamelCase : str , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any]=None , __UpperCamelCase : Optional[int]=None , __UpperCamelCase : Any=None , __UpperCamelCase : List[str]=None , __UpperCamelCase : List[Any]=None , ) -> str: if attention_mask is None: UpperCAmelCase_ = tf.cast(tf.math.not_equal(__UpperCamelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase_ = 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: UpperCAmelCase_ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase_ = 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 a ( _A , _A , unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Optional[int] = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) lowerCAmelCase : Optional[Any] = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () lowerCAmelCase : Union[str, Any] = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) lowerCAmelCase : List[Any] = True lowerCAmelCase : Tuple = False lowerCAmelCase : List[Any] = False def lowerCamelCase_ ( self : Optional[Any] ): UpperCAmelCase_ = TFBlenderbotSmallModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__snake_case ) def lowerCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self : int ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__snake_case ) @require_tokenizers @require_tf class a ( unittest.TestCase ): '''simple docstring''' lowerCAmelCase : int = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] lowerCAmelCase : Optional[Any] = 'facebook/blenderbot_small-90M' @cached_property def lowerCamelCase_ ( self : List[str] ): # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) @cached_property def lowerCamelCase_ ( self : Dict ): UpperCAmelCase_ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def lowerCamelCase_ ( self : List[str] ): UpperCAmelCase_ = self.tokenizer(self.src_text , return_tensors='''tf''' ) UpperCAmelCase_ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__snake_case , ) UpperCAmelCase_ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__snake_case )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
144
1
"""simple docstring""" import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch __lowercase = """sshleifer/bart-tiny-random""" __lowercase = """patrickvonplaten/t5-tiny-random""" @require_torch class _A ( unittest.TestCase ): """simple docstring""" @cached_property def __snake_case ( self : Dict): return AutoConfig.from_pretrained(snake_case_) def __snake_case ( self : List[str]): a : List[Any] = create_student_by_copying_alternating_layers(snake_case_ , tempfile.mkdtemp() , e=1 , d=1) self.assertEqual(student.config.num_hidden_layers , 1) def __snake_case ( self : List[str]): a : Optional[int] = create_student_by_copying_alternating_layers(snake_case_ , tempfile.mkdtemp() , e=1 , d=snake_case_) def __snake_case ( self : Union[str, Any]): a : Dict = create_student_by_copying_alternating_layers(snake_case_ , tempfile.mkdtemp() , e=1 , d=snake_case_) self.assertEqual(student.config.encoder_layers , 1) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers) def __snake_case ( self : List[str]): a : List[str] = create_student_by_copying_alternating_layers(snake_case_ , tempfile.mkdtemp() , e=1 , d=1) self.assertEqual(student.config.encoder_layers , 1) self.assertEqual(student.config.decoder_layers , 1) def __snake_case ( self : List[str]): with self.assertRaises(snake_case_): create_student_by_copying_alternating_layers(snake_case_ , tempfile.mkdtemp() , e=snake_case_ , d=snake_case_)
721
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { """facebook/s2t-small-librispeech-asr""": ( """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class _A ( _a ): """simple docstring""" UpperCAmelCase : List[Any] = """speech_to_text""" UpperCAmelCase : str = ["""past_key_values"""] UpperCAmelCase : Any = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : int , __UpperCAmelCase : List[Any]=10000 , __UpperCAmelCase : Any=12 , __UpperCAmelCase : Optional[Any]=2048 , __UpperCAmelCase : int=4 , __UpperCAmelCase : Dict=6 , __UpperCAmelCase : Optional[int]=2048 , __UpperCAmelCase : Dict=4 , __UpperCAmelCase : Any=0.0 , __UpperCAmelCase : List[Any]=0.0 , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : Union[str, Any]=256 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : List[str]=0.0 , __UpperCAmelCase : int=0.0 , __UpperCAmelCase : Union[str, Any]=0.02 , __UpperCAmelCase : Dict=2 , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Optional[Any]=1 , __UpperCAmelCase : int=0 , __UpperCAmelCase : List[Any]=2 , __UpperCAmelCase : Optional[int]=6000 , __UpperCAmelCase : List[str]=1024 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : List[Any]=(5, 5) , __UpperCAmelCase : Union[str, Any]=1024 , __UpperCAmelCase : str=80 , __UpperCAmelCase : str=1 , **__UpperCAmelCase : str , ): a : Optional[Any] = vocab_size a : Any = d_model a : List[Any] = encoder_ffn_dim a : List[Any] = encoder_layers a : List[str] = encoder_attention_heads a : Union[str, Any] = decoder_ffn_dim a : int = decoder_layers a : Any = decoder_attention_heads a : Tuple = dropout a : Any = attention_dropout a : str = activation_dropout a : Union[str, Any] = activation_function a : List[Any] = init_std a : List[Any] = encoder_layerdrop a : str = decoder_layerdrop a : str = use_cache a : List[str] = encoder_layers a : Dict = scale_embedding # scale factor will be sqrt(d_model) if True a : List[Any] = max_source_positions a : Optional[Any] = max_target_positions a : Tuple = num_conv_layers a : Optional[Any] = list(__UpperCAmelCase) a : int = conv_channels a : Dict = input_feat_per_channel a : str = input_channels if len(self.conv_kernel_sizes) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` " f'''but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes)}`, ''' f'''`config.num_conv_layers = {self.num_conv_layers}`.''') super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , decoder_start_token_id=__UpperCAmelCase , **__UpperCAmelCase , )
135
0
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch a_ = True except ImportError: a_ = False try: from torch.hub import _get_torch_home a_ = _get_torch_home() except ImportError: a_ = os.path.expanduser( os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')) ) a_ = os.path.join(torch_cache_home, 'transformers') a_ = 'https://cdn.huggingface.co' a_ = 'https://s3.amazonaws.com/models.huggingface.co/bert' a_ = '/'.join(str(Path(__file__).resolve()).split('/')[:-1]) a_ = os.path.join(PATH, 'config.yaml') a_ = os.path.join(PATH, 'attributes.txt') a_ = os.path.join(PATH, 'objects.txt') a_ = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path) a_ = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE) a_ = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE) a_ = 'pytorch_model.bin' a_ = 'config.yaml' def __lowercase ( lowerCamelCase : str=OBJECTS , lowerCamelCase : List[str]=ATTRIBUTES ): UpperCamelCase_ : str = [] with open(lowerCamelCase ) as f: for object in f.readlines(): vg_classes.append(object.split(',' )[0].lower().strip() ) UpperCamelCase_ : Union[str, Any] = [] with open(lowerCamelCase ) as f: for object in f.readlines(): vg_attrs.append(object.split(',' )[0].lower().strip() ) return vg_classes, vg_attrs def __lowercase ( lowerCamelCase : List[str] ): UpperCamelCase_ : str = OrderedDict() with open(lowerCamelCase , 'rb' ) as f: UpperCamelCase_ : Union[str, Any] = pkl.load(lowerCamelCase )['model'] for k in copy.deepcopy(list(ckp.keys() ) ): UpperCamelCase_ : Tuple = ckp.pop(lowerCamelCase ) if isinstance(lowerCamelCase , np.ndarray ): UpperCamelCase_ : int = torch.tensor(lowerCamelCase ) else: assert isinstance(lowerCamelCase , torch.tensor ), type(lowerCamelCase ) UpperCamelCase_ : Any = v return r class _lowercase : lowercase = {} def __init__( self : int , snake_case : dict , snake_case : str = "root" , snake_case : str=0 ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : Tuple = name UpperCamelCase_ : Optional[int] = level UpperCamelCase_ : Any = {} for k, v in dictionary.items(): if v is None: raise ValueError() UpperCamelCase_ : Union[str, Any] = copy.deepcopy(snake_case ) UpperCamelCase_ : str = copy.deepcopy(snake_case ) if isinstance(snake_case , snake_case ): UpperCamelCase_ : List[str] = Config(snake_case , name=snake_case , level=level + 1 ) UpperCamelCase_ : Optional[Any] = v setattr(self , snake_case , snake_case ) UpperCamelCase_ : Union[str, Any] = d def __repr__( self : Dict ) -> Tuple: """simple docstring""" return str(list((self._pointer.keys()) ) ) def __setattr__( self : Tuple , snake_case : List[str] , snake_case : int ) -> str: """simple docstring""" UpperCamelCase_ : List[str] = val UpperCamelCase_ : Optional[int] = val UpperCamelCase_ : List[str] = key.split('.' ) UpperCamelCase_ : int = len(snake_case ) - 1 UpperCamelCase_ : Optional[Any] = self._pointer if len(snake_case ) > 1: for i, l in enumerate(snake_case ): if hasattr(self , snake_case ) and isinstance(getattr(self , snake_case ) , snake_case ): setattr(getattr(self , snake_case ) , '.'.join(levels[i:] ) , snake_case ) if l == last_level: UpperCamelCase_ : Tuple = val else: UpperCamelCase_ : List[Any] = pointer[l] def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[int]: """simple docstring""" return self._pointer def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : Any , snake_case : Tuple ) -> Any: """simple docstring""" with open(f"{file_name}" , 'w' ) as stream: dump(snake_case , snake_case ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : Tuple , snake_case : Optional[Any] ) -> Optional[int]: """simple docstring""" with open(f"{file_name}" , 'w' ) as stream: json.dump(snake_case , snake_case ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case : str ) -> Dict: """simple docstring""" with open(snake_case ) as stream: UpperCamelCase_ : str = load(snake_case , Loader=snake_case ) return data def __str__( self : Tuple ) -> int: """simple docstring""" UpperCamelCase_ : List[str] = ' ' if self._name != "root": UpperCamelCase_ : int = f"{t * (self._level-1)}{self._name}:\n" else: UpperCamelCase_ : str = '' UpperCamelCase_ : Tuple = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(snake_case , snake_case ): r += f"{t * (self._level)}{v}\n" self._level += 1 else: r += f"{t * (self._level)}{k}: {v} ({type(snake_case ).__name__})\n" UpperCamelCase_ : Any = level return r[:-1] @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple , snake_case : str , **snake_case : Any ) -> Dict: """simple docstring""" UpperCamelCase_, UpperCamelCase_ : Optional[Any] = cls.get_config_dict(snake_case , **snake_case ) return cls(snake_case ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : str , snake_case : str , **snake_case : str ) -> int: """simple docstring""" UpperCamelCase_ : Dict = kwargs.pop('cache_dir' , snake_case ) UpperCamelCase_ : List[Any] = kwargs.pop('force_download' , snake_case ) UpperCamelCase_ : Any = kwargs.pop('resume_download' , snake_case ) UpperCamelCase_ : Tuple = kwargs.pop('proxies' , snake_case ) UpperCamelCase_ : Union[str, Any] = kwargs.pop('local_files_only' , snake_case ) if os.path.isdir(snake_case ): UpperCamelCase_ : Dict = os.path.join(snake_case , snake_case ) elif os.path.isfile(snake_case ) or is_remote_url(snake_case ): UpperCamelCase_ : List[Any] = pretrained_model_name_or_path else: UpperCamelCase_ : Optional[int] = hf_bucket_url(snake_case , filename=snake_case , use_cdn=snake_case ) try: # Load from URL or cache if already cached UpperCamelCase_ : Any = cached_path( snake_case , cache_dir=snake_case , force_download=snake_case , proxies=snake_case , resume_download=snake_case , local_files_only=snake_case , ) # Load config dict if resolved_config_file is None: raise EnvironmentError UpperCamelCase_ : Dict = Config.load_yaml(snake_case ) except EnvironmentError: UpperCamelCase_ : List[Any] = 'Can\'t load config for' raise EnvironmentError(snake_case ) if resolved_config_file == config_file: print('loading configuration file from path' ) else: print('loading configuration file cache' ) return Config.load_yaml(snake_case ), kwargs def __lowercase ( lowerCamelCase : List[str] ): UpperCamelCase_ : int = torch.load('dump.pt' , map_location=in_tensor.device ) UpperCamelCase_ : List[Any] = in_tensor.numpy() UpperCamelCase_ : Dict = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(lowerCamelCase , lowerCamelCase , rtol=0.0_1 , atol=0.1 ), ( F"{sum([1 for x in np.isclose(lowerCamelCase , lowerCamelCase , rtol=0.0_1 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %" " element-wise mismatch" ) raise Exception('tensors are all good' ) # Hugging face functions below def __lowercase ( lowerCamelCase : Optional[int] ): UpperCamelCase_ : str = urlparse(lowerCamelCase ) return parsed.scheme in ("http", "https") def __lowercase ( lowerCamelCase : str , lowerCamelCase : str , lowerCamelCase : Tuple=True ): UpperCamelCase_ : Dict = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX UpperCamelCase_ : List[Any] = '/' not in model_id if legacy_format: return F"{endpoint}/{model_id}-{filename}" else: return F"{endpoint}/{model_id}/{filename}" def __lowercase ( lowerCamelCase : str , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[Any]=None , lowerCamelCase : int=0 , lowerCamelCase : Tuple=None , ): UpperCamelCase_ : Union[str, Any] = 'python/{}'.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(lowerCamelCase , lowerCamelCase ): ua += "; " + "; ".join('{}/{}'.format(lowerCamelCase , lowerCamelCase ) for k, v in user_agent.items() ) elif isinstance(lowerCamelCase , lowerCamelCase ): ua += "; " + user_agent UpperCamelCase_ : Union[str, Any] = {'user-agent': ua} if resume_size > 0: UpperCamelCase_ : Optional[int] = 'bytes=%d-' % (resume_size,) UpperCamelCase_ : Any = requests.get(lowerCamelCase , stream=lowerCamelCase , proxies=lowerCamelCase , headers=lowerCamelCase ) if response.status_code == 416: # Range not satisfiable return UpperCamelCase_ : Dict = response.headers.get('Content-Length' ) UpperCamelCase_ : Dict = resume_size + int(lowerCamelCase ) if content_length is not None else None UpperCamelCase_ : int = tqdm( unit='B' , unit_scale=lowerCamelCase , total=lowerCamelCase , initial=lowerCamelCase , desc='Downloading' , ) for chunk in response.iter_content(chunk_size=1024 ): if chunk: # filter out keep-alive new chunks progress.update(len(lowerCamelCase ) ) temp_file.write(lowerCamelCase ) progress.close() def __lowercase ( lowerCamelCase : Dict , lowerCamelCase : Tuple=None , lowerCamelCase : List[str]=False , lowerCamelCase : List[Any]=None , lowerCamelCase : int=10 , lowerCamelCase : List[Any]=False , lowerCamelCase : int=None , lowerCamelCase : Any=False , ): if cache_dir is None: UpperCamelCase_ : Union[str, Any] = TRANSFORMERS_CACHE if isinstance(lowerCamelCase , lowerCamelCase ): UpperCamelCase_ : List[Any] = str(lowerCamelCase ) os.makedirs(lowerCamelCase , exist_ok=lowerCamelCase ) UpperCamelCase_ : List[str] = None if not local_files_only: try: UpperCamelCase_ : Optional[Any] = requests.head(lowerCamelCase , allow_redirects=lowerCamelCase , proxies=lowerCamelCase , timeout=lowerCamelCase ) if response.status_code == 200: UpperCamelCase_ : str = response.headers.get('ETag' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass UpperCamelCase_ : Tuple = url_to_filename(lowerCamelCase , lowerCamelCase ) # get cache path to put the file UpperCamelCase_ : int = os.path.join(lowerCamelCase , lowerCamelCase ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(lowerCamelCase ): return cache_path else: UpperCamelCase_ : Any = [ file for file in fnmatch.filter(os.listdir(lowerCamelCase ) , filename + '.*' ) if not file.endswith('.json' ) and not file.endswith('.lock' ) ] if len(lowerCamelCase ) > 0: return os.path.join(lowerCamelCase , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( 'Cannot find the requested files in the cached path and outgoing traffic has been' ' disabled. To enable model look-ups and downloads online, set \'local_files_only\'' ' to False.' ) return None # From now on, etag is not None. if os.path.exists(lowerCamelCase ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. UpperCamelCase_ : Optional[Any] = cache_path + '.lock' with FileLock(lowerCamelCase ): # If the download just completed while the lock was activated. if os.path.exists(lowerCamelCase ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: UpperCamelCase_ : int = cache_path + '.incomplete' @contextmanager def _resumable_file_manager(): with open(lowerCamelCase , 'a+b' ) as f: yield f UpperCamelCase_ : Union[str, Any] = _resumable_file_manager if os.path.exists(lowerCamelCase ): UpperCamelCase_ : List[Any] = os.stat(lowerCamelCase ).st_size else: UpperCamelCase_ : str = 0 else: UpperCamelCase_ : Optional[int] = partial(tempfile.NamedTemporaryFile , dir=lowerCamelCase , delete=lowerCamelCase ) UpperCamelCase_ : int = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( '%s not found in cache or force_download set to True, downloading to %s' , lowerCamelCase , temp_file.name , ) http_get( lowerCamelCase , lowerCamelCase , proxies=lowerCamelCase , resume_size=lowerCamelCase , user_agent=lowerCamelCase , ) os.replace(temp_file.name , lowerCamelCase ) UpperCamelCase_ : Any = {'url': url, 'etag': etag} UpperCamelCase_ : int = cache_path + '.json' with open(lowerCamelCase , 'w' ) as meta_file: json.dump(lowerCamelCase , lowerCamelCase ) return cache_path def __lowercase ( lowerCamelCase : List[str] , lowerCamelCase : Optional[Any]=None ): UpperCamelCase_ : Optional[Any] = url.encode('utf-8' ) UpperCamelCase_ : str = shaaaa(lowerCamelCase ) UpperCamelCase_ : Dict = url_hash.hexdigest() if etag: UpperCamelCase_ : Optional[Any] = etag.encode('utf-8' ) UpperCamelCase_ : Optional[int] = shaaaa(lowerCamelCase ) filename += "." + etag_hash.hexdigest() if url.endswith('.h5' ): filename += ".h5" return filename def __lowercase ( lowerCamelCase : Optional[Any] , lowerCamelCase : Dict=None , lowerCamelCase : Optional[Any]=False , lowerCamelCase : Any=None , lowerCamelCase : Optional[int]=False , lowerCamelCase : int=None , lowerCamelCase : Optional[int]=False , lowerCamelCase : Any=False , lowerCamelCase : Any=False , ): if cache_dir is None: UpperCamelCase_ : List[Any] = TRANSFORMERS_CACHE if isinstance(lowerCamelCase , lowerCamelCase ): UpperCamelCase_ : List[Any] = str(lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ): UpperCamelCase_ : Optional[int] = str(lowerCamelCase ) if is_remote_url(lowerCamelCase ): # URL, so get it from the cache (downloading if necessary) UpperCamelCase_ : Tuple = get_from_cache( lowerCamelCase , cache_dir=lowerCamelCase , force_download=lowerCamelCase , proxies=lowerCamelCase , resume_download=lowerCamelCase , user_agent=lowerCamelCase , local_files_only=lowerCamelCase , ) elif os.path.exists(lowerCamelCase ): # File, and it exists. UpperCamelCase_ : List[str] = url_or_filename elif urlparse(lowerCamelCase ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('file {} not found'.format(lowerCamelCase ) ) else: # Something unknown raise ValueError('unable to parse {} as a URL or as a local path'.format(lowerCamelCase ) ) if extract_compressed_file: if not is_zipfile(lowerCamelCase ) and not tarfile.is_tarfile(lowerCamelCase ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" UpperCamelCase_, UpperCamelCase_ : str = os.path.split(lowerCamelCase ) UpperCamelCase_ : Union[str, Any] = output_file.replace('.' , '-' ) + '-extracted' UpperCamelCase_ : List[Any] = os.path.join(lowerCamelCase , lowerCamelCase ) if os.path.isdir(lowerCamelCase ) and os.listdir(lowerCamelCase ) and not force_extract: return output_path_extracted # Prevent parallel extractions UpperCamelCase_ : int = output_path + '.lock' with FileLock(lowerCamelCase ): shutil.rmtree(lowerCamelCase , ignore_errors=lowerCamelCase ) os.makedirs(lowerCamelCase ) if is_zipfile(lowerCamelCase ): with ZipFile(lowerCamelCase , 'r' ) as zip_file: zip_file.extractall(lowerCamelCase ) zip_file.close() elif tarfile.is_tarfile(lowerCamelCase ): UpperCamelCase_ : int = tarfile.open(lowerCamelCase ) tar_file.extractall(lowerCamelCase ) tar_file.close() else: raise EnvironmentError('Archive format of {} could not be identified'.format(lowerCamelCase ) ) return output_path_extracted return output_path def __lowercase ( lowerCamelCase : Tuple , lowerCamelCase : int="," ): assert isinstance(lowerCamelCase , lowerCamelCase ) if os.path.isfile(lowerCamelCase ): with open(lowerCamelCase ) as f: UpperCamelCase_ : str = eval(f.read() ) else: UpperCamelCase_ : int = requests.get(lowerCamelCase ) try: UpperCamelCase_ : int = requests.json() except Exception: UpperCamelCase_ : int = req.content.decode() assert data is not None, "could not connect" try: UpperCamelCase_ : List[str] = eval(lowerCamelCase ) except Exception: UpperCamelCase_ : Tuple = data.split('\n' ) req.close() return data def __lowercase ( lowerCamelCase : List[str] ): UpperCamelCase_ : int = requests.get(lowerCamelCase ) UpperCamelCase_ : Optional[int] = np.array(Image.open(BytesIO(response.content ) ) ) return img def __lowercase ( lowerCamelCase : Union[str, Any] ): UpperCamelCase_ : Any = url.split('/' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(lowerCamelCase ) with open(lowerCamelCase , 'rb' ) as stream: UpperCamelCase_ : Optional[int] = pkl.load(lowerCamelCase ) UpperCamelCase_ : Optional[int] = weights.pop('model' ) UpperCamelCase_ : Optional[int] = {} for k, v in model.items(): UpperCamelCase_ : Dict = torch.from_numpy(lowerCamelCase ) if "running_var" in k: UpperCamelCase_ : Union[str, Any] = torch.tensor([0] ) UpperCamelCase_ : Tuple = k.replace('running_var' , 'num_batches_tracked' ) UpperCamelCase_ : Union[str, Any] = zero return new def __lowercase ( ): print(F"{os.path.abspath(os.path.join(lowerCamelCase , os.pardir ) )}/demo.ipynb" ) def __lowercase ( lowerCamelCase : Any , lowerCamelCase : Optional[int]="RGB" ): assert isinstance(lowerCamelCase , lowerCamelCase ) if os.path.isfile(lowerCamelCase ): UpperCamelCase_ : List[Any] = cva.imread(lowerCamelCase ) else: UpperCamelCase_ : Any = get_image_from_url(lowerCamelCase ) assert img is not None, F"could not connect to: {im}" UpperCamelCase_ : Any = cva.cvtColor(lowerCamelCase , cva.COLOR_BGR2RGB ) if input_format == "RGB": UpperCamelCase_ : Optional[Any] = img[:, :, ::-1] return img def __lowercase ( lowerCamelCase : Tuple , lowerCamelCase : int=1 ): return (images[i : i + batch] for i in range(0 , len(lowerCamelCase ) , lowerCamelCase ))
417
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging a_ = logging.get_logger(__name__) class _lowercase ( snake_case_ ): lowercase = ['pixel_values'] def __init__( self : Optional[int] , snake_case : bool = True , snake_case : int = 3_2 , snake_case : List[str]=PILImageResampling.BILINEAR , snake_case : bool = True , **snake_case : Tuple , ) -> None: """simple docstring""" UpperCamelCase_ : int = do_resize UpperCamelCase_ : Union[str, Any] = do_rescale UpperCamelCase_ : Any = size_divisor UpperCamelCase_ : str = resample super().__init__(**snake_case ) def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case : np.ndarray , snake_case : int , snake_case : Optional[Any] , snake_case : Optional[ChannelDimension] = None , **snake_case : str ) -> np.ndarray: """simple docstring""" UpperCamelCase_, UpperCamelCase_ : Dict = get_image_size(snake_case ) # Rounds the height and width down to the closest multiple of size_divisor UpperCamelCase_ : Optional[int] = height // size_divisor * size_divisor UpperCamelCase_ : Union[str, Any] = width // size_divisor * size_divisor UpperCamelCase_ : Any = resize(snake_case , (new_h, new_w) , resample=snake_case , data_format=snake_case , **snake_case ) return image def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case : np.ndarray , snake_case : float , snake_case : Optional[ChannelDimension] = None , **snake_case : Optional[int] ) -> np.ndarray: """simple docstring""" return rescale(image=snake_case , scale=snake_case , data_format=snake_case , **snake_case ) def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , snake_case : Optional[bool] = None , snake_case : Optional[int] = None , snake_case : str=None , snake_case : Optional[bool] = None , snake_case : Optional[Union[TensorType, str]] = None , snake_case : ChannelDimension = ChannelDimension.FIRST , **snake_case : Tuple , ) -> BatchFeature: """simple docstring""" UpperCamelCase_ : str = do_resize if do_resize is not None else self.do_resize UpperCamelCase_ : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase_ : str = size_divisor if size_divisor is not None else self.size_divisor UpperCamelCase_ : int = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('size_divisor is required for resizing' ) UpperCamelCase_ : int = make_list_of_images(snake_case ) if not valid_images(snake_case ): raise ValueError('Invalid image(s)' ) # All transformations expect numpy arrays. UpperCamelCase_ : Optional[int] = [to_numpy_array(snake_case ) for img in images] if do_resize: UpperCamelCase_ : List[str] = [self.resize(snake_case , size_divisor=snake_case , resample=snake_case ) for image in images] if do_rescale: UpperCamelCase_ : List[str] = [self.rescale(snake_case , scale=1 / 2_5_5 ) for image in images] UpperCamelCase_ : Tuple = [to_channel_dimension_format(snake_case , snake_case ) for image in images] UpperCamelCase_ : Dict = {'pixel_values': images} return BatchFeature(data=snake_case , tensor_type=snake_case )
417
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 ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): A__ : Any = IFInpaintingPipeline A__ : Dict = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} A__ : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS A__ : Dict = PipelineTesterMixin.required_optional_params - {"latents"} def _a ( self ): return self._get_dummy_components() def _a ( self , _lowerCamelCase , _lowerCamelCase=0 ): if str(_snake_case ).startswith("mps" ): lowerCamelCase__ =torch.manual_seed(_snake_case ) else: lowerCamelCase__ =torch.Generator(device=_snake_case ).manual_seed(_snake_case ) lowerCamelCase__ =floats_tensor((1, 3, 32, 32) , rng=random.Random(_snake_case ) ).to(_snake_case ) lowerCamelCase__ =floats_tensor((1, 3, 32, 32) , rng=random.Random(_snake_case ) ).to(_snake_case ) lowerCamelCase__ ={ "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 _a ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def _a ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def _a ( self ): super().test_save_load_floataa(expected_max_diff=1E-1 ) def _a ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _a ( self ): self._test_save_load_local() def _a ( self ): self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
708
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a =logging.get_logger(__name__) a ={ 'shi-labs/dinat-mini-in1k-224': 'https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json', # See all Dinat models at https://huggingface.co/models?filter=dinat } class __UpperCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ): A__ : str = '''dinat''' A__ : List[str] = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _lowerCamelCase=4 , _lowerCamelCase=3 , _lowerCamelCase=64 , _lowerCamelCase=[3, 4, 6, 5] , _lowerCamelCase=[2, 4, 8, 16] , _lowerCamelCase=7 , _lowerCamelCase=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] , _lowerCamelCase=3.0 , _lowerCamelCase=True , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=0.0_2 , _lowerCamelCase=1E-5 , _lowerCamelCase=0.0 , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ): super().__init__(**_lowerCamelCase ) lowerCamelCase__ =patch_size lowerCamelCase__ =num_channels lowerCamelCase__ =embed_dim lowerCamelCase__ =depths lowerCamelCase__ =len(_lowerCamelCase ) lowerCamelCase__ =num_heads lowerCamelCase__ =kernel_size lowerCamelCase__ =dilations lowerCamelCase__ =mlp_ratio lowerCamelCase__ =qkv_bias lowerCamelCase__ =hidden_dropout_prob lowerCamelCase__ =attention_probs_dropout_prob lowerCamelCase__ =drop_path_rate lowerCamelCase__ =hidden_act lowerCamelCase__ =layer_norm_eps lowerCamelCase__ =initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowerCamelCase__ =int(embed_dim * 2 ** (len(_lowerCamelCase ) - 1) ) lowerCamelCase__ =layer_scale_init_value lowerCamelCase__ =["stem"] + [F'''stage{idx}''' for idx in range(1 , len(_lowerCamelCase ) + 1 )] lowerCamelCase__ , lowerCamelCase__ =get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names )
132
0
'''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 lowerCamelCase__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Tuple="shi-labs/oneformer_demo" ): with open(hf_hub_download(__A , __A , repo_type='dataset' ) , 'r' ) as f: UpperCAmelCase = json.load(__A ) UpperCAmelCase = {} UpperCAmelCase = [] UpperCAmelCase = [] for key, info in class_info.items(): UpperCAmelCase = info['''name'''] class_names.append(info['name'] ) if info["isthing"]: thing_ids.append(int(__A ) ) UpperCAmelCase = thing_ids UpperCAmelCase = class_names return metadata class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , a_ , a_=7 , a_=3 , a_=3_0 , a_=4_0_0 , a_=None , a_=True , a_=True , a_=[0.5, 0.5, 0.5] , a_=[0.5, 0.5, 0.5] , a_=1_0 , a_=False , a_=2_5_5 , a_="shi-labs/oneformer_demo" , a_="ade20k_panoptic.json" , a_=1_0 , ) -> Dict: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution UpperCAmelCase = do_resize UpperCAmelCase = {'''shortest_edge''': 3_2, '''longest_edge''': 1_3_3_3} if size is None else size UpperCAmelCase = do_normalize UpperCAmelCase = image_mean UpperCAmelCase = image_std UpperCAmelCase = class_info_file UpperCAmelCase = prepare_metadata(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) UpperCAmelCase = num_text UpperCAmelCase = repo_path # for the post_process_functions UpperCAmelCase = 2 UpperCAmelCase = 1_0 UpperCAmelCase = 1_0 UpperCAmelCase = 3 UpperCAmelCase = 4 UpperCAmelCase = num_labels UpperCAmelCase = do_reduce_labels UpperCAmelCase = ignore_index def snake_case_ ( self ) -> int: """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 snake_case_ ( self , a_ , a_=False ) -> Optional[Any]: """simple docstring""" if not batched: UpperCAmelCase = image_inputs[0] if isinstance(__SCREAMING_SNAKE_CASE , Image.Image ): UpperCAmelCase = image.size else: UpperCAmelCase = image.shape[1], image.shape[2] if w < h: UpperCAmelCase = int(self.size['shortest_edge'] * h / w ) UpperCAmelCase = self.size['''shortest_edge'''] elif w > h: UpperCAmelCase = self.size['''shortest_edge'''] UpperCAmelCase = int(self.size['shortest_edge'] * w / h ) else: UpperCAmelCase = self.size['''shortest_edge'''] UpperCAmelCase = self.size['''shortest_edge'''] else: UpperCAmelCase = [] for image in image_inputs: UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCAmelCase = max(__SCREAMING_SNAKE_CASE , key=lambda a_ : item[0] )[0] UpperCAmelCase = max(__SCREAMING_SNAKE_CASE , key=lambda a_ : item[1] )[1] return expected_height, expected_width def snake_case_ ( self ) -> List[str]: """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 lowercase_ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase : List[Any] = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string __lowerCAmelCase : Union[str, Any] = image_processing_class def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = OneFormerImageProcessorTester(self ) @property def snake_case_ ( self ) -> Any: """simple docstring""" return self.image_processing_tester.prepare_image_processor_dict() def snake_case_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'ignore_index' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'class_info_file' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'num_text' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'repo_path' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'metadata' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'do_reduce_labels' ) ) def snake_case_ ( self ) -> str: """simple docstring""" pass def snake_case_ ( self ) -> Tuple: """simple docstring""" # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values UpperCAmelCase = self.image_processing_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = self.image_processing_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = image_processor( __SCREAMING_SNAKE_CASE , ['semantic'] * len(__SCREAMING_SNAKE_CASE ) , 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 snake_case_ ( self ) -> str: """simple docstring""" # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values UpperCAmelCase = self.image_processing_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = self.image_processing_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = image_processor( __SCREAMING_SNAKE_CASE , ['semantic'] * len(__SCREAMING_SNAKE_CASE ) , 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 snake_case_ ( self ) -> int: """simple docstring""" # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values UpperCAmelCase = self.image_processing_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = self.image_processing_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = image_processor( __SCREAMING_SNAKE_CASE , ['semantic'] * len(__SCREAMING_SNAKE_CASE ) , 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 snake_case_ ( self , a_=False , a_=False , a_="np" ) -> Any: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # prepare image and target UpperCAmelCase = self.image_processing_tester.num_labels UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = prepare_image_inputs(self.image_processing_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) if with_segmentation_maps: UpperCAmelCase = num_labels if is_instance_map: UpperCAmelCase = list(range(__SCREAMING_SNAKE_CASE ) ) * 2 UpperCAmelCase = dict(enumerate(__SCREAMING_SNAKE_CASE ) ) UpperCAmelCase = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": UpperCAmelCase = [Image.fromarray(__SCREAMING_SNAKE_CASE ) for annotation in annotations] UpperCAmelCase = image_processor( __SCREAMING_SNAKE_CASE , ['semantic'] * len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , return_tensors='pt' , instance_id_to_semantic_id=__SCREAMING_SNAKE_CASE , pad_and_return_pixel_mask=__SCREAMING_SNAKE_CASE , ) return inputs def snake_case_ ( self ) -> Optional[Any]: """simple docstring""" pass def snake_case_ ( self ) -> List[str]: """simple docstring""" def common(a_=False , a_=None ): UpperCAmelCase = self.comm_get_image_processor_inputs( with_segmentation_maps=__SCREAMING_SNAKE_CASE , is_instance_map=__SCREAMING_SNAKE_CASE , segmentation_type=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = inputs['''mask_labels'''] UpperCAmelCase = inputs['''class_labels'''] UpperCAmelCase = inputs['''pixel_values'''] UpperCAmelCase = inputs['''text_inputs'''] # check the batch_size for mask_label, class_label, text_input in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): 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(__SCREAMING_SNAKE_CASE ) , self.image_processing_tester.num_text ) common() common(is_instance_map=__SCREAMING_SNAKE_CASE ) common(is_instance_map=__SCREAMING_SNAKE_CASE , segmentation_type='pil' ) common(is_instance_map=__SCREAMING_SNAKE_CASE , segmentation_type='pil' ) def snake_case_ ( self ) -> str: """simple docstring""" UpperCAmelCase = np.zeros((2_0, 5_0) ) UpperCAmelCase = 1 UpperCAmelCase = 1 UpperCAmelCase = 1 UpperCAmelCase = binary_mask_to_rle(__SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 4 ) self.assertEqual(rle[0] , 2_1 ) self.assertEqual(rle[1] , 4_5 ) def snake_case_ ( self ) -> int: """simple docstring""" UpperCAmelCase = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) UpperCAmelCase = self.image_processing_tester.get_fake_oneformer_outputs() UpperCAmelCase = fature_extractor.post_process_semantic_segmentation(__SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) UpperCAmelCase = [(1, 4) for i in range(self.image_processing_tester.batch_size )] UpperCAmelCase = fature_extractor.post_process_semantic_segmentation(__SCREAMING_SNAKE_CASE , target_sizes=__SCREAMING_SNAKE_CASE ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def snake_case_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) UpperCAmelCase = self.image_processing_tester.get_fake_oneformer_outputs() UpperCAmelCase = image_processor.post_process_instance_segmentation(__SCREAMING_SNAKE_CASE , threshold=0 ) self.assertTrue(len(__SCREAMING_SNAKE_CASE ) == 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'] ) , __SCREAMING_SNAKE_CASE ) self.assertEqual( el['segmentation'].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) UpperCAmelCase = self.image_processing_tester.get_fake_oneformer_outputs() UpperCAmelCase = image_processor.post_process_panoptic_segmentation(__SCREAMING_SNAKE_CASE , threshold=0 ) self.assertTrue(len(__SCREAMING_SNAKE_CASE ) == 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'] ) , __SCREAMING_SNAKE_CASE ) self.assertEqual( el['segmentation'].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
447
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py __lowerCAmelCase = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. __lowerCAmelCase = direct_transformers_import(PATH_TO_TRANSFORMERS) __lowerCAmelCase = transformers.models.auto.configuration_auto.CONFIG_MAPPING __lowerCAmelCase = { # used to compute the property `self.chunk_length` 'EncodecConfig': ['overlap'], # used as `self.bert_model = BertModel(config, ...)` 'DPRConfig': True, # not used in modeling files, but it's an important information 'FSMTConfig': ['langs'], # used internally in the configuration class file 'GPTNeoConfig': ['attention_types'], # used internally in the configuration class file 'EsmConfig': ['is_folding_model'], # used during training (despite we don't have training script for these models yet) 'Mask2FormerConfig': ['ignore_value'], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) 'OneFormerConfig': ['ignore_value', 'norm'], # used during preprocessing and collation, see `collating_graphormer.py` 'GraphormerConfig': ['spatial_pos_max'], # used internally in the configuration class file 'T5Config': ['feed_forward_proj'], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally 'MT5Config': ['feed_forward_proj', 'tokenizer_class'], 'UMT5Config': ['feed_forward_proj', 'tokenizer_class'], # used internally in the configuration class file 'LongT5Config': ['feed_forward_proj'], # used internally in the configuration class file 'SwitchTransformersConfig': ['feed_forward_proj'], # having default values other than `1e-5` - we can't fix them without breaking 'BioGptConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'GLPNConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'SegformerConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'CvtConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'PerceiverConfig': ['layer_norm_eps'], # used internally to calculate the feature size 'InformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'TimeSeriesTransformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'AutoformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate `mlp_dim` 'SamVisionConfig': ['mlp_ratio'], # For (head) training, but so far not implemented 'ClapAudioConfig': ['num_classes'], # Not used, but providing useful information to users 'SpeechT5HifiGanConfig': ['sampling_rate'], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { 'CLIPSegConfig': True, 'DeformableDetrConfig': True, 'DetaConfig': True, 'DinatConfig': True, 'DonutSwinConfig': True, 'EfficientFormerConfig': True, 'FSMTConfig': True, 'JukeboxConfig': True, 'LayoutLMv2Config': True, 'MaskFormerSwinConfig': True, 'MT5Config': True, 'NatConfig': True, 'OneFormerConfig': True, 'PerceiverConfig': True, 'RagConfig': True, 'SpeechT5Config': True, 'SwinConfig': True, 'Swin2SRConfig': True, 'Swinv2Config': True, 'SwitchTransformersConfig': True, 'TableTransformerConfig': True, 'TapasConfig': True, 'TransfoXLConfig': True, 'UniSpeechConfig': True, 'UniSpeechSatConfig': True, 'WavLMConfig': True, 'WhisperConfig': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) 'JukeboxPriorConfig': True, # TODO: @Younes (for `is_decoder`) 'Pix2StructTextConfig': True, } ) def _UpperCAmelCase ( __A : Optional[Any] , __A : List[str] , __A : List[str] , __A : Union[str, Any] ): a_ : List[str] = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( f'config.{attribute}' in modeling_source or f'getattr(config, "{attribute}"' in modeling_source or f'getattr(self.config, "{attribute}"' in modeling_source ): a_ : Tuple = True # Deal with multi-line cases elif ( re.search( Rf'getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"' , __A , ) is not None ): a_ : Union[str, Any] = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: a_ : Any = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files a_ : Tuple = [ '''bos_index''', '''eos_index''', '''pad_index''', '''unk_index''', '''mask_index''', '''image_size''', '''use_cache''', '''out_features''', '''out_indices''', ] a_ : Tuple = ['''encoder_no_repeat_ngram_size'''] # Special cases to be allowed a_ : Optional[int] = True if not attribute_used: a_ : Optional[Any] = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: a_ : Dict = True elif attribute in ["tie_word_embeddings"] and default_value is False: a_ : List[str] = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: a_ : Optional[int] = True elif attribute.endswith('''_token_id''' ): a_ : Tuple = True # configuration class specific cases if not case_allowed: a_ : Dict = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) a_ : int = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def _UpperCAmelCase ( __A : Union[str, Any] ): a_ : str = dict(inspect.signature(config_class.__init__ ).parameters ) a_ : List[str] = [x for x in list(signature.keys() ) if x not in ['''self''', '''kwargs''']] a_ : Optional[Any] = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass a_ : int = {} if len(config_class.attribute_map ) > 0: a_ : List[str] = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files a_ : Tuple = inspect.getsourcefile(__A ) a_ : str = os.path.dirname(__A ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. a_ : Tuple = [os.path.join(__A , __A ) for fn in os.listdir(__A ) if fn.startswith('''modeling_''' )] # Get the source code strings a_ : Dict = [] for path in modeling_paths: if os.path.isfile(__A ): with open(__A ) as fp: modeling_sources.append(fp.read() ) a_ : List[Any] = [] for config_param, default_value in zip(__A , __A ): # `attributes` here is all the variant names for `config_param` a_ : int = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(__A , __A , __A , __A ): unused_attributes.append(attributes[0] ) return sorted(__A ) def _UpperCAmelCase ( ): a_ : Optional[int] = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) a_ : int = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda __A : inspect.isclass(__A ) and issubclass(__A , __A ) and inspect.getmodule(__A ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: a_ : int = check_config_attributes_being_used(__A ) if len(__A ) > 0: a_ : Dict = unused_attributes if len(__A ) > 0: a_ : Dict = '''The following configuration classes contain unused attributes in the corresponding modeling files:\n''' for name, attributes in configs_with_unused_attributes.items(): error += f'{name}: {attributes}\n' raise ValueError(__A ) if __name__ == "__main__": check_config_attributes()
466
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib snake_case : List[Any] = get_logger() snake_case : Optional[dict] = None class snake_case_ (TensorFormatter[Mapping, '''jax.Array''', Mapping] ): def __init__( self :Tuple ,__snake_case :List[str]=None ,__snake_case :Dict=None ,**__snake_case :Union[str, Any] ) -> Tuple: super().__init__(features=__snake_case ) import jax from jaxlib.xla_client import Device if isinstance(__snake_case ,__snake_case ): raise ValueError( F'Expected {device} to be a `str` not {type(__snake_case )}, as `jaxlib.xla_extension.Device` ' 'is not serializable neither with `pickle` nor with `dill`. Instead you can surround ' 'the device with `str()` to get its string identifier that will be internally mapped ' 'to the actual `jaxlib.xla_extension.Device`.' ) a__ = device if isinstance(__snake_case ,__snake_case ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: a__ = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F'Device with string identifier {self.device} not listed among the available ' F'devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ' F'device: {str(jax.devices()[0] )}.' ) a__ = str(jax.devices()[0] ) a__ = jnp_array_kwargs @staticmethod def lowerCamelCase__( ) -> Dict[str, "jaxlib.xla_extension.Device"]: import jax return {str(__snake_case ): device for device in jax.devices()} def lowerCamelCase__( self :List[Any] ,__snake_case :List[str] ) -> List[Any]: import jax import jax.numpy as jnp if isinstance(__snake_case ,__snake_case ) and column: if all( isinstance(__snake_case ,jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(__snake_case ,axis=0 ) return column def lowerCamelCase__( self :str ,__snake_case :Any ) -> List[str]: import jax import jax.numpy as jnp if isinstance(__snake_case ,(str, bytes, type(__snake_case )) ): return value elif isinstance(__snake_case ,(np.character, np.ndarray) ) and np.issubdtype(value.dtype ,np.character ): return value.tolist() a__ = {} if isinstance(__snake_case ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: a__ = {'dtype': jnp.intaa} else: a__ = {'dtype': jnp.intaa} elif isinstance(__snake_case ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.floating ): a__ = {'dtype': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(__snake_case ,PIL.Image.Image ): a__ = np.asarray(__snake_case ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: a__ = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(__snake_case ,**{**default_dtype, **self.jnp_array_kwargs} ) def lowerCamelCase__( self :List[Any] ,__snake_case :Tuple ) -> Any: import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(__snake_case ,torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(__snake_case ,'__array__' ) and not isinstance(__snake_case ,jax.Array ): a__ = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(__snake_case ,np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(__snake_case ) for substruct in data_struct] ) elif isinstance(__snake_case ,(list, tuple) ): return self._consolidate([self.recursive_tensorize(__snake_case ) for substruct in data_struct] ) return self._tensorize(__snake_case ) def lowerCamelCase__( self :Union[str, Any] ,__snake_case :dict ) -> List[Any]: return map_nested(self._recursive_tensorize ,__snake_case ,map_list=__snake_case ) def lowerCamelCase__( self :Optional[int] ,__snake_case :pa.Table ) -> Mapping: a__ = self.numpy_arrow_extractor().extract_row(__snake_case ) a__ = self.python_features_decoder.decode_row(__snake_case ) return self.recursive_tensorize(__snake_case ) def lowerCamelCase__( self :int ,__snake_case :pa.Table ) -> "jax.Array": a__ = self.numpy_arrow_extractor().extract_column(__snake_case ) a__ = self.python_features_decoder.decode_column(__snake_case ,pa_table.column_names[0] ) a__ = self.recursive_tensorize(__snake_case ) a__ = self._consolidate(__snake_case ) return column def lowerCamelCase__( self :Union[str, Any] ,__snake_case :pa.Table ) -> Mapping: a__ = self.numpy_arrow_extractor().extract_batch(__snake_case ) a__ = self.python_features_decoder.decode_batch(__snake_case ) a__ = self.recursive_tensorize(__snake_case ) for column_name in batch: a__ = self._consolidate(batch[column_name] ) return batch
657
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class snake_case_ (lowerCamelCase_ , lowerCamelCase_ ): UpperCAmelCase__ : Optional[Any] = 1 @register_to_config def __init__( self :Optional[int] ,__snake_case :int = 10_00 ,__snake_case :Optional[Union[np.ndarray, List[float]]] = None ) -> int: # set `betas`, `alphas`, `timesteps` self.set_timesteps(__snake_case ) # standard deviation of the initial noise distribution a__ = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. a__ = 4 # running values a__ = [] def lowerCamelCase__( self :Union[str, Any] ,__snake_case :int ,__snake_case :Union[str, torch.device] = None ) -> Union[str, Any]: a__ = num_inference_steps a__ = torch.linspace(1 ,0 ,num_inference_steps + 1 )[:-1] a__ = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: a__ = torch.tensor(self.config.trained_betas ,dtype=torch.floataa ) else: a__ = torch.sin(steps * math.pi / 2 ) ** 2 a__ = (1.0 - self.betas**2) ** 0.5 a__ = (torch.atana(self.betas ,self.alphas ) / math.pi * 2)[:-1] a__ = timesteps.to(__snake_case ) a__ = [] def lowerCamelCase__( self :Any ,__snake_case :torch.FloatTensor ,__snake_case :int ,__snake_case :torch.FloatTensor ,__snake_case :bool = True ,) -> Union[SchedulerOutput, Tuple]: if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) a__ = (self.timesteps == timestep).nonzero().item() a__ = timestep_index + 1 a__ = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(__snake_case ) if len(self.ets ) == 1: a__ = self.ets[-1] elif len(self.ets ) == 2: a__ = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: a__ = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: a__ = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) a__ = self._get_prev_sample(__snake_case ,__snake_case ,__snake_case ,__snake_case ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__snake_case ) def lowerCamelCase__( self :Union[str, Any] ,__snake_case :torch.FloatTensor ,*__snake_case :int ,**__snake_case :Optional[int] ) -> torch.FloatTensor: return sample def lowerCamelCase__( self :Optional[Any] ,__snake_case :List[Any] ,__snake_case :Optional[int] ,__snake_case :Dict ,__snake_case :Any ) -> Optional[Any]: a__ = self.alphas[timestep_index] a__ = self.betas[timestep_index] a__ = self.alphas[prev_timestep_index] a__ = self.betas[prev_timestep_index] a__ = (sample - sigma * ets) / max(__snake_case ,1E-8 ) a__ = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self :Any ) -> Union[str, Any]: return self.config.num_train_timesteps
657
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class lowercase_ ( UpperCamelCase__): """simple docstring""" def __init__( self , _UpperCAmelCase ): """simple docstring""" a_ = data def __iter__( self ): """simple docstring""" for element in self.data: yield element def lowerCamelCase_ ( UpperCAmelCase__=True ): """simple docstring""" a_ = Accelerator(even_batches=UpperCAmelCase__ ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = False ): """simple docstring""" if iterable: a_ = DummyIterableDataset(torch.as_tensor(range(UpperCAmelCase__ ) ) ) else: a_ = TensorDataset(torch.as_tensor(range(UpperCAmelCase__ ) ) ) a_ = DataLoader(UpperCAmelCase__ , batch_size=UpperCAmelCase__ ) a_ = accelerator.prepare(UpperCAmelCase__ ) return dl def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ): """simple docstring""" a_ = create_dataloader(accelerator=UpperCAmelCase__ , dataset_size=UpperCAmelCase__ , batch_size=UpperCAmelCase__ ) a_ = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator(even_batches=UpperCAmelCase__ ) verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator(even_batches=UpperCAmelCase__ ) a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) a_ = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(UpperCAmelCase__ ): a_ = ddp_model(batch[0].float() ) a_ = output.sum() loss.backward() batch_idxs.append(UpperCAmelCase__ ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def lowerCamelCase_ ( UpperCAmelCase__ ): """simple docstring""" with warnings.catch_warnings(record=UpperCAmelCase__ ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , UpperCAmelCase__ ) assert "only supported for multi-GPU" in str(w[-1].message ) def lowerCamelCase_ ( ): """simple docstring""" a_ = True a_ = False a_ = create_accelerator(even_batches=UpperCAmelCase__ ) a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): a_ = train_dl.batch_sampler.even_batches a_ = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def lowerCamelCase_ ( ): """simple docstring""" a_ = True a_ = False a_ = create_accelerator(even_batches=UpperCAmelCase__ ) a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=UpperCAmelCase__ ) a_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): a_ = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator() a_ = torch.nn.Linear(1 , 1 ) a_ = accelerator.prepare(UpperCAmelCase__ ) create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=UpperCAmelCase__ ) with warnings.catch_warnings(record=UpperCAmelCase__ ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): pass assert issubclass(w[-1].category , UpperCAmelCase__ ) assert "only supported for map-style datasets" in str(w[-1].message ) def lowerCamelCase_ ( ): """simple docstring""" a_ = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) a_ = accelerator.state.distributed_type a_ = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(UpperCAmelCase__ ) a_ = original_state if __name__ == "__main__": main()
483
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class lowercase_ ( unittest.TestCase): """simple docstring""" def __init__( self , _UpperCAmelCase , _UpperCAmelCase=7 , _UpperCAmelCase=3 , _UpperCAmelCase=30 , _UpperCAmelCase=400 , _UpperCAmelCase=True , _UpperCAmelCase=None , _UpperCAmelCase=0.9 , _UpperCAmelCase=None , _UpperCAmelCase=True , _UpperCAmelCase=[0.5, 0.5, 0.5] , _UpperCAmelCase=[0.5, 0.5, 0.5] , ): """simple docstring""" a_ = size if size is not None else {"""shortest_edge""": 30} a_ = crop_size if crop_size is not None else {"""height""": 30, """width""": 30} a_ = parent a_ = batch_size a_ = num_channels a_ = min_resolution a_ = max_resolution a_ = do_resize_and_center_crop a_ = size a_ = crop_pct a_ = crop_size a_ = do_normalize a_ = image_mean a_ = image_std def lowercase__ ( self ): """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class lowercase_ ( UpperCamelCase__ ,unittest.TestCase): """simple docstring""" snake_case_ = PoolFormerImageProcessor if is_vision_available() else None def lowercase__ ( self ): """simple docstring""" a_ = PoolFormerImageProcessingTester(self ) @property def lowercase__ ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowercase__ ( self ): """simple docstring""" a_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_UpperCAmelCase , """do_resize_and_center_crop""" ) ) self.assertTrue(hasattr(_UpperCAmelCase , """size""" ) ) self.assertTrue(hasattr(_UpperCAmelCase , """crop_pct""" ) ) self.assertTrue(hasattr(_UpperCAmelCase , """do_normalize""" ) ) self.assertTrue(hasattr(_UpperCAmelCase , """image_mean""" ) ) self.assertTrue(hasattr(_UpperCAmelCase , """image_std""" ) ) def lowercase__ ( self ): """simple docstring""" a_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 30} ) self.assertEqual(image_processor.crop_size , {"""height""": 30, """width""": 30} ) a_ = 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 lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self ): """simple docstring""" a_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , Image.Image ) # Test not batched input a_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched a_ = image_processing(_UpperCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowercase__ ( self ): """simple docstring""" a_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase , numpify=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , np.ndarray ) # Test not batched input a_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched a_ = image_processing(_UpperCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowercase__ ( self ): """simple docstring""" a_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase , torchify=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , torch.Tensor ) # Test not batched input a_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched a_ = image_processing(_UpperCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
483
1
from __future__ import annotations from typing import TypedDict class _a ( __a ): __a : str __a : int def snake_case_ (_a : str ): if not isinstance(_a , _a ): raise TypeError('''The parameter s type must be str.''' ) return [s[i:] + s[:i] for i in range(len(_a ) )] def snake_case_ (_a : str ): if not isinstance(_a , _a ): raise TypeError('''The parameter s type must be str.''' ) if not s: raise ValueError('''The parameter s must not be empty.''' ) UpperCAmelCase = all_rotations(_a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCAmelCase = { '''bwt_string''': ''''''.join([word[-1] for word in rotations] ), '''idx_original_string''': rotations.index(_a ), } return response def snake_case_ (_a : str , _a : int ): if not isinstance(_a , _a ): raise TypeError('''The parameter bwt_string type must be str.''' ) if not bwt_string: raise ValueError('''The parameter bwt_string must not be empty.''' ) try: UpperCAmelCase = int(_a ) except ValueError: raise TypeError( '''The parameter idx_original_string type must be int or passive''' ''' of cast to int.''' ) if idx_original_string < 0: raise ValueError('''The parameter idx_original_string must not be lower than 0.''' ) if idx_original_string >= len(_a ): raise ValueError( '''The parameter idx_original_string must be lower than''' ''' len(bwt_string).''' ) UpperCAmelCase = [''''''] * len(_a ) for _ in range(len(_a ) ): for i in range(len(_a ) ): UpperCAmelCase = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A ='Provide a string that I will generate its BWT transform: ' A =input(entry_msg).strip() A =bwt_transform(s) print( f"""Burrows Wheeler transform for string '{s}' results """ f"""in '{result["bwt_string"]}'""" ) A =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}'""" )
717
'''simple docstring''' import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class _a ( unittest.TestCase ): def __init__( self : List[Any] , lowercase : Dict , lowercase : List[str]=13 , lowercase : str=7 , lowercase : List[str]=True , lowercase : List[str]=True , lowercase : Optional[Any]=True , lowercase : Optional[Any]=True , lowercase : Any=99 , lowercase : Any=32 , lowercase : Any=5 , lowercase : Tuple=4 , lowercase : List[Any]=37 , lowercase : List[Any]="gelu" , lowercase : int=0.1 , lowercase : Any=0.1 , lowercase : Optional[int]=512 , lowercase : List[str]=16 , lowercase : Union[str, Any]=2 , lowercase : int=0.02 , lowercase : int=4 , ): '''simple docstring''' UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_attention_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_choices def A ( self : Any ): '''simple docstring''' UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_attention_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase = RobertaPreLayerNormConfig( 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=lowercase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def A ( self : List[Any] ): '''simple docstring''' UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def A ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = True UpperCAmelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class _a ( __a , unittest.TestCase ): __a : Any = True __a : str = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def A ( self : Any ): '''simple docstring''' UpperCAmelCase = FlaxRobertaPreLayerNormModelTester(self ) @slow def A ( self : Optional[int] ): '''simple docstring''' for model_class_name in self.all_model_classes: UpperCAmelCase = model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=lowercase ) UpperCAmelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowercase ) @require_flax class _a ( unittest.TestCase ): @slow def A ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=lowercase ) UpperCAmelCase = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) UpperCAmelCase = model(lowercase )[0] UpperCAmelCase = [1, 11, 50_265] self.assertEqual(list(output.shape ) , lowercase ) # compare the actual values for a slice. UpperCAmelCase = np.array( [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowercase , atol=1E-4 ) ) @slow def A ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase = FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=lowercase ) UpperCAmelCase = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) UpperCAmelCase = model(lowercase )[0] # compare the actual values for a slice. UpperCAmelCase = np.array( [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowercase , atol=1E-4 ) )
358
0
"""simple docstring""" from __future__ import annotations def __A ( a_ :list) -> float: if not nums: raise ValueError('''List is empty''') return sum(a_) / len(a_) if __name__ == "__main__": import doctest doctest.testmod()
52
"""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 rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __lowerCamelCase = logging.get_logger(__name__) def a ( __snake_case : Any, __snake_case : Dict ): '''simple docstring''' UpperCAmelCase_ :Any = b.T UpperCAmelCase_ :Tuple = np.sum(np.square(__snake_case ), axis=1 ) UpperCAmelCase_ :List[str] = np.sum(np.square(__snake_case ), axis=0 ) UpperCAmelCase_ :Optional[Any] = np.matmul(__snake_case, __snake_case ) UpperCAmelCase_ :str = aa[:, None] - 2 * ab + ba[None, :] return d def a ( __snake_case : Union[str, Any], __snake_case : Tuple ): '''simple docstring''' UpperCAmelCase_ :List[str] = x.reshape(-1, 3 ) UpperCAmelCase_ :List[str] = squared_euclidean_distance(__snake_case, __snake_case ) return np.argmin(__snake_case, axis=1 ) class _snake_case ( A__ ): '''simple docstring''' UpperCamelCase__ =["""pixel_values"""] def __init__( self : Any , snake_case : Optional[Union[List[List[int]], np.ndarray]] = None , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = PILImageResampling.BILINEAR , snake_case : bool = True , snake_case : bool = True , **snake_case : Optional[Any] , ): super().__init__(**snake_case ) UpperCAmelCase_ :List[str] = size if size is not None else {'''height''': 256, '''width''': 256} UpperCAmelCase_ :Any = get_size_dict(snake_case ) UpperCAmelCase_ :str = np.array(snake_case ) if clusters is not None else None UpperCAmelCase_ :List[Any] = do_resize UpperCAmelCase_ :Optional[int] = size UpperCAmelCase_ :Union[str, Any] = resample UpperCAmelCase_ :Dict = do_normalize UpperCAmelCase_ :Optional[Any] = do_color_quantize def snake_case_ ( self : Any , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : PILImageResampling = PILImageResampling.BILINEAR , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Dict , ): UpperCAmelCase_ :Any = get_size_dict(snake_case ) if "height" not in size or "width" not in size: raise ValueError(f'Size dictionary must contain both height and width keys. Got {size.keys()}' ) return resize( snake_case , size=(size['''height'''], size['''width''']) , resample=snake_case , data_format=snake_case , **snake_case ) def snake_case_ ( self : Tuple , snake_case : np.ndarray , snake_case : Optional[Union[str, ChannelDimension]] = None , ): UpperCAmelCase_ :Optional[int] = rescale(image=snake_case , scale=1 / 127.5 , data_format=snake_case ) UpperCAmelCase_ :str = image - 1 return image def snake_case_ ( self : Any , snake_case : ImageInput , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = None , snake_case : bool = None , snake_case : Optional[bool] = None , snake_case : Optional[Union[List[List[int]], np.ndarray]] = None , snake_case : Optional[Union[str, TensorType]] = None , snake_case : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **snake_case : List[Any] , ): UpperCAmelCase_ :Dict = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ :List[Any] = size if size is not None else self.size UpperCAmelCase_ :Optional[int] = get_size_dict(snake_case ) UpperCAmelCase_ :Optional[int] = resample if resample is not None else self.resample UpperCAmelCase_ :str = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase_ :str = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCAmelCase_ :Optional[int] = clusters if clusters is not None else self.clusters UpperCAmelCase_ :Any = np.array(snake_case ) UpperCAmelCase_ :Tuple = make_list_of_images(snake_case ) if not valid_images(snake_case ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_color_quantize and clusters is None: raise ValueError('''Clusters must be specified if do_color_quantize is True.''' ) # All transformations expect numpy arrays. UpperCAmelCase_ :Optional[Any] = [to_numpy_array(snake_case ) for image in images] if do_resize: UpperCAmelCase_ :Optional[Any] = [self.resize(image=snake_case , size=snake_case , resample=snake_case ) for image in images] if do_normalize: UpperCAmelCase_ :Optional[Any] = [self.normalize(image=snake_case ) for image in images] if do_color_quantize: UpperCAmelCase_ :List[Any] = [to_channel_dimension_format(snake_case , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCAmelCase_ :str = np.array(snake_case ) UpperCAmelCase_ :Dict = color_quantize(snake_case , snake_case ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCAmelCase_ :Tuple = images.shape[0] UpperCAmelCase_ :int = images.reshape(snake_case , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCAmelCase_ :int = list(snake_case ) else: UpperCAmelCase_ :Any = [to_channel_dimension_format(snake_case , snake_case ) for image in images] UpperCAmelCase_ :Optional[Any] = {'''input_ids''': images} return BatchFeature(data=snake_case , tensor_type=snake_case )
608
0
'''simple docstring''' lowerCAmelCase__ : Dict = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCAmelCase__ : Tuple = [{"type": "code", "content": INSTALL_CONTENT}] lowerCAmelCase__ : Tuple = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
712
'''simple docstring''' from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCAmelCase__ : List[str] = TypeVar("KEY") lowerCAmelCase__ : str = TypeVar("VAL") @dataclass(frozen=snake_case__ ,slots=snake_case__ ) class SCREAMING_SNAKE_CASE__ ( Generic[KEY, VAL] ): """simple docstring""" SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CASE = 42 class SCREAMING_SNAKE_CASE__ ( _Item ): """simple docstring""" def __init__( self : Tuple ): """simple docstring""" super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) def __bool__( self : Dict ): """simple docstring""" return False lowerCAmelCase__ : str = _DeletedItem() class SCREAMING_SNAKE_CASE__ ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self : Optional[int] , UpperCAmelCase_ : int = 8 , UpperCAmelCase_ : float = 0.75 ): """simple docstring""" __UpperCAmelCase : List[Any] = initial_block_size __UpperCAmelCase : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __UpperCAmelCase : int = capacity_factor __UpperCAmelCase : int = 0 def lowerCamelCase_ ( self : str , UpperCAmelCase_ : KEY ): """simple docstring""" return hash(UpperCAmelCase_ ) % len(self._buckets ) def lowerCamelCase_ ( self : Dict , UpperCAmelCase_ : int ): """simple docstring""" return (ind + 1) % len(self._buckets ) def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : KEY , UpperCAmelCase_ : VAL ): """simple docstring""" __UpperCAmelCase : Tuple = self._buckets[ind] if not stored: __UpperCAmelCase : str = _Item(UpperCAmelCase_ , UpperCAmelCase_ ) self._len += 1 return True elif stored.key == key: __UpperCAmelCase : List[Any] = _Item(UpperCAmelCase_ , UpperCAmelCase_ ) return True else: return False def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" __UpperCAmelCase : List[Any] = len(self._buckets ) * self._capacity_factor return len(self ) >= int(UpperCAmelCase_ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" if len(self._buckets ) <= self._initial_block_size: return False __UpperCAmelCase : Dict = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def lowerCamelCase_ ( self : int , UpperCAmelCase_ : int ): """simple docstring""" __UpperCAmelCase : List[Any] = self._buckets __UpperCAmelCase : str = [None] * new_size __UpperCAmelCase : Any = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" self._resize(len(self._buckets ) * 2 ) def lowerCamelCase_ ( self : int ): """simple docstring""" self._resize(len(self._buckets ) // 2 ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase_ : KEY ): """simple docstring""" __UpperCAmelCase : str = self._get_bucket_index(UpperCAmelCase_ ) for _ in range(len(self._buckets ) ): yield ind __UpperCAmelCase : Optional[Any] = self._get_next_ind(UpperCAmelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase_ : KEY , UpperCAmelCase_ : VAL ): """simple docstring""" for ind in self._iterate_buckets(UpperCAmelCase_ ): if self._try_set(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): break def __setitem__( self : Tuple , UpperCAmelCase_ : KEY , UpperCAmelCase_ : VAL ): """simple docstring""" if self._is_full(): self._size_up() self._add_item(UpperCAmelCase_ , UpperCAmelCase_ ) def __delitem__( self : Optional[int] , UpperCAmelCase_ : KEY ): """simple docstring""" for ind in self._iterate_buckets(UpperCAmelCase_ ): __UpperCAmelCase : Optional[int] = self._buckets[ind] if item is None: raise KeyError(UpperCAmelCase_ ) if item is _deleted: continue if item.key == key: __UpperCAmelCase : Optional[Any] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Any , UpperCAmelCase_ : KEY ): """simple docstring""" for ind in self._iterate_buckets(UpperCAmelCase_ ): __UpperCAmelCase : str = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(UpperCAmelCase_ ) def __len__( self : List[Any] ): """simple docstring""" return self._len def __iter__( self : Optional[int] ): """simple docstring""" yield from (item.key for item in self._buckets if item) def __repr__( self : List[str] ): """simple docstring""" __UpperCAmelCase : Any = " ,".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})"
329
0
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 __magic_name__ (unittest.TestCase ): @slow def __a ( self ) -> Tuple: lowerCAmelCase_ = TFXLMRobertaModel.from_pretrained("jplu/tf-xlm-roberta-base" ) lowerCAmelCase_ = { "input_ids": tf.convert_to_tensor([[0, 2646, 10269, 83, 99942, 2]] , dtype=tf.intaa ), # "My dog is cute" "attention_mask": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } lowerCAmelCase_ = model(_a )["last_hidden_state"] lowerCAmelCase_ = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , _a ) # compare the actual values for a slice. lowerCAmelCase_ = tf.convert_to_tensor( [ [ [0.0_6_8_1_7_6_2, 0.1_0_8_9_4_4_5_1, 0.0_6_7_7_2_5_0_4], [-0.0_6_4_2_3_6_6_8, 0.0_2_3_6_6_6_1_5, 0.0_4_3_2_9_3_4_4], [-0.0_6_0_5_7_2_9_5, 0.0_9_9_7_4_1_3_5, -0.0_0_0_7_0_5_8_4], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
122
from string import ascii_uppercase lowerCamelCase__ = {char: i for i, char in enumerate(ascii_uppercase)} lowerCamelCase__ = dict(enumerate(ascii_uppercase)) def A(__a: str , __a: str ): lowerCAmelCase_ = len(__a ) lowerCAmelCase_ = 0 while True: if x == i: lowerCAmelCase_ = 0 if len(__a ) == len(__a ): break key += key[i] i += 1 return key def A(__a: str , __a: str ): lowerCAmelCase_ = "" lowerCAmelCase_ = 0 for letter in message: if letter == " ": cipher_text += " " else: lowerCAmelCase_ = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def A(__a: str , __a: str ): lowerCAmelCase_ = "" lowerCAmelCase_ = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: lowerCAmelCase_ = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def A(): lowerCAmelCase_ = "THE GERMAN ATTACK" lowerCAmelCase_ = "SECRET" lowerCAmelCase_ = generate_key(__a , __a ) lowerCAmelCase_ = cipher_text(__a , __a ) print(F"Encrypted Text = {s}" ) print(F"Original Text = {original_text(__a , __a )}" ) if __name__ == "__main__": import doctest doctest.testmod() main()
122
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor __lowerCAmelCase : Dict = logging.get_logger(__name__) class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , *_lowercase , **_lowercase ) -> None: '''simple docstring''' warnings.warn( """The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use SegformerImageProcessor instead.""" , _lowercase , ) super().__init__(*_lowercase , **_lowercase )
21
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu __lowerCAmelCase : Optional[Any] = False class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self ) -> Any: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase__ ( self ) -> Any: '''simple docstring''' return 1_2 @property def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' return 1_2 @property def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return 3_2 @property def UpperCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : List[Any] = VQModel( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(_lowercase ) @property def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : Union[str, Any] = 1_2 snake_case_ : Tuple = 1_2 snake_case_ : Tuple = { """attention_bias""": True, """cross_attention_dim""": 3_2, """attention_head_dim""": height * width, """num_attention_heads""": 1, """num_vector_embeds""": self.num_embed, """num_embeds_ada_norm""": self.num_embeds_ada_norm, """norm_num_groups""": 3_2, """sample_size""": width, """activation_fn""": """geglu-approximate""", } snake_case_ : Optional[Any] = TransformeraDModel(**_lowercase ) return model def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ : str = """cpu""" snake_case_ : List[str] = self.dummy_vqvae snake_case_ : Any = self.dummy_text_encoder snake_case_ : Tuple = self.dummy_tokenizer snake_case_ : int = self.dummy_transformer snake_case_ : int = VQDiffusionScheduler(self.num_embed ) snake_case_ : Dict = LearnedClassifierFreeSamplingEmbeddings(learnable=_lowercase ) snake_case_ : Optional[Any] = VQDiffusionPipeline( vqvae=_lowercase , text_encoder=_lowercase , tokenizer=_lowercase , transformer=_lowercase , scheduler=_lowercase , learned_classifier_free_sampling_embeddings=_lowercase , ) snake_case_ : int = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) snake_case_ : List[Any] = """teddy bear playing in the pool""" snake_case_ : Dict = torch.Generator(device=_lowercase ).manual_seed(0 ) snake_case_ : List[Any] = pipe([prompt] , generator=_lowercase , num_inference_steps=2 , output_type="""np""" ) snake_case_ : Optional[int] = output.images snake_case_ : List[Any] = torch.Generator(device=_lowercase ).manual_seed(0 ) snake_case_ : Dict = pipe( [prompt] , generator=_lowercase , output_type="""np""" , return_dict=_lowercase , num_inference_steps=2 )[0] snake_case_ : List[Any] = image[0, -3:, -3:, -1] snake_case_ : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 2_4, 2_4, 3) snake_case_ : Dict = np.array([0.6551, 0.6168, 0.5008, 0.5676, 0.5659, 0.4295, 0.6073, 0.5599, 0.4992] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ : int = """cpu""" snake_case_ : List[Any] = self.dummy_vqvae snake_case_ : Optional[int] = self.dummy_text_encoder snake_case_ : List[Any] = self.dummy_tokenizer snake_case_ : Union[str, Any] = self.dummy_transformer snake_case_ : str = VQDiffusionScheduler(self.num_embed ) snake_case_ : List[Any] = LearnedClassifierFreeSamplingEmbeddings( learnable=_lowercase , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) snake_case_ : Union[str, Any] = VQDiffusionPipeline( vqvae=_lowercase , text_encoder=_lowercase , tokenizer=_lowercase , transformer=_lowercase , scheduler=_lowercase , learned_classifier_free_sampling_embeddings=_lowercase , ) snake_case_ : Any = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) snake_case_ : Tuple = """teddy bear playing in the pool""" snake_case_ : str = torch.Generator(device=_lowercase ).manual_seed(0 ) snake_case_ : Tuple = pipe([prompt] , generator=_lowercase , num_inference_steps=2 , output_type="""np""" ) snake_case_ : Dict = output.images snake_case_ : Union[str, Any] = torch.Generator(device=_lowercase ).manual_seed(0 ) snake_case_ : Any = pipe( [prompt] , generator=_lowercase , output_type="""np""" , return_dict=_lowercase , num_inference_steps=2 )[0] snake_case_ : Optional[Any] = image[0, -3:, -3:, -1] snake_case_ : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 2_4, 2_4, 3) snake_case_ : int = np.array([0.6693, 0.6075, 0.4959, 0.5701, 0.5583, 0.4333, 0.6171, 0.5684, 0.4988] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy""" ) snake_case_ : str = VQDiffusionPipeline.from_pretrained("""microsoft/vq-diffusion-ithq""" ) snake_case_ : Optional[Any] = pipeline.to(_lowercase ) pipeline.set_progress_bar_config(disable=_lowercase ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though snake_case_ : Any = torch.Generator(device=_lowercase ).manual_seed(0 ) snake_case_ : Optional[int] = pipeline( """teddy bear playing in the pool""" , num_images_per_prompt=1 , generator=_lowercase , output_type="""np""" , ) snake_case_ : Union[str, Any] = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) assert np.abs(expected_image - image ).max() < 2.0
21
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def __UpperCAmelCase ( ) -> Dict: """simple docstring""" __a = ArgumentParser('Accelerate CLI tool', usage='accelerate <command> [<args>]', allow_abbrev=SCREAMING_SNAKE_CASE__ ) __a = parser.add_subparsers(help='accelerate command helpers' ) # Register commands get_config_parser(subparsers=SCREAMING_SNAKE_CASE__ ) env_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) launch_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) tpu_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) test_command_parser(subparsers=SCREAMING_SNAKE_CASE__ ) # Let's go __a = parser.parse_args() if not hasattr(SCREAMING_SNAKE_CASE__, 'func' ): parser.print_help() exit(1 ) # Run args.func(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
448
'''simple docstring''' __UpperCamelCase : List[Any] = """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/""" def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: bytes ) -> bytes: """simple docstring""" # Make sure the supplied data is a bytes-like object if not isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): __a = f"""a bytes-like object is required, not '{data.__class__.__name__}'""" raise TypeError(SCREAMING_SNAKE_CASE__ ) __a = ''.join(bin(SCREAMING_SNAKE_CASE__ )[2:].zfill(8 ) for byte in data ) __a = len(SCREAMING_SNAKE_CASE__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'=' * ((6 - len(SCREAMING_SNAKE_CASE__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(SCREAMING_SNAKE_CASE__ ) % 6) else: __a = b'' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6], 2 )] for index in range(0, len(SCREAMING_SNAKE_CASE__ ), 6 ) ).encode() + padding ) def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: str ) -> bytes: """simple docstring""" # Make sure encoded_data is either a string or a bytes-like object if not isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): __a = ( 'argument should be a bytes-like object or ASCII string, ' f"""not '{encoded_data.__class__.__name__}'""" ) raise TypeError(SCREAMING_SNAKE_CASE__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): try: __a = encoded_data.decode('utf-8' ) except UnicodeDecodeError: raise ValueError('base64 encoded data should only contain ASCII characters' ) __a = encoded_data.count('=' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(SCREAMING_SNAKE_CASE__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''.join( bin(B64_CHARSET.index(SCREAMING_SNAKE_CASE__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''.join( bin(B64_CHARSET.index(SCREAMING_SNAKE_CASE__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8], 2 ) for index in range(0, len(SCREAMING_SNAKE_CASE__ ), 8 ) ] return bytes(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
448
1
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def _UpperCAmelCase (UpperCamelCase_ : str , UpperCamelCase_ : float | Decimal , UpperCamelCase_ : float = 10**-10 ): '''simple docstring''' _lowerCAmelCase : Tuple = a while True: _lowerCAmelCase : Any = Decimal(UpperCamelCase_ ) - ( Decimal(eval(UpperCamelCase_ ) ) / Decimal(eval(str(diff(UpperCamelCase_ ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(UpperCamelCase_ ) ) < precision: # noqa: S307 return float(UpperCamelCase_ ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F'''The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}''') # Find root of polynomial print(F'''The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}''') # Find Square Root of 5 print(F'''The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}''') # Exponential Roots print(F'''The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}''')
701
def _UpperCAmelCase (UpperCamelCase_ : int ): '''simple docstring''' _lowerCAmelCase : int = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
196
0
import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def UpperCamelCase__ ( _A: Optional[int] , _A: List[str] , _A: Optional[int] , _A: Optional[Any]=1024 ): '''simple docstring''' __lowerCamelCase = [], [] __lowerCamelCase = list(zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = sorted_examples[0] def is_too_big(_A: List[str] ): return tok(SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): __lowerCamelCase = new_src + ' ' + src __lowerCamelCase = new_tgt + ' ' + tgt if is_too_big(SCREAMING_SNAKE_CASE__ ) or is_too_big(SCREAMING_SNAKE_CASE__ ): # cant fit, finalize example finished_src.append(SCREAMING_SNAKE_CASE__ ) finished_tgt.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = src, tgt else: # can fit, keep adding __lowerCamelCase = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(SCREAMING_SNAKE_CASE__ ) finished_tgt.append(SCREAMING_SNAKE_CASE__ ) return finished_src, finished_tgt def UpperCamelCase__ ( _A: Optional[int] , _A: Union[str, Any] , _A: Optional[Any] , _A: Optional[Any] ): '''simple docstring''' __lowerCamelCase = Path(SCREAMING_SNAKE_CASE__ ) save_path.mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) for split in ["train"]: __lowerCamelCase = data_dir / f'''{split}.source''', data_dir / f'''{split}.target''' __lowerCamelCase = [x.rstrip() for x in Path(SCREAMING_SNAKE_CASE__ ).open().readlines()] __lowerCamelCase = [x.rstrip() for x in Path(SCREAMING_SNAKE_CASE__ ).open().readlines()] __lowerCamelCase = pack_examples(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'''packed {split} split from {len(SCREAMING_SNAKE_CASE__ )} examples -> {len(SCREAMING_SNAKE_CASE__ )}.''' ) Path(save_path / f'''{split}.source''' ).open("""w""" ).write("""\n""".join(SCREAMING_SNAKE_CASE__ ) ) Path(save_path / f'''{split}.target''' ).open("""w""" ).write("""\n""".join(SCREAMING_SNAKE_CASE__ ) ) for split in ["val", "test"]: __lowerCamelCase = data_dir / f'''{split}.source''', data_dir / f'''{split}.target''' shutil.copyfile(SCREAMING_SNAKE_CASE__ , save_path / f'''{split}.source''' ) shutil.copyfile(SCREAMING_SNAKE_CASE__ , save_path / f'''{split}.target''' ) def UpperCamelCase__ ( ): '''simple docstring''' __lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""--tok_name""" , type=SCREAMING_SNAKE_CASE__ , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""--max_seq_len""" , type=SCREAMING_SNAKE_CASE__ , default=128 ) parser.add_argument("""--data_dir""" , type=SCREAMING_SNAKE_CASE__ ) parser.add_argument("""--save_path""" , type=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = parser.parse_args() __lowerCamelCase = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(SCREAMING_SNAKE_CASE__ , Path(args.data_dir ) , args.max_seq_len , args.save_path ) if __name__ == "__main__": packer_cli()
479
'''simple docstring''' import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 SCREAMING_SNAKE_CASE_ = 0B10_11_00_11_11_10_11_00_10_01_00_00_01_11_10_11_10_11_00_01_10_01_11_10 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 SCREAMING_SNAKE_CASE_ = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class lowerCAmelCase : """simple docstring""" def __init__( self ) -> Optional[int]: __a : Tuple = WATERMARK_BITS __a : Union[str, Any] = WatermarkEncoder() self.encoder.set_watermark('bits' , self.watermark ) def __magic_name__ ( self , _A ) -> List[str]: # can't encode images that are smaller than 256 if images.shape[-1] < 256: return images __a : List[str] = (255 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __a : Any = [self.encoder.encode(_A , 'dwtDct' ) for image in images] __a : List[Any] = torch.from_numpy(np.array(_A ) ).permute(0 , 3 , 1 , 2 ) __a : Any = torch.clamp(2 * (images / 255 - 0.5) , min=-1.0 , max=1.0 ) return images
597
0
def __UpperCamelCase ( A ): UpperCamelCase__ = 0 for ch in input_str: UpperCamelCase__ = ord(A ) UpperCamelCase__ = pow(2 , A ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
469
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _A ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : List[str] ="" SCREAMING_SNAKE_CASE_ : str =( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) SCREAMING_SNAKE_CASE_ : str =None # compression type in fsspec. ex: "gzip" SCREAMING_SNAKE_CASE_ : str =None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__(self , SCREAMING_SNAKE_CASE_ = "" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' super().__init__(self , **SCREAMING_SNAKE_CASE_ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode UpperCamelCase__ = fsspec.open( SCREAMING_SNAKE_CASE_ , mode='''rb''' , protocol=SCREAMING_SNAKE_CASE_ , compression=self.compression , client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) UpperCamelCase__ = os.path.basename(self.file.path.split('''::''' )[0] ) UpperCamelCase__ = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) UpperCamelCase__ = None @classmethod def _a (cls , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' return super()._strip_protocol(SCREAMING_SNAKE_CASE_ ).lstrip('''/''' ) def _a (self ) -> Union[str, Any]: '''simple docstring''' if self.dir_cache is None: UpperCamelCase__ = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} UpperCamelCase__ = {f['''name''']: f} def _a (self , SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' return self.file.open().read() def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "rb" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = self._strip_protocol(SCREAMING_SNAKE_CASE_ ) if mode != "rb": raise ValueError(F"Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'" ) return self.file.open() class _A ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : Tuple ="bz2" SCREAMING_SNAKE_CASE_ : List[str] ="bz2" SCREAMING_SNAKE_CASE_ : List[Any] =".bz2" class _A ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : Tuple ="gzip" SCREAMING_SNAKE_CASE_ : Dict ="gzip" SCREAMING_SNAKE_CASE_ : List[Any] =".gz" class _A ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : List[Any] ="lz4" SCREAMING_SNAKE_CASE_ : str ="lz4" SCREAMING_SNAKE_CASE_ : Any =".lz4" class _A ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : Dict ="xz" SCREAMING_SNAKE_CASE_ : List[str] ="xz" SCREAMING_SNAKE_CASE_ : Optional[int] =".xz" class _A ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : Optional[Any] ="zstd" SCREAMING_SNAKE_CASE_ : Optional[int] ="zstd" SCREAMING_SNAKE_CASE_ : Optional[int] =".zst" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "rb" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = DEFAULT_BLOCK_SIZE , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__( fo=SCREAMING_SNAKE_CASE_ , mode=SCREAMING_SNAKE_CASE_ , target_protocol=SCREAMING_SNAKE_CASE_ , target_options=SCREAMING_SNAKE_CASE_ , block_size=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 UpperCamelCase__ = self.file.__enter__ class _A : def __init__(self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' UpperCamelCase__ = file_ def __enter__(self ) -> Union[str, Any]: '''simple docstring''' self._file.__enter__() return self def __exit__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' self._file.__exit__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __iter__(self ) -> Dict: '''simple docstring''' return iter(self._file ) def _a (self ) -> Dict: '''simple docstring''' return next(self._file ) def __getattr__(self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' return getattr(self._file , SCREAMING_SNAKE_CASE_ ) def fixed_enter(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return WrappedFile(_enter(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = fixed_enter
469
1
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A : @staticmethod def __lowerCAmelCase ( *lowerCAmelCase_ : str , **lowerCAmelCase_ : Any ) -> Union[str, Any]: """simple docstring""" pass @is_pipeline_test @require_vision class A ( unittest.TestCase ): @require_torch def __lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" _a = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) _a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _a = image_classifier(lowerCAmelCase_ , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(lowerCAmelCase_ ) , [ [{'''score''': 0.3_3_3, '''label''': '''a'''}, {'''score''': 0.3_3_3, '''label''': '''b'''}, {'''score''': 0.3_3_3, '''label''': '''c'''}], [{'''score''': 0.3_3_3, '''label''': '''a'''}, {'''score''': 0.3_3_3, '''label''': '''c'''}, {'''score''': 0.3_3_3, '''label''': '''b'''}], ] , ) _a = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], ] , ) @require_tf def __lowerCAmelCase ( self : Any ) -> Tuple: """simple docstring""" _a = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) _a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _a = image_classifier(lowerCAmelCase_ , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [{'''score''': 0.3_3_3, '''label''': '''a'''}, {'''score''': 0.3_3_3, '''label''': '''b'''}, {'''score''': 0.3_3_3, '''label''': '''c'''}] , ) _a = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], [ {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, {'''score''': 0.3_3_3, '''label''': ANY(lowerCAmelCase_ )}, ], ] , ) @slow @require_torch def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" _a = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes _a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _a = image_classifier(lowerCAmelCase_ , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ {'''score''': 0.5_1_1, '''label''': '''remote'''}, {'''score''': 0.4_8_5, '''label''': '''cat'''}, {'''score''': 0.0_0_4, '''label''': '''plane'''}, ] , ) _a = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ [ {'''score''': 0.5_1_1, '''label''': '''remote'''}, {'''score''': 0.4_8_5, '''label''': '''cat'''}, {'''score''': 0.0_0_4, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" _a = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes _a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _a = image_classifier(lowerCAmelCase_ , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ {'''score''': 0.5_1_1, '''label''': '''remote'''}, {'''score''': 0.4_8_5, '''label''': '''cat'''}, {'''score''': 0.0_0_4, '''label''': '''plane'''}, ] , ) _a = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ [ {'''score''': 0.5_1_1, '''label''': '''remote'''}, {'''score''': 0.4_8_5, '''label''': '''cat'''}, {'''score''': 0.0_0_4, '''label''': '''plane'''}, ], ] * 5 , )
22
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowercase : Tuple = logging.getLogger(__name__) class lowerCamelCase__ ( __lowercase): '''simple docstring''' def __init__( self :Dict , a :Union[str, Any]=-1 ) -> List[str]: # in NER datasets, the last column is usually reserved for NER label __UpperCamelCase : str = label_idx def _lowerCamelCase ( self :str , a :Tuple , a :Union[Split, str] ) -> List[InputExample]: if isinstance(a , a ): __UpperCamelCase : Dict = mode.value __UpperCamelCase : Union[str, Any] = os.path.join(a , f'{mode}.txt' ) __UpperCamelCase : Any = 1 __UpperCamelCase : List[str] = [] with open(a , encoding="utf-8" ) as f: __UpperCamelCase : Tuple = [] __UpperCamelCase : Dict = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=a , labels=a ) ) guid_index += 1 __UpperCamelCase : Dict = [] __UpperCamelCase : List[str] = [] else: __UpperCamelCase : Union[str, Any] = line.split(" " ) words.append(splits[0] ) if len(a ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=a , labels=a ) ) return examples def _lowerCamelCase ( self :int , a :TextIO , a :TextIO , a :List ) -> Optional[Any]: __UpperCamelCase : Tuple = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(a ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __UpperCamelCase : Union[str, Any] = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(a ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def _lowerCamelCase ( self :Tuple , a :str ) -> List[str]: if path: with open(a , "r" ) as f: __UpperCamelCase : List[str] = f.read().splitlines() if "O" not in labels: __UpperCamelCase : Any = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class lowerCamelCase__ ( __lowercase): '''simple docstring''' def __init__( self :List[str] ) -> int: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def _lowerCamelCase ( self :List[str] , a :str ) -> List[str]: if path: with open(a , "r" ) as f: __UpperCamelCase : Optional[Any] = f.read().splitlines() if "O" not in labels: __UpperCamelCase : int = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class lowerCamelCase__ ( __lowercase): '''simple docstring''' def _lowerCamelCase ( self :List[str] , a :Union[str, Any] , a :Union[Split, str] ) -> List[InputExample]: if isinstance(a , a ): __UpperCamelCase : Optional[Any] = mode.value __UpperCamelCase : List[str] = os.path.join(a , f'{mode}.txt' ) __UpperCamelCase : Dict = 1 __UpperCamelCase : List[str] = [] with open(a , encoding="utf-8" ) as f: for sentence in parse_incr(a ): __UpperCamelCase : Optional[int] = [] __UpperCamelCase : int = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(a ) == len(a ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=a , labels=a ) ) guid_index += 1 return examples def _lowerCamelCase ( self :List[Any] , a :TextIO , a :TextIO , a :List ) -> str: __UpperCamelCase : List[Any] = 0 for sentence in parse_incr(a ): __UpperCamelCase : Tuple = preds_list[example_id] __UpperCamelCase : Dict = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(a ) example_id += 1 def _lowerCamelCase ( self :List[str] , a :str ) -> List[str]: if path: with open(a , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
557
0
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated lowerCAmelCase_ : List[Any] = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ lowerCAmelCase_ : Dict = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _lowerCamelCase (__lowerCamelCase : str ) -> List[str]: a__ = numpy.dtype(numpy.uintaa ).newbyteorder(">" ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__lowerCamelCase )[0] @deprecated(__lowerCamelCase , "Please use tf.data to implement this functionality." ) def _lowerCamelCase (__lowerCamelCase : List[str] ) -> List[str]: print("Extracting" , f.name ) with gzip.GzipFile(fileobj=__lowerCamelCase ) as bytestream: a__ = _readaa(__lowerCamelCase ) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) a__ = _readaa(__lowerCamelCase ) a__ = _readaa(__lowerCamelCase ) a__ = _readaa(__lowerCamelCase ) a__ = bytestream.read(rows * cols * num_images ) a__ = numpy.frombuffer(__lowerCamelCase , dtype=numpy.uinta ) a__ = data.reshape(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , 1 ) return data @deprecated(__lowerCamelCase , "Please use tf.one_hot on tensors." ) def _lowerCamelCase (__lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] ) -> Dict: a__ = labels_dense.shape[0] a__ = numpy.arange(__lowerCamelCase ) * num_classes a__ = numpy.zeros((num_labels, num_classes) ) a__ = 1 return labels_one_hot @deprecated(__lowerCamelCase , "Please use tf.data to implement this functionality." ) def _lowerCamelCase (__lowerCamelCase : List[str] , __lowerCamelCase : Tuple=False , __lowerCamelCase : Dict=10 ) -> Any: print("Extracting" , f.name ) with gzip.GzipFile(fileobj=__lowerCamelCase ) as bytestream: a__ = _readaa(__lowerCamelCase ) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) a__ = _readaa(__lowerCamelCase ) a__ = bytestream.read(__lowerCamelCase ) a__ = numpy.frombuffer(__lowerCamelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__lowerCamelCase , __lowerCamelCase ) return labels class UpperCamelCase__ : @deprecated( lowerCamelCase , "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models." , ) def __init__( self : List[str] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Any , lowerCamelCase : str=False , lowerCamelCase : Tuple=False , lowerCamelCase : Optional[int]=dtypes.floataa , lowerCamelCase : List[str]=True , lowerCamelCase : Dict=None , ): '''simple docstring''' a__ , a__ = random_seed.get_seed(lowerCamelCase ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) a__ = dtypes.as_dtype(lowerCamelCase ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype ) if fake_data: a__ = 1_0_0_0_0 a__ = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F'''images.shape: {images.shape} labels.shape: {labels.shape}''' a__ = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 a__ = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. a__ = images.astype(numpy.floataa ) a__ = numpy.multiply(lowerCamelCase , 1.0 / 255.0 ) a__ = images a__ = labels a__ = 0 a__ = 0 @property def __a ( self : Tuple ): '''simple docstring''' return self._images @property def __a ( self : Tuple ): '''simple docstring''' return self._labels @property def __a ( self : Any ): '''simple docstring''' return self._num_examples @property def __a ( self : Any ): '''simple docstring''' return self._epochs_completed def __a ( self : List[str] , lowerCamelCase : str , lowerCamelCase : Any=False , lowerCamelCase : List[Any]=True ): '''simple docstring''' if fake_data: a__ = [1] * 7_8_4 a__ = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(lowerCamelCase )], [fake_label for _ in range(lowerCamelCase )], ) a__ = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: a__ = numpy.arange(self._num_examples ) numpy.random.shuffle(lowerCamelCase ) a__ = self.images[perma] a__ = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch a__ = self._num_examples - start a__ = self._images[start : self._num_examples] a__ = self._labels[start : self._num_examples] # Shuffle the data if shuffle: a__ = numpy.arange(self._num_examples ) numpy.random.shuffle(lowerCamelCase ) a__ = self.images[perm] a__ = self.labels[perm] # Start next epoch a__ = 0 a__ = batch_size - rest_num_examples a__ = self._index_in_epoch a__ = self._images[start:end] a__ = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size a__ = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__lowerCamelCase , "Please write your own downloading logic." ) def _lowerCamelCase (__lowerCamelCase : Optional[int] , __lowerCamelCase : int , __lowerCamelCase : List[Any] ) -> Tuple: if not gfile.Exists(__lowerCamelCase ): gfile.MakeDirs(__lowerCamelCase ) a__ = os.path.join(__lowerCamelCase , __lowerCamelCase ) if not gfile.Exists(__lowerCamelCase ): urllib.request.urlretrieve(__lowerCamelCase , __lowerCamelCase ) # noqa: S310 with gfile.GFile(__lowerCamelCase ) as f: a__ = f.size() print("Successfully downloaded" , __lowerCamelCase , __lowerCamelCase , "bytes." ) return filepath @deprecated( __lowerCamelCase , "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def _lowerCamelCase (__lowerCamelCase : List[Any] , __lowerCamelCase : Optional[Any]=False , __lowerCamelCase : Dict=False , __lowerCamelCase : Union[str, Any]=dtypes.floataa , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : int=5000 , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=DEFAULT_SOURCE_URL , ) -> int: if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__lowerCamelCase , one_hot=__lowerCamelCase , dtype=__lowerCamelCase , seed=__lowerCamelCase ) a__ = fake() a__ = fake() a__ = fake() return _Datasets(train=__lowerCamelCase , validation=__lowerCamelCase , test=__lowerCamelCase ) if not source_url: # empty string check a__ = DEFAULT_SOURCE_URL a__ = "train-images-idx3-ubyte.gz" a__ = "train-labels-idx1-ubyte.gz" a__ = "t10k-images-idx3-ubyte.gz" a__ = "t10k-labels-idx1-ubyte.gz" a__ = _maybe_download( __lowerCamelCase , __lowerCamelCase , source_url + train_images_file ) with gfile.Open(__lowerCamelCase , "rb" ) as f: a__ = _extract_images(__lowerCamelCase ) a__ = _maybe_download( __lowerCamelCase , __lowerCamelCase , source_url + train_labels_file ) with gfile.Open(__lowerCamelCase , "rb" ) as f: a__ = _extract_labels(__lowerCamelCase , one_hot=__lowerCamelCase ) a__ = _maybe_download( __lowerCamelCase , __lowerCamelCase , source_url + test_images_file ) with gfile.Open(__lowerCamelCase , "rb" ) as f: a__ = _extract_images(__lowerCamelCase ) a__ = _maybe_download( __lowerCamelCase , __lowerCamelCase , source_url + test_labels_file ) with gfile.Open(__lowerCamelCase , "rb" ) as f: a__ = _extract_labels(__lowerCamelCase , one_hot=__lowerCamelCase ) if not 0 <= validation_size <= len(__lowerCamelCase ): a__ = ( "Validation size should be between 0 and " f'''{len(__lowerCamelCase )}. Received: {validation_size}.''' ) raise ValueError(__lowerCamelCase ) a__ = train_images[:validation_size] a__ = train_labels[:validation_size] a__ = train_images[validation_size:] a__ = train_labels[validation_size:] a__ = {"dtype": dtype, "reshape": reshape, "seed": seed} a__ = _DataSet(__lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) a__ = _DataSet(__lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) a__ = _DataSet(__lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) return _Datasets(train=__lowerCamelCase , validation=__lowerCamelCase , test=__lowerCamelCase )
706
'''simple docstring''' import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def _lowerCamelCase (__lowerCamelCase : Tuple , __lowerCamelCase : Dict ) -> Tuple: a__ = XCLIPTextConfig() # derive patch size from model name a__ = model_name.find("patch" ) a__ = int(model_name[start_idx + len("patch" ) : start_idx + len("patch" ) + 2] ) a__ = XCLIPVisionConfig(patch_size=__lowerCamelCase , num_frames=__lowerCamelCase ) if "large" in model_name: a__ = 768 a__ = 3072 a__ = 12 a__ = 1024 a__ = 4096 a__ = 16 a__ = 24 a__ = 768 a__ = 3072 if model_name == "xclip-large-patch14-16-frames": a__ = 336 a__ = XCLIPConfig.from_text_vision_configs(__lowerCamelCase , __lowerCamelCase ) if "large" in model_name: a__ = 768 return config def _lowerCamelCase (__lowerCamelCase : Optional[int] ) -> List[str]: # text encoder if name == "token_embedding.weight": a__ = name.replace("token_embedding.weight" , "text_model.embeddings.token_embedding.weight" ) if name == "positional_embedding": a__ = name.replace("positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "ln_1" in name: a__ = name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: a__ = name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: a__ = name.replace("c_fc" , "fc1" ) if "c_proj" in name: a__ = name.replace("c_proj" , "fc2" ) if name.startswith("transformer.resblocks" ): a__ = name.replace("transformer.resblocks" , "text_model.encoder.layers" ) if "attn.out_proj" in name and "message" not in name: a__ = name.replace("attn.out_proj" , "self_attn.out_proj" ) if "ln_final" in name: a__ = name.replace("ln_final" , "text_model.final_layer_norm" ) # visual encoder if name == "visual.class_embedding": a__ = name.replace("visual.class_embedding" , "vision_model.embeddings.class_embedding" ) if name == "visual.positional_embedding": a__ = name.replace("visual.positional_embedding" , "vision_model.embeddings.position_embedding.weight" ) if name.startswith("visual.transformer.resblocks" ): a__ = name.replace("visual.transformer.resblocks" , "vision_model.encoder.layers" ) if "visual.conv1" in name: a__ = name.replace("visual.conv1" , "vision_model.embeddings.patch_embedding" ) if "visual.ln_pre" in name: a__ = name.replace("visual.ln_pre" , "vision_model.pre_layernorm" ) if "visual.ln_post" in name: a__ = name.replace("visual.ln_post" , "vision_model.post_layernorm" ) if "visual.proj" in name: a__ = name.replace("visual.proj" , "visual_projection.weight" ) if "text_projection" in name: a__ = name.replace("text_projection" , "text_projection.weight" ) # things on top if "prompts_visual_proj" in name: a__ = name.replace("prompts_visual_proj" , "prompts_visual_projection" ) if "prompts_visual_ln" in name: a__ = name.replace("prompts_visual_ln" , "prompts_visual_layernorm" ) # mit if name == "mit.positional_embedding": a__ = name.replace("positional" , "position" ) if name.startswith("mit.resblocks" ): a__ = name.replace("mit.resblocks" , "mit.encoder.layers" ) # prompts generator if name.startswith("prompts_generator.norm" ): a__ = name.replace("prompts_generator.norm" , "prompts_generator.layernorm" ) return name def _lowerCamelCase (__lowerCamelCase : Any , __lowerCamelCase : str ) -> Optional[Any]: for key in orig_state_dict.copy().keys(): a__ = orig_state_dict.pop(__lowerCamelCase ) if "attn.in_proj" in key: a__ = key.split("." ) if key.startswith("visual" ): a__ = key_split[3] a__ = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: a__ = val[ :dim, : ] a__ = val[ dim : dim * 2, : ] a__ = val[ -dim:, : ] else: a__ = val[ :dim ] a__ = val[ dim : dim * 2 ] a__ = val[ -dim: ] else: if "weight" in key: a__ = val[ :dim, : ] a__ = val[ dim : dim * 2, : ] a__ = val[ -dim:, : ] else: a__ = val[:dim] a__ = val[ dim : dim * 2 ] a__ = val[-dim:] elif key.startswith("mit" ): a__ = key_split[2] a__ = config.vision_config.mit_hidden_size if "weight" in key: a__ = val[:dim, :] a__ = val[dim : dim * 2, :] a__ = val[-dim:, :] else: a__ = val[:dim] a__ = val[dim : dim * 2] a__ = val[-dim:] else: a__ = key_split[2] a__ = config.text_config.hidden_size if "weight" in key: a__ = val[:dim, :] a__ = val[ dim : dim * 2, : ] a__ = val[-dim:, :] else: a__ = val[:dim] a__ = val[ dim : dim * 2 ] a__ = val[-dim:] else: a__ = rename_key(__lowerCamelCase ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: a__ = val.T a__ = val return orig_state_dict def _lowerCamelCase (__lowerCamelCase : List[Any] ) -> List[str]: if num_frames == 8: a__ = "eating_spaghetti_8_frames.npy" elif num_frames == 16: a__ = "eating_spaghetti.npy" elif num_frames == 32: a__ = "eating_spaghetti_32_frames.npy" a__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename=__lowerCamelCase , repo_type="dataset" , ) a__ = np.load(__lowerCamelCase ) return list(__lowerCamelCase ) def _lowerCamelCase (__lowerCamelCase : Tuple , __lowerCamelCase : Any=None , __lowerCamelCase : Optional[Any]=False ) -> Optional[Any]: a__ = { # fully supervised kinetics-400 checkpoints "xclip-base-patch32": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth", "xclip-base-patch32-16-frames": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth" ), "xclip-base-patch16": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth", "xclip-base-patch16-16-frames": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth" ), "xclip-large-patch14": "https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb", "xclip-large-patch14-16-frames": "https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f", # fully supervised kinetics-600 checkpoints "xclip-base-patch16-kinetics-600": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth" ), "xclip-base-patch16-kinetics-600-16-frames": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth" ), "xclip-large-patch14-kinetics-600": "https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be", # few shot "xclip-base-patch16-hmdb-2-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth" ), "xclip-base-patch16-hmdb-4-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth" ), "xclip-base-patch16-hmdb-8-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth" ), "xclip-base-patch16-hmdb-16-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth" ), "xclip-base-patch16-ucf-2-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth" ), "xclip-base-patch16-ucf-4-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth" ), "xclip-base-patch16-ucf-8-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth" ), "xclip-base-patch16-ucf-16-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth" ), # zero shot "xclip-base-patch16-zero-shot": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth", } a__ = model_to_url[model_name] a__ = 8 if "16-frames" in model_name: a__ = 16 elif "shot" in model_name: a__ = 32 a__ = get_xclip_config(__lowerCamelCase , __lowerCamelCase ) a__ = XCLIPModel(__lowerCamelCase ) model.eval() if "drive" in checkpoint_url: a__ = "pytorch_model.bin" gdown.cached_download(__lowerCamelCase , __lowerCamelCase , quiet=__lowerCamelCase ) a__ = torch.load(__lowerCamelCase , map_location="cpu" )["model"] else: a__ = torch.hub.load_state_dict_from_url(__lowerCamelCase )["model"] a__ = convert_state_dict(__lowerCamelCase , __lowerCamelCase ) a__ = XCLIPModel(__lowerCamelCase ) a__ , a__ = model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() a__ = 336 if model_name == "xclip-large-patch14-16-frames" else 224 a__ = VideoMAEImageProcessor(size=__lowerCamelCase ) a__ = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32" ) a__ = CLIPTokenizerFast.from_pretrained("openai/clip-vit-base-patch32" ) a__ = XCLIPProcessor(image_processor=__lowerCamelCase , tokenizer=__lowerCamelCase ) a__ = prepare_video(__lowerCamelCase ) a__ = processor( text=["playing sports", "eating spaghetti", "go shopping"] , videos=__lowerCamelCase , return_tensors="pt" , padding=__lowerCamelCase ) print("Shape of pixel values:" , inputs.pixel_values.shape ) with torch.no_grad(): a__ = model(**__lowerCamelCase ) # Verify outputs a__ = outputs.logits_per_video a__ = logits_per_video.softmax(dim=1 ) print("Probs:" , __lowerCamelCase ) # kinetics-400 if model_name == "xclip-base-patch32": a__ = torch.tensor([[0.0_019, 0.9_951, 0.0_030]] ) elif model_name == "xclip-base-patch32-16-frames": a__ = torch.tensor([[7.0999e-04, 9.9883e-01, 4.5580e-04]] ) elif model_name == "xclip-base-patch16": a__ = torch.tensor([[0.0_083, 0.9_681, 0.0_236]] ) elif model_name == "xclip-base-patch16-16-frames": a__ = torch.tensor([[7.6937e-04, 9.9728e-01, 1.9473e-03]] ) elif model_name == "xclip-large-patch14": a__ = torch.tensor([[0.0_062, 0.9_864, 0.0_075]] ) elif model_name == "xclip-large-patch14-16-frames": a__ = torch.tensor([[3.3877e-04, 9.9937e-01, 2.8888e-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": a__ = torch.tensor([[0.0_555, 0.8_914, 0.0_531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": a__ = torch.tensor([[3.8554e-04, 9.9929e-01, 3.2754e-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": a__ = torch.tensor([[0.0_036, 0.9_920, 0.0_045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": a__ = torch.tensor([[7.1890e-06, 9.9994e-01, 5.6559e-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": a__ = torch.tensor([[1.0320e-05, 9.9993e-01, 6.2435e-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": a__ = torch.tensor([[4.1377e-06, 9.9990e-01, 9.8386e-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": a__ = torch.tensor([[4.1347e-05, 9.9962e-01, 3.3411e-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": a__ = torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": a__ = torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": a__ = torch.tensor([[0.0_027, 0.9_904, 0.0_070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": a__ = torch.tensor([[9.8219e-04, 9.9593e-01, 3.0863e-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": a__ = torch.tensor([[3.5082e-04, 9.9785e-01, 1.7966e-03]] ) else: raise ValueError(f'''Model name {model_name} not supported''' ) assert torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) 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 ) if push_to_hub: print("Pushing model, processor and slow tokenizer files to the hub..." ) model.push_to_hub(__lowerCamelCase , organization="nielsr" ) processor.push_to_hub(__lowerCamelCase , organization="nielsr" ) slow_tokenizer.push_to_hub(__lowerCamelCase , organization="nielsr" ) if __name__ == "__main__": lowerCAmelCase_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="xclip-base-patch32", type=str, help="Name of the model.", ) 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." ) lowerCAmelCase_ : Dict = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
289
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __lowerCAmelCase = { 'configuration_convnext': ['CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvNextConfig', 'ConvNextOnnxConfig'] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = ['ConvNextFeatureExtractor'] __lowerCAmelCase = ['ConvNextImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ 'CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvNextForImageClassification', 'ConvNextModel', 'ConvNextPreTrainedModel', 'ConvNextBackbone', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ 'TFConvNextForImageClassification', 'TFConvNextModel', 'TFConvNextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure)
585
"""simple docstring""" import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort a = logging.get_logger(__name__) a = { '''tensor(bool)''': np.bool_, '''tensor(int8)''': np.inta, '''tensor(uint8)''': np.uinta, '''tensor(int16)''': np.intaa, '''tensor(uint16)''': np.uintaa, '''tensor(int32)''': np.intaa, '''tensor(uint32)''': np.uintaa, '''tensor(int64)''': np.intaa, '''tensor(uint64)''': np.uintaa, '''tensor(float16)''': np.floataa, '''tensor(float)''': np.floataa, '''tensor(double)''': np.floataa, } class lowercase_ : '''simple docstring''' def __init__( self : Optional[Any] , _UpperCAmelCase : Dict=None , **_UpperCAmelCase : Optional[Any] ): logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.' ) _A = model _A = kwargs.get('model_save_dir' , _UpperCAmelCase ) _A = kwargs.get('latest_model_name' , _UpperCAmelCase ) def __call__( self : Dict , **_UpperCAmelCase : List[Any] ): _A = {k: np.array(_UpperCAmelCase ) for k, v in kwargs.items()} return self.model.run(_UpperCAmelCase , _UpperCAmelCase ) @staticmethod def lowerCAmelCase_ ( _UpperCAmelCase : Union[str, Path] , _UpperCAmelCase : List[str]=None , _UpperCAmelCase : List[Any]=None ): if provider is None: logger.info('No onnxruntime provider specified, using CPUExecutionProvider' ) _A = 'CPUExecutionProvider' return ort.InferenceSession(_UpperCAmelCase , providers=[provider] , sess_options=_UpperCAmelCase ) def lowerCAmelCase_ ( self : int , _UpperCAmelCase : Union[str, Path] , _UpperCAmelCase : Optional[str] = None , **_UpperCAmelCase : List[Any] ): _A = file_name if file_name is not None else ONNX_WEIGHTS_NAME _A = self.model_save_dir.joinpath(self.latest_model_name ) _A = Path(_UpperCAmelCase ).joinpath(_UpperCAmelCase ) try: shutil.copyfile(_UpperCAmelCase , _UpperCAmelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) _A = self.model_save_dir.joinpath(_UpperCAmelCase ) if src_path.exists(): _A = Path(_UpperCAmelCase ).joinpath(_UpperCAmelCase ) try: shutil.copyfile(_UpperCAmelCase , _UpperCAmelCase ) except shutil.SameFileError: pass def lowerCAmelCase_ ( self : List[Any] , _UpperCAmelCase : Union[str, os.PathLike] , **_UpperCAmelCase : List[str] , ): if os.path.isfile(_UpperCAmelCase ): logger.error(F'''Provided path ({save_directory}) should be a directory, not a file''' ) return os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase ) # saving model weights/files self._save_pretrained(_UpperCAmelCase , **_UpperCAmelCase ) @classmethod def lowerCAmelCase_ ( cls : Tuple , _UpperCAmelCase : Union[str, Path] , _UpperCAmelCase : Optional[Union[bool, str, None]] = None , _UpperCAmelCase : Optional[Union[str, None]] = None , _UpperCAmelCase : bool = False , _UpperCAmelCase : Optional[str] = None , _UpperCAmelCase : Optional[str] = None , _UpperCAmelCase : Optional[str] = None , _UpperCAmelCase : Optional["ort.SessionOptions"] = None , **_UpperCAmelCase : Union[str, Any] , ): _A = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_UpperCAmelCase ): _A = OnnxRuntimeModel.load_model( os.path.join(_UpperCAmelCase , _UpperCAmelCase ) , provider=_UpperCAmelCase , sess_options=_UpperCAmelCase ) _A = Path(_UpperCAmelCase ) # load model from hub else: # download model _A = hf_hub_download( repo_id=_UpperCAmelCase , filename=_UpperCAmelCase , use_auth_token=_UpperCAmelCase , revision=_UpperCAmelCase , cache_dir=_UpperCAmelCase , force_download=_UpperCAmelCase , ) _A = Path(_UpperCAmelCase ).parent _A = Path(_UpperCAmelCase ).name _A = OnnxRuntimeModel.load_model(_UpperCAmelCase , provider=_UpperCAmelCase , sess_options=_UpperCAmelCase ) return cls(model=_UpperCAmelCase , **_UpperCAmelCase ) @classmethod def lowerCAmelCase_ ( cls : List[Any] , _UpperCAmelCase : Union[str, Path] , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[str] = None , _UpperCAmelCase : Optional[str] = None , **_UpperCAmelCase : Tuple , ): _A = None if len(str(_UpperCAmelCase ).split('@' ) ) == 2: _A , _A = model_id.split('@' ) return cls._from_pretrained( model_id=_UpperCAmelCase , revision=_UpperCAmelCase , cache_dir=_UpperCAmelCase , force_download=_UpperCAmelCase , use_auth_token=_UpperCAmelCase , **_UpperCAmelCase , )
7
0
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml __lowercase : Dict =NewType("""DataClass""", Any) __lowercase : Any =NewType("""DataClassType""", Any) def a__ ( lowercase__ : Dict ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).' ) def a__ ( lowercase__ : Dict ): '''simple docstring''' UpperCAmelCase_ ={str(lowercase__ ): choice for choice in choices} return lambda lowercase__ : str_to_choice.get(lowercase__ , lowercase__ ) def a__ ( *, lowercase__ : Tuple = None , lowercase__ : Optional[int] = None , lowercase__ : Optional[Any] = dataclasses.MISSING , lowercase__ : Optional[int] = dataclasses.MISSING , lowercase__ : Tuple = None , **lowercase__ : str , ): '''simple docstring''' if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls UpperCAmelCase_ ={} if aliases is not None: UpperCAmelCase_ =aliases if help is not None: UpperCAmelCase_ =help return dataclasses.field(metadata=lowercase__ , default=lowercase__ , default_factory=lowercase__ , **lowercase__ ) class A ( __lowercase ): _snake_case =42 def __init__( self: int , _lowerCAmelCase: Union[DataClassType, Iterable[DataClassType]] , **_lowerCAmelCase: List[str] ) -> Optional[Any]: '''simple docstring''' if "formatter_class" not in kwargs: UpperCAmelCase_ =ArgumentDefaultsHelpFormatter super().__init__(**_lowerCAmelCase ) if dataclasses.is_dataclass(_lowerCAmelCase ): UpperCAmelCase_ =[dataclass_types] UpperCAmelCase_ =list(_lowerCAmelCase ) for dtype in self.dataclass_types: self._add_dataclass_arguments(_lowerCAmelCase ) @staticmethod def lowerCAmelCase__ ( _lowerCAmelCase: ArgumentParser , _lowerCAmelCase: dataclasses.Field ) -> Tuple: '''simple docstring''' UpperCAmelCase_ =F'--{field.name}' UpperCAmelCase_ =field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , _lowerCAmelCase ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) UpperCAmelCase_ =kwargs.pop("aliases" , [] ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase_ =[aliases] UpperCAmelCase_ =getattr(field.type , "__origin__" , field.type ) if origin_type is Union or (hasattr(_lowerCAmelCase , "UnionType" ) and isinstance(_lowerCAmelCase , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(_lowerCAmelCase ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." F' Problem encountered in field \'{field.name}\'.' ) if type(_lowerCAmelCase ) not in field.type.__args__: # filter `str` in Union UpperCAmelCase_ =field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] UpperCAmelCase_ =getattr(field.type , "__origin__" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) UpperCAmelCase_ =( field.type.__args__[0] if isinstance(_lowerCAmelCase , field.type.__args__[1] ) else field.type.__args__[1] ) UpperCAmelCase_ =getattr(field.type , "__origin__" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) UpperCAmelCase_ ={} if origin_type is Literal or (isinstance(field.type , _lowerCAmelCase ) and issubclass(field.type , _lowerCAmelCase )): if origin_type is Literal: UpperCAmelCase_ =field.type.__args__ else: UpperCAmelCase_ =[x.value for x in field.type] UpperCAmelCase_ =make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: UpperCAmelCase_ =field.default else: UpperCAmelCase_ =True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument UpperCAmelCase_ =copy(_lowerCAmelCase ) # Hack because type=bool in argparse does not behave as we want. UpperCAmelCase_ =string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. UpperCAmelCase_ =False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way UpperCAmelCase_ =default # This tells argparse we accept 0 or 1 value after --field_name UpperCAmelCase_ ="?" # This is the value that will get picked if we do --field_name (without value) UpperCAmelCase_ =True elif isclass(_lowerCAmelCase ) and issubclass(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase_ =field.type.__args__[0] UpperCAmelCase_ ="+" if field.default_factory is not dataclasses.MISSING: UpperCAmelCase_ =field.default_factory() elif field.default is dataclasses.MISSING: UpperCAmelCase_ =True else: UpperCAmelCase_ =field.type if field.default is not dataclasses.MISSING: UpperCAmelCase_ =field.default elif field.default_factory is not dataclasses.MISSING: UpperCAmelCase_ =field.default_factory() else: UpperCAmelCase_ =True parser.add_argument(_lowerCAmelCase , *_lowerCAmelCase , **_lowerCAmelCase ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): UpperCAmelCase_ =False parser.add_argument(F'--no_{field.name}' , action="store_false" , dest=field.name , **_lowerCAmelCase ) def lowerCAmelCase__ ( self: str , _lowerCAmelCase: DataClassType ) -> Dict: '''simple docstring''' if hasattr(_lowerCAmelCase , "_argument_group_name" ): UpperCAmelCase_ =self.add_argument_group(dtype._argument_group_name ) else: UpperCAmelCase_ =self try: UpperCAmelCase_ =get_type_hints(_lowerCAmelCase ) except NameError: raise RuntimeError( F'Type resolution failed for {dtype}. Try declaring the class in global scope or ' "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(_lowerCAmelCase ): UpperCAmelCase_ =".".join(map(_lowerCAmelCase , sys.version_info[:3] ) ) raise RuntimeError( F'Type resolution failed for {dtype} on Python {python_version}. Try removing ' "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(_lowerCAmelCase ): if not field.init: continue UpperCAmelCase_ =type_hints[field.name] self._parse_dataclass_field(_lowerCAmelCase , _lowerCAmelCase ) def lowerCAmelCase__ ( self: Dict , _lowerCAmelCase: List[Any]=None , _lowerCAmelCase: List[str]=False , _lowerCAmelCase: Any=True , _lowerCAmelCase: List[str]=None , _lowerCAmelCase: Optional[int]=None , ) -> Tuple[DataClass, ...]: '''simple docstring''' if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): UpperCAmelCase_ =[] if args_filename: args_files.append(Path(_lowerCAmelCase ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values UpperCAmelCase_ =ArgumentParser() args_file_parser.add_argument(_lowerCAmelCase , type=_lowerCAmelCase , action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) UpperCAmelCase_ , UpperCAmelCase_ =args_file_parser.parse_known_args(args=_lowerCAmelCase ) UpperCAmelCase_ =vars(_lowerCAmelCase ).get(args_file_flag.lstrip("-" ) , _lowerCAmelCase ) if cmd_args_file_paths: args_files.extend([Path(_lowerCAmelCase ) for p in cmd_args_file_paths] ) UpperCAmelCase_ =[] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last UpperCAmelCase_ =file_args + args if args is not None else file_args + sys.argv[1:] UpperCAmelCase_ , UpperCAmelCase_ =self.parse_known_args(args=_lowerCAmelCase ) UpperCAmelCase_ =[] for dtype in self.dataclass_types: UpperCAmelCase_ ={f.name for f in dataclasses.fields(_lowerCAmelCase ) if f.init} UpperCAmelCase_ ={k: v for k, v in vars(_lowerCAmelCase ).items() if k in keys} for k in keys: delattr(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase_ =dtype(**_lowerCAmelCase ) outputs.append(_lowerCAmelCase ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(_lowerCAmelCase ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F'Some specified arguments are not used by the HfArgumentParser: {remaining_args}' ) return (*outputs,) def lowerCAmelCase__ ( self: Optional[int] , _lowerCAmelCase: Dict[str, Any] , _lowerCAmelCase: bool = False ) -> Tuple[DataClass, ...]: '''simple docstring''' UpperCAmelCase_ =set(args.keys() ) UpperCAmelCase_ =[] for dtype in self.dataclass_types: UpperCAmelCase_ ={f.name for f in dataclasses.fields(_lowerCAmelCase ) if f.init} UpperCAmelCase_ ={k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) UpperCAmelCase_ =dtype(**_lowerCAmelCase ) outputs.append(_lowerCAmelCase ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(_lowerCAmelCase )}' ) return tuple(_lowerCAmelCase ) def lowerCAmelCase__ ( self: str , _lowerCAmelCase: str , _lowerCAmelCase: bool = False ) -> Tuple[DataClass, ...]: '''simple docstring''' with open(Path(_lowerCAmelCase ) , encoding="utf-8" ) as open_json_file: UpperCAmelCase_ =json.loads(open_json_file.read() ) UpperCAmelCase_ =self.parse_dict(_lowerCAmelCase , allow_extra_keys=_lowerCAmelCase ) return tuple(_lowerCAmelCase ) def lowerCAmelCase__ ( self: List[Any] , _lowerCAmelCase: str , _lowerCAmelCase: bool = False ) -> Tuple[DataClass, ...]: '''simple docstring''' UpperCAmelCase_ =self.parse_dict(yaml.safe_load(Path(_lowerCAmelCase ).read_text() ) , allow_extra_keys=_lowerCAmelCase ) return tuple(_lowerCAmelCase )
701
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class A ( __lowercase ): _snake_case =(DDIMParallelScheduler,) _snake_case =(('''eta''', 0.0), ('''num_inference_steps''', 50)) def lowerCAmelCase__ ( self: str , **_lowerCAmelCase: str ) -> str: '''simple docstring''' UpperCAmelCase_ ={ "num_train_timesteps": 1000, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**_lowerCAmelCase ) return config def lowerCAmelCase__ ( self: int , **_lowerCAmelCase: Tuple ) -> str: '''simple docstring''' UpperCAmelCase_ =self.scheduler_classes[0] UpperCAmelCase_ =self.get_scheduler_config(**_lowerCAmelCase ) UpperCAmelCase_ =scheduler_class(**_lowerCAmelCase ) UpperCAmelCase_ , UpperCAmelCase_ =10, 0.0 UpperCAmelCase_ =self.dummy_model() UpperCAmelCase_ =self.dummy_sample_deter scheduler.set_timesteps(_lowerCAmelCase ) for t in scheduler.timesteps: UpperCAmelCase_ =model(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase_ =scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ).prev_sample return sample def lowerCAmelCase__ ( self: Optional[int] ) -> Optional[int]: '''simple docstring''' for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=_lowerCAmelCase ) def lowerCAmelCase__ ( self: int ) -> List[str]: '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=_lowerCAmelCase ) UpperCAmelCase_ =self.scheduler_classes[0] UpperCAmelCase_ =self.get_scheduler_config(steps_offset=1 ) UpperCAmelCase_ =scheduler_class(**_lowerCAmelCase ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def lowerCAmelCase__ ( self: int ) -> Dict: '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_lowerCAmelCase , beta_end=_lowerCAmelCase ) def lowerCAmelCase__ ( self: int ) -> Any: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_lowerCAmelCase ) def lowerCAmelCase__ ( self: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_lowerCAmelCase ) def lowerCAmelCase__ ( self: Optional[int] ) -> Tuple: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=_lowerCAmelCase ) def lowerCAmelCase__ ( self: Union[str, Any] ) -> List[Any]: '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=_lowerCAmelCase ) def lowerCAmelCase__ ( self: Union[str, Any] ) -> Any: '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=_lowerCAmelCase ) def lowerCAmelCase__ ( self: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' self.check_over_configs(thresholding=_lowerCAmelCase ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=_lowerCAmelCase , prediction_type=_lowerCAmelCase , sample_max_value=_lowerCAmelCase , ) def lowerCAmelCase__ ( self: Union[str, Any] ) -> List[str]: '''simple docstring''' for t in [1, 10, 49]: self.check_over_forward(time_step=_lowerCAmelCase ) def lowerCAmelCase__ ( self: Any ) -> List[str]: '''simple docstring''' for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=_lowerCAmelCase , num_inference_steps=_lowerCAmelCase ) def lowerCAmelCase__ ( self: int ) -> Tuple: '''simple docstring''' for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=_lowerCAmelCase , eta=_lowerCAmelCase ) def lowerCAmelCase__ ( self: Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ =self.scheduler_classes[0] UpperCAmelCase_ =self.get_scheduler_config() UpperCAmelCase_ =scheduler_class(**_lowerCAmelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.1_47_71 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.3_24_60 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def lowerCAmelCase__ ( self: int ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ =self.scheduler_classes[0] UpperCAmelCase_ =self.get_scheduler_config() UpperCAmelCase_ =scheduler_class(**_lowerCAmelCase ) UpperCAmelCase_ , UpperCAmelCase_ =10, 0.0 scheduler.set_timesteps(_lowerCAmelCase ) UpperCAmelCase_ =self.dummy_model() UpperCAmelCase_ =self.dummy_sample_deter UpperCAmelCase_ =self.dummy_sample_deter + 0.1 UpperCAmelCase_ =self.dummy_sample_deter - 0.1 UpperCAmelCase_ =samplea.shape[0] UpperCAmelCase_ =torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCAmelCase_ =torch.arange(_lowerCAmelCase )[0:3, None].repeat(1 , _lowerCAmelCase ) UpperCAmelCase_ =model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCAmelCase_ =scheduler.batch_step_no_noise(_lowerCAmelCase , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , _lowerCAmelCase ) UpperCAmelCase_ =torch.sum(torch.abs(_lowerCAmelCase ) ) UpperCAmelCase_ =torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 11_47.79_04 ) < 1e-2 assert abs(result_mean.item() - 0.49_82 ) < 1e-3 def lowerCAmelCase__ ( self: Optional[int] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ =self.full_loop() UpperCAmelCase_ =torch.sum(torch.abs(_lowerCAmelCase ) ) UpperCAmelCase_ =torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 1_72.00_67 ) < 1e-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1e-3 def lowerCAmelCase__ ( self: int ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ =self.full_loop(prediction_type="v_prediction" ) UpperCAmelCase_ =torch.sum(torch.abs(_lowerCAmelCase ) ) UpperCAmelCase_ =torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 52.53_02 ) < 1e-2 assert abs(result_mean.item() - 0.06_84 ) < 1e-3 def lowerCAmelCase__ ( self: Optional[Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ =self.full_loop(set_alpha_to_one=_lowerCAmelCase , beta_start=0.01 ) UpperCAmelCase_ =torch.sum(torch.abs(_lowerCAmelCase ) ) UpperCAmelCase_ =torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 1_49.82_95 ) < 1e-2 assert abs(result_mean.item() - 0.19_51 ) < 1e-3 def lowerCAmelCase__ ( self: Optional[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ =self.full_loop(set_alpha_to_one=_lowerCAmelCase , beta_start=0.01 ) UpperCAmelCase_ =torch.sum(torch.abs(_lowerCAmelCase ) ) UpperCAmelCase_ =torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 1_49.07_84 ) < 1e-2 assert abs(result_mean.item() - 0.19_41 ) < 1e-3
550
0
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging SCREAMING_SNAKE_CASE :Optional[int] = '''\ ''' SCREAMING_SNAKE_CASE :Optional[Any] = ''' Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity ''' SCREAMING_SNAKE_CASE :str = ''' Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to \'cuda\' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] >>> results = perplexity.compute(model_id=\'gpt2\', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 78.22 >>> print(round(results["perplexities"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = datasets.load_dataset("wikitext", ... "wikitext-2-raw-v1", ... split="test")["text"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=\'\'] >>> results = perplexity.compute(model_id=\'gpt2\', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 60.35 >>> print(round(results["perplexities"][0], 2)) 81.12 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): """simple docstring""" def lowerCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "input_texts": datasets.Value("string" ), } ) , reference_urls=["https://huggingface.co/docs/transformers/perplexity"] , ) def lowerCAmelCase__ ( self : str , _lowerCAmelCase : str , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[str] = 1_6 , _lowerCAmelCase : int = True , _lowerCAmelCase : List[str]=None ) -> Union[str, Any]: """simple docstring""" if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": snake_case_ = "cuda" else: snake_case_ = "cuda" if torch.cuda.is_available() else "cpu" snake_case_ = AutoModelForCausalLM.from_pretrained(A_ ) snake_case_ = model.to(A_ ) snake_case_ = AutoTokenizer.from_pretrained(A_ ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: snake_case_ = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(A_ ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" snake_case_ = model.config.max_length - 1 else: snake_case_ = model.config.max_length snake_case_ = tokenizer( A_ , add_special_tokens=A_ , padding=A_ , truncation=A_ , max_length=A_ , return_tensors="pt" , return_attention_mask=A_ , ).to(A_ ) snake_case_ = encodings["input_ids"] snake_case_ = encodings["attention_mask"] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." snake_case_ = [] snake_case_ = CrossEntropyLoss(reduction="none" ) for start_index in logging.tqdm(range(0 , len(A_ ) , A_ ) ): snake_case_ = min(start_index + batch_size , len(A_ ) ) snake_case_ = encoded_texts[start_index:end_index] snake_case_ = attn_masks[start_index:end_index] if add_start_token: snake_case_ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(A_ ) snake_case_ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) snake_case_ = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(A_ ), attn_mask] , dim=1 ) snake_case_ = encoded_batch with torch.no_grad(): snake_case_ = model(A_ , attention_mask=A_ ).logits snake_case_ = out_logits[..., :-1, :].contiguous() snake_case_ = labels[..., 1:].contiguous() snake_case_ = attn_mask[..., 1:].contiguous() snake_case_ = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , A_ ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(A_ )}
283
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class A_ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCAmelCase = None class A_ ( datasets.ArrowBasedBuilder ): '''simple docstring''' _lowerCAmelCase = PandasConfig def a ( self ): return datasets.DatasetInfo(features=self.config.features ) def a ( self , A_ ): if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}" ) _UpperCamelCase = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A_ , (str, list, tuple) ): _UpperCamelCase = data_files if isinstance(A_ , A_ ): _UpperCamelCase = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _UpperCamelCase = [dl_manager.iter_files(A_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )] _UpperCamelCase = [] for split_name, files in data_files.items(): if isinstance(A_ , A_ ): _UpperCamelCase = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _UpperCamelCase = [dl_manager.iter_files(A_ ) for file in files] splits.append(datasets.SplitGenerator(name=A_ , gen_kwargs={"files": files} ) ) return splits def a ( self , A_ ): if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _UpperCamelCase = table_cast(A_ , self.config.features.arrow_schema ) return pa_table def a ( self , A_ ): for i, file in enumerate(itertools.chain.from_iterable(A_ ) ): with open(A_ , "rb" ) as f: _UpperCamelCase = pa.Table.from_pandas(pd.read_pickle(A_ ) ) yield i, self._cast_table(A_ )
138
0
import argparse import datetime def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> str: snake_case__ = { '''0''': '''Sunday''', '''1''': '''Monday''', '''2''': '''Tuesday''', '''3''': '''Wednesday''', '''4''': '''Thursday''', '''5''': '''Friday''', '''6''': '''Saturday''', } snake_case__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(__lowerCAmelCase ) < 11: raise ValueError('''Must be 10 characters long''' ) # Get month snake_case__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError('''Month must be between 1 - 12''' ) snake_case__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('''Date separator must be \'-\' or \'/\'''' ) # Get day snake_case__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError('''Date must be between 1 - 31''' ) # Get second separator snake_case__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('''Date separator must be \'-\' or \'/\'''' ) # Get year snake_case__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8500: raise ValueError( '''Year out of range. There has to be some sort of limit...right?''' ) # Get datetime obj for validation snake_case__ = datetime.date(int(__lowerCAmelCase ) , int(__lowerCAmelCase ) , int(__lowerCAmelCase ) ) # Start math if m <= 2: snake_case__ = y - 1 snake_case__ = m + 12 # maths var snake_case__ = int(str(__lowerCAmelCase )[:2] ) snake_case__ = int(str(__lowerCAmelCase )[2:] ) snake_case__ = int(2.6 * m - 5.39 ) snake_case__ = int(c / 4 ) snake_case__ = int(k / 4 ) snake_case__ = int(d + k ) snake_case__ = int(t + u + v + x ) snake_case__ = int(z - (2 * c) ) snake_case__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('''The date was evaluated incorrectly. Contact developer.''' ) # Response snake_case__ = F"""Your date {date_input}, is a {days[str(__lowerCAmelCase )]}!""" return response if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ : Union[str, Any] = argparse.ArgumentParser( description=( """Find out what day of the week nearly any date is or was. Enter """ """date as a string in the mm-dd-yyyy or mm/dd/yyyy format""" ) ) parser.add_argument( """date_input""", type=str, help="""Date as a string (mm-dd-yyyy or mm/dd/yyyy)""" ) lowerCamelCase__ : Union[str, Any] = parser.parse_args() zeller(args.date_input)
720
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase__ : List[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class __magic_name__ (snake_case_ ,unittest.TestCase ): '''simple docstring''' __lowercase : int = XGLMTokenizer __lowercase : List[Any] = XGLMTokenizerFast __lowercase : List[str] = True __lowercase : int = True def SCREAMING_SNAKE_CASE__ ( self:int ): super().setUp() # We have a SentencePiece fixture for testing snake_case__ = XGLMTokenizer(_a , keep_accents=_a ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ): snake_case__ = '''<pad>''' snake_case__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def SCREAMING_SNAKE_CASE__ ( self:List[str] ): snake_case__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(_a ) , 10_08 ) def SCREAMING_SNAKE_CASE__ ( self:List[str] ): self.assertEqual(self.get_tokenizer().vocab_size , 10_08 ) def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ): snake_case__ = XGLMTokenizer(_a , keep_accents=_a ) snake_case__ = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_a , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) snake_case__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _a , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) snake_case__ = tokenizer.convert_tokens_to_ids(_a ) self.assertListEqual( _a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) snake_case__ = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def SCREAMING_SNAKE_CASE__ ( self:List[Any] ): return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def SCREAMING_SNAKE_CASE__ ( self:List[str] ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(_a , f.name ) snake_case__ = XGLMTokenizer(f.name , keep_accents=_a ) snake_case__ = pickle.dumps(_a ) pickle.loads(_a ) def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ): if not self.test_rust_tokenizer: return snake_case__ = self.get_tokenizer() snake_case__ = self.get_rust_tokenizer() snake_case__ = '''I was born in 92000, and this is falsé.''' snake_case__ = tokenizer.tokenize(_a ) snake_case__ = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) snake_case__ = tokenizer.encode(_a , add_special_tokens=_a ) snake_case__ = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) snake_case__ = self.get_rust_tokenizer() snake_case__ = tokenizer.encode(_a ) snake_case__ = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) @slow def SCREAMING_SNAKE_CASE__ ( self:List[str] ): snake_case__ = '''Hello World!''' snake_case__ = [2, 3_12_27, 44_47, 35] self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @slow def SCREAMING_SNAKE_CASE__ ( self:Union[str, Any] ): snake_case__ = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth''' ) # fmt: off snake_case__ = [2, 10_18, 67, 11, 19_88, 26_17, 56_31, 2_78, 11, 34_07, 48, 7_16_30, 2_80_85, 4, 32_34, 1_57, 13, 6, 5, 6, 4, 35_26, 7_68, 15, 6_59, 57, 2_98, 39_83, 8_64, 1_29, 21, 6, 5, 1_36_75, 3_77, 6_52, 75_80, 1_03_41, 1_55, 28_17, 4_22, 16_66, 7, 16_74, 53, 1_13, 20_22_77, 1_78_92, 33, 60, 87, 4, 32_34, 1_57, 61, 26_67, 5_23_76, 19, 88, 23, 7_35] # fmt: on self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @slow def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ): # fmt: off snake_case__ = { '''input_ids''': [[2, 10_88_25, 11_63, 15, 8_80_10, 4_73, 1_58_98, 1_57, 1_36_72, 18_57, 3_12, 8, 23_80_21, 11_63, 53, 1_36_72, 18_57, 3_12, 8, 5_32_83, 18_23_96, 8, 1_85_66, 16, 3_67_33, 41_01, 8, 2_30, 24_40_17, 12_25_53, 7, 15, 13_25_97, 4, 2_93, 1_25_11, 76_10, 4, 34_14, 13_25_97, 9, 4, 3_23_61, 3_62, 4, 7_34, 2_85_12, 3_25_69, 18, 4, 3_23_61, 2_60_96, 1_49_82, 73, 1_87_15, 2_14_33, 23_52_61, 15, 4_92, 1_24_27, 16, 53, 1_87_15, 2_14_33, 6_54_54, 15, 2_36_59, 5_63, 16, 2_78, 5_97, 28_43, 5_95, 79_31, 18_23_96, 6_41_86, 22, 8_86, 5_95, 13_29_81, 53, 2_55_40, 34_49, 4_39_82, 3_99_01, 59_51, 8_78, 3_30, 4, 2_76_94, 8_02_69, 3_12, 53, 65_17, 1_17_80, 6_11, 2_04_08, 5], [2, 6, 13_25_97, 67, 4_28_97, 33, 5_92, 8, 16_37_29, 2_55_40, 3_61, 13_69_97, 10_95_14, 17_32_30, 7, 5_01, 60, 10_29_13, 1_96, 56_31, 2_35, 6_32_43, 4_73, 6, 23_17_57, 74, 52_77, 79_05, 53, 30_95, 3_73_17, 22, 4_54, 18_38_74, 5], [2, 2_68, 3_12_98, 4_65_30, 6, 13_29_35, 4_38_31, 7, 5_97, 32, 24, 36_88, 98_65, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='''facebook/xglm-564M''' , padding=_a , )
208
0
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase : def __init__( self , lowercase__ , lowercase__=3 , lowercase__=3_2 , lowercase__=3 , lowercase__=1_0 , lowercase__=[1_0, 2_0, 3_0, 4_0] , lowercase__=[1, 1, 2, 1] , lowercase__=True , lowercase__=True , lowercase__="relu" , lowercase__=3 , lowercase__=None , ): __UpperCAmelCase : Dict = parent __UpperCAmelCase : Optional[int] = batch_size __UpperCAmelCase : Any = image_size __UpperCAmelCase : Tuple = num_channels __UpperCAmelCase : Optional[Any] = embeddings_size __UpperCAmelCase : int = hidden_sizes __UpperCAmelCase : str = depths __UpperCAmelCase : Any = is_training __UpperCAmelCase : Optional[Any] = use_labels __UpperCAmelCase : Tuple = hidden_act __UpperCAmelCase : List[Any] = num_labels __UpperCAmelCase : Any = scope __UpperCAmelCase : List[Any] = len(lowercase__) def A( self): __UpperCAmelCase : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __UpperCAmelCase : List[Any] = None if self.use_labels: __UpperCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.num_labels) __UpperCAmelCase : Optional[Any] = self.get_config() return config, pixel_values, labels def A( self): return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def A( self , lowercase__ , lowercase__ , lowercase__): __UpperCAmelCase : Dict = TFResNetModel(config=lowercase__) __UpperCAmelCase : Dict = model(lowercase__) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def A( self , lowercase__ , lowercase__ , lowercase__): __UpperCAmelCase : Any = self.num_labels __UpperCAmelCase : Any = TFResNetForImageClassification(lowercase__) __UpperCAmelCase : List[Any] = model(lowercase__ , labels=lowercase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def A( self): __UpperCAmelCase : List[Any] = self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Tuple = config_and_inputs __UpperCAmelCase : Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): _lowerCAmelCase : Optional[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowerCAmelCase : List[Any] = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowerCAmelCase : List[str] = False _lowerCAmelCase : Any = False _lowerCAmelCase : Tuple = False _lowerCAmelCase : str = False _lowerCAmelCase : Any = False def A( self): __UpperCAmelCase : int = TFResNetModelTester(self) __UpperCAmelCase : int = ConfigTester(self , config_class=lowercase__ , has_text_modality=lowercase__) def A( self): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A( self): return @unittest.skip(reason='''ResNet does not use inputs_embeds''') def A( self): pass @unittest.skip(reason='''ResNet does not support input and output embeddings''') def A( self): pass def A( self): __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : List[str] = model_class(lowercase__) __UpperCAmelCase : Any = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase : Optional[Any] = [*signature.parameters.keys()] __UpperCAmelCase : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase__) def A( self): __UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__) def A( self): def check_hidden_states_output(lowercase__ , lowercase__ , lowercase__): __UpperCAmelCase : str = model_class(lowercase__) __UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(lowercase__ , lowercase__)) __UpperCAmelCase : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __UpperCAmelCase : Tuple = self.model_tester.num_stages self.assertEqual(len(lowercase__) , expected_num_stages + 1) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __UpperCAmelCase , __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Any = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: __UpperCAmelCase : str = layer_type __UpperCAmelCase : Any = True check_hidden_states_output(lowercase__ , lowercase__ , lowercase__) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : str = True check_hidden_states_output(lowercase__ , lowercase__ , lowercase__) def A( self): __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase__) @slow def A( self): for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Optional[int] = TFResNetModel.from_pretrained(lowercase__) self.assertIsNotNone(lowercase__) def __SCREAMING_SNAKE_CASE ( ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class lowerCamelCase ( unittest.TestCase ): @cached_property def A( self): return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def A( self): __UpperCAmelCase : Optional[int] = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) __UpperCAmelCase : Tuple = self.default_image_processor __UpperCAmelCase : Any = prepare_img() __UpperCAmelCase : Optional[Any] = image_processor(images=lowercase__ , return_tensors='''tf''') # forward pass __UpperCAmelCase : int = model(**lowercase__) # verify the logits __UpperCAmelCase : Dict = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , lowercase__) __UpperCAmelCase : List[str] = tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowercase__ , atol=1e-4))
462
import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class lowerCamelCase ( unittest.TestCase ): def A( self): __UpperCAmelCase : List[Any] = inspect.getfile(accelerate.test_utils) __UpperCAmelCase : Dict = os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ['''scripts''', '''test_script.py''']) __UpperCAmelCase : Union[str, Any] = os.path.sep.join(inspect.getfile(self.__class__).split(os.path.sep)[:-1]) @require_tpu def A( self): __UpperCAmelCase : Dict = F"\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n ".split() __UpperCAmelCase : Union[str, Any] = [sys.executable] + distributed_args execute_subprocess_async(lowercase__ , env=os.environ.copy())
462
1
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """b0""": efficientnet.EfficientNetBa, """b1""": efficientnet.EfficientNetBa, """b2""": efficientnet.EfficientNetBa, """b3""": efficientnet.EfficientNetBa, """b4""": efficientnet.EfficientNetBa, """b5""": efficientnet.EfficientNetBa, """b6""": efficientnet.EfficientNetBa, """b7""": efficientnet.EfficientNetBa, } lowerCamelCase__ = { """b0""": { """hidden_dim""": 1280, """width_coef""": 1.0, """depth_coef""": 1.0, """image_size""": 224, """dropout_rate""": 0.2, """dw_padding""": [], }, """b1""": { """hidden_dim""": 1280, """width_coef""": 1.0, """depth_coef""": 1.1, """image_size""": 240, """dropout_rate""": 0.2, """dw_padding""": [16], }, """b2""": { """hidden_dim""": 1408, """width_coef""": 1.1, """depth_coef""": 1.2, """image_size""": 260, """dropout_rate""": 0.3, """dw_padding""": [5, 8, 16], }, """b3""": { """hidden_dim""": 1536, """width_coef""": 1.2, """depth_coef""": 1.4, """image_size""": 300, """dropout_rate""": 0.3, """dw_padding""": [5, 18], }, """b4""": { """hidden_dim""": 1792, """width_coef""": 1.4, """depth_coef""": 1.8, """image_size""": 380, """dropout_rate""": 0.4, """dw_padding""": [6], }, """b5""": { """hidden_dim""": 2048, """width_coef""": 1.6, """depth_coef""": 2.2, """image_size""": 456, """dropout_rate""": 0.4, """dw_padding""": [13, 27], }, """b6""": { """hidden_dim""": 2304, """width_coef""": 1.8, """depth_coef""": 2.6, """image_size""": 528, """dropout_rate""": 0.5, """dw_padding""": [31], }, """b7""": { """hidden_dim""": 2560, """width_coef""": 2.0, """depth_coef""": 3.1, """image_size""": 600, """dropout_rate""": 0.5, """dw_padding""": [18], }, } def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> List[Any]: lowerCAmelCase__ : int = EfficientNetConfig() lowerCAmelCase__ : Union[str, Any] = CONFIG_MAP[model_name]['hidden_dim'] lowerCAmelCase__ : List[str] = CONFIG_MAP[model_name]['width_coef'] lowerCAmelCase__ : Union[str, Any] = CONFIG_MAP[model_name]['depth_coef'] lowerCAmelCase__ : Tuple = CONFIG_MAP[model_name]['image_size'] lowerCAmelCase__ : str = CONFIG_MAP[model_name]['dropout_rate'] lowerCAmelCase__ : Any = CONFIG_MAP[model_name]['dw_padding'] lowerCAmelCase__ : int = 'huggingface/label-files' lowerCAmelCase__ : List[str] = 'imagenet-1k-id2label.json' lowerCAmelCase__ : Tuple = 1_000 lowerCAmelCase__ : List[str] = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='dataset' ) , 'r' ) ) lowerCAmelCase__ : Union[str, Any] = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} lowerCAmelCase__ : Union[str, Any] = idalabel lowerCAmelCase__ : int = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase__ ( ) -> Any: lowerCAmelCase__ : Any = 'http://images.cocodataset.org/val2017/000000039769.jpg' lowerCAmelCase__ : Union[str, Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> Optional[int]: lowerCAmelCase__ : Any = CONFIG_MAP[model_name]['image_size'] lowerCAmelCase__ : List[str] = EfficientNetImageProcessor( size={'height': size, 'width': size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.47853944, 0.4732864, 0.47434163] , do_center_crop=SCREAMING_SNAKE_CASE_ , ) return preprocessor def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> List[str]: lowerCAmelCase__ : Tuple = [v.split('_' )[0].split('block' )[1] for v in original_param_names if v.startswith('block' )] lowerCAmelCase__ : int = sorted(set(SCREAMING_SNAKE_CASE_ ) ) lowerCAmelCase__ : Dict = len(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : str = {b: str(SCREAMING_SNAKE_CASE_ ) for b, i in zip(SCREAMING_SNAKE_CASE_ , range(SCREAMING_SNAKE_CASE_ ) )} lowerCAmelCase__ : int = [] rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight') ) rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight') ) rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias') ) rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean') ) rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var') ) for b in block_names: lowerCAmelCase__ : List[str] = block_name_mapping[b] rename_keys.append((F'''block{b}_expand_conv/kernel:0''', F'''encoder.blocks.{hf_b}.expansion.expand_conv.weight''') ) rename_keys.append((F'''block{b}_expand_bn/gamma:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.weight''') ) rename_keys.append((F'''block{b}_expand_bn/beta:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.bias''') ) rename_keys.append( (F'''block{b}_expand_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.running_mean''') ) rename_keys.append( (F'''block{b}_expand_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.running_var''') ) rename_keys.append( (F'''block{b}_dwconv/depthwise_kernel:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight''') ) rename_keys.append((F'''block{b}_bn/gamma:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight''') ) rename_keys.append((F'''block{b}_bn/beta:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias''') ) rename_keys.append( (F'''block{b}_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean''') ) rename_keys.append( (F'''block{b}_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var''') ) rename_keys.append((F'''block{b}_se_reduce/kernel:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.reduce.weight''') ) rename_keys.append((F'''block{b}_se_reduce/bias:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.reduce.bias''') ) rename_keys.append((F'''block{b}_se_expand/kernel:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.expand.weight''') ) rename_keys.append((F'''block{b}_se_expand/bias:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.expand.bias''') ) rename_keys.append( (F'''block{b}_project_conv/kernel:0''', F'''encoder.blocks.{hf_b}.projection.project_conv.weight''') ) rename_keys.append((F'''block{b}_project_bn/gamma:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.weight''') ) rename_keys.append((F'''block{b}_project_bn/beta:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.bias''') ) rename_keys.append( (F'''block{b}_project_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.running_mean''') ) rename_keys.append( (F'''block{b}_project_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.running_var''') ) rename_keys.append(('top_conv/kernel:0', 'encoder.top_conv.weight') ) rename_keys.append(('top_bn/gamma:0', 'encoder.top_bn.weight') ) rename_keys.append(('top_bn/beta:0', 'encoder.top_bn.bias') ) rename_keys.append(('top_bn/moving_mean:0', 'encoder.top_bn.running_mean') ) rename_keys.append(('top_bn/moving_variance:0', 'encoder.top_bn.running_var') ) lowerCAmelCase__ : Any = {} for item in rename_keys: if item[0] in original_param_names: lowerCAmelCase__ : Tuple = 'efficientnet.' + item[1] lowerCAmelCase__ : Tuple = 'classifier.weight' lowerCAmelCase__ : Union[str, Any] = 'classifier.bias' return key_mapping def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: for key, value in tf_params.items(): if "normalization" in key: continue lowerCAmelCase__ : str = key_mapping[key] if "_conv" in key and "kernel" in key: lowerCAmelCase__ : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: lowerCAmelCase__ : List[str] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: lowerCAmelCase__ : Any = torch.from_numpy(np.transpose(SCREAMING_SNAKE_CASE_ ) ) else: lowerCAmelCase__ : Optional[Any] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: lowerCAmelCase__ : List[Any] = model_classes[model_name]( include_top=SCREAMING_SNAKE_CASE_ , weights='imagenet' , input_tensor=SCREAMING_SNAKE_CASE_ , input_shape=SCREAMING_SNAKE_CASE_ , pooling=SCREAMING_SNAKE_CASE_ , classes=1_000 , classifier_activation='softmax' , ) lowerCAmelCase__ : Union[str, Any] = original_model.trainable_variables lowerCAmelCase__ : Dict = original_model.non_trainable_variables lowerCAmelCase__ : str = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: lowerCAmelCase__ : List[str] = param.numpy() lowerCAmelCase__ : Optional[Any] = list(tf_params.keys() ) # Load HuggingFace model lowerCAmelCase__ : str = get_efficientnet_config(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Dict = EfficientNetForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() lowerCAmelCase__ : Any = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('Converting parameters...' ) lowerCAmelCase__ : Optional[Any] = rename_keys(SCREAMING_SNAKE_CASE_ ) replace_params(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Initialize preprocessor and preprocess input image lowerCAmelCase__ : Any = convert_image_processor(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : int = preprocessor(images=prepare_img() , return_tensors='pt' ) # HF model inference hf_model.eval() with torch.no_grad(): lowerCAmelCase__ : List[Any] = hf_model(**SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Optional[Any] = outputs.logits.detach().numpy() # Original model inference lowerCAmelCase__ : Optional[Any] = False lowerCAmelCase__ : Union[str, Any] = CONFIG_MAP[model_name]['image_size'] lowerCAmelCase__ : Optional[int] = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) lowerCAmelCase__ : List[str] = image.img_to_array(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Tuple = np.expand_dims(SCREAMING_SNAKE_CASE_ , axis=0 ) lowerCAmelCase__ : Union[str, Any] = original_model.predict(SCREAMING_SNAKE_CASE_ ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ), "The predicted logits are not the same." print('Model outputs match!' ) if save_model: # Create folder to save model if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): os.mkdir(SCREAMING_SNAKE_CASE_ ) # Save converted model and image processor hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) preprocessor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: # Push model and image processor to hub print(F'''Pushing converted {model_name} to the hub...''' ) lowerCAmelCase__ : List[str] = F'''efficientnet-{model_name}''' preprocessor.push_to_hub(SCREAMING_SNAKE_CASE_ ) hf_model.push_to_hub(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""b0""", type=str, help="""Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""hf_model""", type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--save_model""", action="""store_true""", help="""Save model to local""") parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") lowerCamelCase__ = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
703
import numpy class A__ : def __init__( self : Tuple , a : numpy.ndarray , a : numpy.ndarray ): '''simple docstring''' lowerCAmelCase__ : int = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. lowerCAmelCase__ : Dict = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. lowerCAmelCase__ : List[str] = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. lowerCAmelCase__ : List[Any] = numpy.random.rand(3 , 1 ) # Real output values provided. lowerCAmelCase__ : str = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. lowerCAmelCase__ : List[Any] = numpy.zeros(output_array.shape ) def _lowerCamelCase ( self : List[Any] ): '''simple docstring''' lowerCAmelCase__ : str = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. lowerCAmelCase__ : Tuple = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. lowerCAmelCase__ : Any = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCAmelCase__ : List[str] = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) lowerCAmelCase__ : Optional[Any] = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) lowerCAmelCase__ : int = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def _lowerCamelCase ( self : Optional[int] , a : numpy.ndarray , a : int , a : bool ): '''simple docstring''' for iteration in range(1 , iterations + 1 ): lowerCAmelCase__ : Any = self.feedforward() self.back_propagation() if give_loss: lowerCAmelCase__ : Tuple = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f'''Iteration {iteration} Loss: {loss}''' ) def _lowerCamelCase ( self : Optional[Any] , a : numpy.ndarray ): '''simple docstring''' lowerCAmelCase__ : Dict = input_arr lowerCAmelCase__ : Any = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) lowerCAmelCase__ : int = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) lowerCAmelCase__ : List[Any] = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> numpy.ndarray: return 1 / (1 + numpy.exp(-value )) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> numpy.ndarray: return (value) * (1 - (value)) def lowerCAmelCase__ ( ) -> int: lowerCAmelCase__ : Any = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. lowerCAmelCase__ : int = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. lowerCAmelCase__ : List[str] = TwoHiddenLayerNeuralNetwork( input_array=SCREAMING_SNAKE_CASE_ , output_array=SCREAMING_SNAKE_CASE_ ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=SCREAMING_SNAKE_CASE_ , iterations=10 , give_loss=SCREAMING_SNAKE_CASE_ ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
69
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
94
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class lowerCamelCase ( lowercase__ ): '''simple docstring''' def __init__( self , *lowerCAmelCase , **lowerCAmelCase ): warnings.warn( "The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ImageGPTImageProcessor instead." , lowerCAmelCase , ) super().__init__(*lowerCAmelCase , **lowerCAmelCase )
579
0
'''simple docstring''' from math import loga def a__ ( lowerCAmelCase__ ) -> int: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError('''Input value must be a \'int\' type''' ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
701
'''simple docstring''' from timeit import timeit def a__ ( lowerCAmelCase__ ) -> int: if number < 0: raise ValueError('''the value of input must not be negative''' ) UpperCAmelCase__ : Tuple = 0 while number: number &= number - 1 result += 1 return result def a__ ( lowerCAmelCase__ ) -> int: if number < 0: raise ValueError('''the value of input must not be negative''' ) UpperCAmelCase__ : Optional[Any] = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def a__ ( ) -> None: def do_benchmark(lowerCAmelCase__ ) -> None: UpperCAmelCase__ : Optional[Any] = '''import __main__ as z''' print(F"""Benchmark when {number = }:""" ) print(F"""{get_set_bits_count_using_modulo_operator(lowerCAmelCase__ ) = }""" ) UpperCAmelCase__ : Optional[int] = timeit('''z.get_set_bits_count_using_modulo_operator(25)''' , setup=lowerCAmelCase__ ) print(F"""timeit() runs in {timing} seconds""" ) print(F"""{get_set_bits_count_using_brian_kernighans_algorithm(lowerCAmelCase__ ) = }""" ) UpperCAmelCase__ : Optional[int] = timeit( '''z.get_set_bits_count_using_brian_kernighans_algorithm(25)''' , setup=lowerCAmelCase__ , ) print(F"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(lowerCAmelCase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
312
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class a ( unittest.TestCase ): def __init__( self : int , snake_case__ : Any , snake_case__ : Dict=7 , snake_case__ : Tuple=3 , snake_case__ : Union[str, Any]=30 , snake_case__ : Any=400 , snake_case__ : Dict=True , snake_case__ : List[Any]=None , snake_case__ : Any=True , snake_case__ : Optional[int]=[0.5, 0.5, 0.5] , snake_case__ : Optional[int]=[0.5, 0.5, 0.5] , snake_case__ : Optional[int]=True , snake_case__ : int=1 / 255 , snake_case__ : str=True , ): """simple docstring""" __lowerCAmelCase = size if size is not None else {"shortest_edge": 18, "longest_edge": 1_333} __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = num_channels __lowerCAmelCase = min_resolution __lowerCAmelCase = max_resolution __lowerCAmelCase = do_resize __lowerCAmelCase = size __lowerCAmelCase = do_normalize __lowerCAmelCase = image_mean __lowerCAmelCase = image_std __lowerCAmelCase = do_rescale __lowerCAmelCase = rescale_factor __lowerCAmelCase = do_pad def UpperCAmelCase__ ( self : List[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, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self : Optional[int] , snake_case__ : Optional[Any] , snake_case__ : Tuple=False ): """simple docstring""" if not batched: __lowerCAmelCase = image_inputs[0] if isinstance(snake_case__ , Image.Image ): __lowerCAmelCase , __lowerCAmelCase = image.size else: __lowerCAmelCase , __lowerCAmelCase = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase = int(self.size["shortest_edge"] * h / w ) __lowerCAmelCase = self.size["shortest_edge"] elif w > h: __lowerCAmelCase = self.size["shortest_edge"] __lowerCAmelCase = int(self.size["shortest_edge"] * w / h ) else: __lowerCAmelCase = self.size["shortest_edge"] __lowerCAmelCase = self.size["shortest_edge"] else: __lowerCAmelCase = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase = max(snake_case__ , key=lambda snake_case__ : item[0] )[0] __lowerCAmelCase = max(snake_case__ , key=lambda snake_case__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a ( __UpperCAmelCase , unittest.TestCase ): lowercase_ : List[str] = ConditionalDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __lowerCAmelCase = ConditionalDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case__ , "image_mean" ) ) self.assertTrue(hasattr(snake_case__ , "image_std" ) ) self.assertTrue(hasattr(snake_case__ , "do_normalize" ) ) self.assertTrue(hasattr(snake_case__ , "do_resize" ) ) self.assertTrue(hasattr(snake_case__ , "size" ) ) def UpperCAmelCase__ ( self : int ): """simple docstring""" __lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1_333} ) self.assertEqual(image_processor.do_pad , snake_case__ ) __lowerCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=snake_case__ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , snake_case__ ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" pass def UpperCAmelCase__ ( self : int ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , Image.Image ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) __lowerCAmelCase = image_processing(snake_case__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , numpify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , np.ndarray ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = image_processing(snake_case__ , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : int ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , torchify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , torch.Tensor ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = image_processing(snake_case__ , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __lowerCAmelCase = json.loads(f.read() ) __lowerCAmelCase = {"image_id": 39_769, "annotations": target} # encode them __lowerCAmelCase = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) __lowerCAmelCase = image_processing(images=snake_case__ , annotations=snake_case__ , return_tensors="pt" ) # verify pixel values __lowerCAmelCase = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , snake_case__ ) __lowerCAmelCase = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1E-4 ) ) # verify area __lowerCAmelCase = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case__ ) ) # verify boxes __lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ ) __lowerCAmelCase = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1E-3 ) ) # verify image_id __lowerCAmelCase = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) ) # verify is_crowd __lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) ) # verify class_labels __lowerCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) ) # verify orig_size __lowerCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) ) # verify size __lowerCAmelCase = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) ) @slow def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __lowerCAmelCase = json.loads(f.read() ) __lowerCAmelCase = {"file_name": "000000039769.png", "image_id": 39_769, "segments_info": target} __lowerCAmelCase = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __lowerCAmelCase = ConditionalDetrImageProcessor(format="coco_panoptic" ) __lowerCAmelCase = image_processing(images=snake_case__ , annotations=snake_case__ , masks_path=snake_case__ , return_tensors="pt" ) # verify pixel values __lowerCAmelCase = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , snake_case__ ) __lowerCAmelCase = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1E-4 ) ) # verify area __lowerCAmelCase = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case__ ) ) # verify boxes __lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ ) __lowerCAmelCase = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1E-3 ) ) # verify image_id __lowerCAmelCase = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) ) # verify is_crowd __lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) ) # verify class_labels __lowerCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) ) # verify masks __lowerCAmelCase = 822_873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , snake_case__ ) # verify orig_size __lowerCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) ) # verify size __lowerCAmelCase = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) )
611
from sklearn.metrics import recall_score import datasets UpperCamelCase_ = "\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n" UpperCamelCase_ = "\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n - `0`: If there is a zero division, the return value is `0`.\n - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n Example 1-A simple example with some errors\n >>> recall_metric = datasets.load_metric('recall')\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n >>> print(results)\n {'recall': 0.6666666666666666}\n\n Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n >>> recall_metric = datasets.load_metric('recall')\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n >>> print(results)\n {'recall': 0.5}\n\n Example 3-The same example as Example 1, but with `sample_weight` included.\n >>> recall_metric = datasets.load_metric('recall')\n >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n >>> print(results)\n {'recall': 0.55}\n\n Example 4-A multiclass example, using different averages.\n >>> recall_metric = datasets.load_metric('recall')\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'recall': array([1., 0., 0.])}\n" UpperCamelCase_ = "\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a ( datasets.Metric ): def UpperCAmelCase__ ( self : Dict ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"] , ) def UpperCAmelCase__ ( self : Dict , snake_case__ : List[str] , snake_case__ : List[Any] , snake_case__ : Union[str, Any]=None , snake_case__ : int=1 , snake_case__ : List[str]="binary" , snake_case__ : Tuple=None , snake_case__ : Dict="warn" , ): """simple docstring""" __lowerCAmelCase = recall_score( snake_case__ , snake_case__ , labels=snake_case__ , pos_label=snake_case__ , average=snake_case__ , sample_weight=snake_case__ , zero_division=snake_case__ , ) return {"recall": float(snake_case__ ) if score.size == 1 else score}
611
1
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract __snake_case =logging.get_logger(__name__) def a_ ( lowerCamelCase : Optional[int] , lowerCamelCase : Optional[int] , lowerCamelCase : List[str] ): return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def a_ ( lowerCamelCase : np.ndarray , lowerCamelCase : Optional[str] , lowerCamelCase : Optional[str] = None ): lowerCAmelCase = tesseract_config if tesseract_config is not None else '' # apply OCR lowerCAmelCase = to_pil_image(lowerCamelCase ) lowerCAmelCase , lowerCAmelCase = pil_image.size lowerCAmelCase = pytesseract.image_to_data(lowerCamelCase , lang=lowerCamelCase , output_type='dict' , config=lowerCamelCase ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates lowerCAmelCase = [idx for idx, word in enumerate(lowerCamelCase ) if not word.strip()] lowerCAmelCase = [word for idx, word in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] lowerCAmelCase = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] lowerCAmelCase = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] lowerCAmelCase = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] lowerCAmelCase = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format lowerCAmelCase = [] for x, y, w, h in zip(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): lowerCAmelCase = [x, y, x + w, y + h] actual_boxes.append(lowerCamelCase ) # finally, normalize the bounding boxes lowerCAmelCase = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowerCamelCase , lowerCamelCase , lowerCamelCase ) ) assert len(lowerCamelCase ) == len(lowerCamelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : Dict = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = "" , **UpperCAmelCase__ : Any , ) -> None: super().__init__(**UpperCAmelCase__ ) lowerCAmelCase = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} lowerCAmelCase = get_size_dict(UpperCAmelCase__ ) lowerCAmelCase = do_resize lowerCAmelCase = size lowerCAmelCase = resample lowerCAmelCase = apply_ocr lowerCAmelCase = ocr_lang lowerCAmelCase = tesseract_config def __UpperCAmelCase ( self : str , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : List[str] , ) -> np.ndarray: lowerCAmelCase = get_size_dict(UpperCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(F'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) lowerCAmelCase = (size['height'], size['width']) return resize(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : Optional[int] , ) -> PIL.Image.Image: lowerCAmelCase = do_resize if do_resize is not None else self.do_resize lowerCAmelCase = size if size is not None else self.size lowerCAmelCase = get_size_dict(UpperCAmelCase__ ) lowerCAmelCase = resample if resample is not None else self.resample lowerCAmelCase = apply_ocr if apply_ocr is not None else self.apply_ocr lowerCAmelCase = ocr_lang if ocr_lang is not None else self.ocr_lang lowerCAmelCase = tesseract_config if tesseract_config is not None else self.tesseract_config lowerCAmelCase = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): 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.' ) # All transformations expect numpy arrays. lowerCAmelCase = [to_numpy_array(UpperCAmelCase__ ) for image in images] if apply_ocr: requires_backends(self , 'pytesseract' ) lowerCAmelCase = [] lowerCAmelCase = [] for image in images: lowerCAmelCase , lowerCAmelCase = apply_tesseract(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) words_batch.append(UpperCAmelCase__ ) boxes_batch.append(UpperCAmelCase__ ) if do_resize: lowerCAmelCase = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) lowerCAmelCase = [flip_channel_order(UpperCAmelCase__ ) for image in images] lowerCAmelCase = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] lowerCAmelCase = BatchFeature(data={'pixel_values': images} , tensor_type=UpperCAmelCase__ ) if apply_ocr: lowerCAmelCase = words_batch lowerCAmelCase = boxes_batch return data
513
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __snake_case ={ """configuration_chinese_clip""": [ """CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ChineseCLIPConfig""", """ChineseCLIPOnnxConfig""", """ChineseCLIPTextConfig""", """ChineseCLIPVisionConfig""", ], """processing_chinese_clip""": ["""ChineseCLIPProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case =["""ChineseCLIPFeatureExtractor"""] __snake_case =["""ChineseCLIPImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case =[ """CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """ChineseCLIPModel""", """ChineseCLIPPreTrainedModel""", """ChineseCLIPTextModel""", """ChineseCLIPVisionModel""", ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys __snake_case =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
513
1
import qiskit def UpperCAmelCase_ ( __UpperCAmelCase : int , __UpperCAmelCase : int ) -> qiskit.result.counts.Counts: SCREAMING_SNAKE_CASE_ = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register SCREAMING_SNAKE_CASE_ = qiskit.QuantumCircuit(__UpperCAmelCase , __UpperCAmelCase ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator SCREAMING_SNAKE_CASE_ = qiskit.execute(__UpperCAmelCase , __UpperCAmelCase , shots=10_00 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(__UpperCAmelCase ) if __name__ == "__main__": print(f'''Total count for various states are: {single_qubit_measure(1, 1)}''')
31
import requests from bsa import BeautifulSoup def lowerCAmelCase( __lowerCamelCase = "AAPL" ): __a = f'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}''' __a = BeautifulSoup(requests.get(__lowerCamelCase ).text , 'html.parser' ) __a = 'My(6px) Pos(r) smartphone_Mt(6px)' return soup.find('div' , class_=class_ ).find('span' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
559
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _a : Union[str, Any]= { "configuration_roberta": ["ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaConfig", "RobertaOnnxConfig"], "tokenization_roberta": ["RobertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int= ["RobertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict= [ "ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaForCausalLM", "RobertaForMaskedLM", "RobertaForMultipleChoice", "RobertaForQuestionAnswering", "RobertaForSequenceClassification", "RobertaForTokenClassification", "RobertaModel", "RobertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : str= [ "TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaForCausalLM", "TFRobertaForMaskedLM", "TFRobertaForMultipleChoice", "TFRobertaForQuestionAnswering", "TFRobertaForSequenceClassification", "TFRobertaForTokenClassification", "TFRobertaMainLayer", "TFRobertaModel", "TFRobertaPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : List[str]= [ "FlaxRobertaForCausalLM", "FlaxRobertaForMaskedLM", "FlaxRobertaForMultipleChoice", "FlaxRobertaForQuestionAnswering", "FlaxRobertaForSequenceClassification", "FlaxRobertaForTokenClassification", "FlaxRobertaModel", "FlaxRobertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys _a : int= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
192
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : list[int] , UpperCAmelCase_ : str ) -> list[int]: '''simple docstring''' __snake_case : Union[str, Any] = int(UpperCAmelCase_ ) # Initialize Result __snake_case : int = [] # Traverse through all denomination for denomination in reversed(UpperCAmelCase_ ): # Find denominations while int(UpperCAmelCase_ ) >= int(UpperCAmelCase_ ): total_value -= int(UpperCAmelCase_ ) answer.append(UpperCAmelCase_ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": _a : Optional[int]= [] _a : Optional[int]= "0" if ( input("Do you want to enter your denominations ? (yY/n): ").strip().lower() == "y" ): _a : int= int(input("Enter the number of denominations you want to add: ").strip()) for i in range(0, n): denominations.append(int(input(f'''Denomination {i}: ''').strip())) _a : Optional[int]= input("Enter the change you want to make in Indian Currency: ").strip() else: # All denominations of Indian Currency if user does not enter _a : Tuple= [1, 2, 5, 10, 20, 50, 100, 500, 2_000] _a : List[str]= input("Enter the change you want to make: ").strip() if int(value) == 0 or int(value) < 0: print("The total value cannot be zero or negative.") else: print(f'''Following is minimal change for {value}: ''') _a : List[Any]= find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=" ")
192
1
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold 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, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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 # ######################################################################## a__ : Dict = 16 a__ : int = 32 def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int = 16 ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = AutoTokenizer.from_pretrained('''bert-base-cased''' ) UpperCAmelCase = DatasetDict( { '''train''': dataset['''train'''].select(SCREAMING_SNAKE_CASE_ ), '''validation''': dataset['''train'''].select(SCREAMING_SNAKE_CASE_ ), '''test''': dataset['''validation'''], } ) def tokenize_function(SCREAMING_SNAKE_CASE_ : int ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCAmelCase = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(SCREAMING_SNAKE_CASE_ : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCAmelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCAmelCase = 16 elif accelerator.mixed_precision != "no": UpperCAmelCase = 8 else: UpperCAmelCase = None return tokenizer.pad( SCREAMING_SNAKE_CASE_ , padding='''longest''' , max_length=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) # Instantiate dataloaders. UpperCAmelCase = DataLoader( tokenized_datasets['''train'''] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = DataLoader( tokenized_datasets['''validation'''] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = DataLoader( tokenized_datasets['''test'''] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) return train_dataloader, eval_dataloader, test_dataloader def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Any: """simple docstring""" UpperCAmelCase = [] # Download the dataset UpperCAmelCase = load_dataset('''glue''' , '''mrpc''' ) # Create our splits UpperCAmelCase = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator UpperCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase = config['''lr'''] UpperCAmelCase = int(config['''num_epochs'''] ) UpperCAmelCase = int(config['''seed'''] ) UpperCAmelCase = int(config['''batch_size'''] ) UpperCAmelCase = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation UpperCAmelCase = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: UpperCAmelCase = batch_size // MAX_GPU_BATCH_SIZE UpperCAmelCase = MAX_GPU_BATCH_SIZE set_seed(SCREAMING_SNAKE_CASE_ ) # New Code # # Create our folds: UpperCAmelCase = kfold.split(np.zeros(datasets['''train'''].num_rows ) , datasets['''train''']['''label'''] ) UpperCAmelCase = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = get_fold_dataloaders( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=SCREAMING_SNAKE_CASE_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCAmelCase = model.to(accelerator.device ) # Instantiate optimizer UpperCAmelCase = AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE_ ) # Instantiate scheduler UpperCAmelCase = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE_ , num_warmup_steps=100 , num_training_steps=(len(SCREAMING_SNAKE_CASE_ ) * 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. UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Now we train the model for epoch in range(SCREAMING_SNAKE_CASE_ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = outputs.loss UpperCAmelCase = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = outputs.logits.argmax(dim=-1 ) UpperCAmelCase, UpperCAmelCase = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ , ) UpperCAmelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , SCREAMING_SNAKE_CASE_ ) # New Code # # We also run predictions on the test set at the very end UpperCAmelCase = [] for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = outputs.logits UpperCAmelCase, UpperCAmelCase = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: UpperCAmelCase = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) UpperCAmelCase = torch.stack(SCREAMING_SNAKE_CASE_ , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) UpperCAmelCase = metric.compute(predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ ) accelerator.print('''Average test metrics from all folds:''' , SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) # New Code # parser.add_argument('''--num_folds''' , type=SCREAMING_SNAKE_CASE_ , default=3 , help='''The number of splits to perform across the dataset''' ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCAmelCase_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
531
0
def __UpperCamelCase ( _UpperCAmelCase, _UpperCAmelCase ): if discount_rate < 0: raise ValueError("Discount rate cannot be negative" ) if not cash_flows: raise ValueError("Cash flows list cannot be empty" ) __UpperCAmelCase : Optional[int] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_UpperCAmelCase ) ) return round(_UpperCAmelCase, ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
707
'''simple docstring''' import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline 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 SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() def lowerCamelCase_ ( self : Any ): """simple docstring""" __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = FlaxControlNetModel.from_pretrained( "lllyasviel/sd-controlnet-canny" , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa ) __UpperCAmelCase , __UpperCAmelCase : List[Any] = FlaxStableDiffusionControlNetPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , controlnet=UpperCAmelCase_ , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa ) __UpperCAmelCase : Any = controlnet_params __UpperCAmelCase : Tuple = "bird" __UpperCAmelCase : Optional[Any] = jax.device_count() __UpperCAmelCase : Tuple = pipe.prepare_text_inputs([prompts] * num_samples ) __UpperCAmelCase : Union[str, Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ) __UpperCAmelCase : str = pipe.prepare_image_inputs([canny_image] * num_samples ) __UpperCAmelCase : List[str] = jax.random.PRNGKey(0 ) __UpperCAmelCase : Optional[int] = jax.random.split(UpperCAmelCase_ , jax.device_count() ) __UpperCAmelCase : Tuple = replicate(UpperCAmelCase_ ) __UpperCAmelCase : List[Any] = shard(UpperCAmelCase_ ) __UpperCAmelCase : List[str] = shard(UpperCAmelCase_ ) __UpperCAmelCase : Optional[int] = pipe( prompt_ids=UpperCAmelCase_ , image=UpperCAmelCase_ , params=UpperCAmelCase_ , prng_seed=UpperCAmelCase_ , num_inference_steps=50 , jit=UpperCAmelCase_ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __UpperCAmelCase : List[Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __UpperCAmelCase : List[Any] = images[0, 253:256, 253:256, -1] __UpperCAmelCase : int = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __UpperCAmelCase : int = jnp.array( [0.167969, 0.116699, 0.081543, 0.154297, 0.132812, 0.108887, 0.169922, 0.169922, 0.205078] ) print(f"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def lowerCamelCase_ ( self : Tuple ): """simple docstring""" __UpperCAmelCase , __UpperCAmelCase : Tuple = FlaxControlNetModel.from_pretrained( "lllyasviel/sd-controlnet-openpose" , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa ) __UpperCAmelCase , __UpperCAmelCase : Tuple = FlaxStableDiffusionControlNetPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , controlnet=UpperCAmelCase_ , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa ) __UpperCAmelCase : Optional[int] = controlnet_params __UpperCAmelCase : int = "Chef in the kitchen" __UpperCAmelCase : Optional[int] = jax.device_count() __UpperCAmelCase : int = pipe.prepare_text_inputs([prompts] * num_samples ) __UpperCAmelCase : Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png" ) __UpperCAmelCase : Optional[int] = pipe.prepare_image_inputs([pose_image] * num_samples ) __UpperCAmelCase : Optional[int] = jax.random.PRNGKey(0 ) __UpperCAmelCase : int = jax.random.split(UpperCAmelCase_ , jax.device_count() ) __UpperCAmelCase : Optional[Any] = replicate(UpperCAmelCase_ ) __UpperCAmelCase : Dict = shard(UpperCAmelCase_ ) __UpperCAmelCase : Any = shard(UpperCAmelCase_ ) __UpperCAmelCase : Optional[int] = pipe( prompt_ids=UpperCAmelCase_ , image=UpperCAmelCase_ , params=UpperCAmelCase_ , prng_seed=UpperCAmelCase_ , num_inference_steps=50 , jit=UpperCAmelCase_ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __UpperCAmelCase : Optional[Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __UpperCAmelCase : Tuple = images[0, 253:256, 253:256, -1] __UpperCAmelCase : Any = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __UpperCAmelCase : int = jnp.array( [[0.271484, 0.261719, 0.275391, 0.277344, 0.279297, 0.291016, 0.294922, 0.302734, 0.302734]] ) print(f"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
329
0
import argparse import struct import unittest class SCREAMING_SNAKE_CASE__ : def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : bytes ) -> None: a_ : Tuple = data # Initialize hash values a_ : int = [ 0X6a09_e667, 0Xbb67_ae85, 0X3c6e_f372, 0Xa54f_f53a, 0X510e_527f, 0X9b05_688c, 0X1f83_d9ab, 0X5be0_cd19, ] # Initialize round constants a_ : Tuple = [ 0X428a_2f98, 0X7137_4491, 0Xb5c0_fbcf, 0Xe9b5_dba5, 0X3956_c25b, 0X59f1_11f1, 0X923f_82a4, 0Xab1c_5ed5, 0Xd807_aa98, 0X1283_5b01, 0X2431_85be, 0X550c_7dc3, 0X72be_5d74, 0X80de_b1fe, 0X9bdc_06a7, 0Xc19b_f174, 0Xe49b_69c1, 0Xefbe_4786, 0X0fc1_9dc6, 0X240c_a1cc, 0X2de9_2c6f, 0X4a74_84aa, 0X5cb0_a9dc, 0X76f9_88da, 0X983e_5152, 0Xa831_c66d, 0Xb003_27c8, 0Xbf59_7fc7, 0Xc6e0_0bf3, 0Xd5a7_9147, 0X06ca_6351, 0X1429_2967, 0X27b7_0a85, 0X2e1b_2138, 0X4d2c_6dfc, 0X5338_0d13, 0X650a_7354, 0X766a_0abb, 0X81c2_c92e, 0X9272_2c85, 0Xa2bf_e8a1, 0Xa81a_664b, 0Xc24b_8b70, 0Xc76c_51a3, 0Xd192_e819, 0Xd699_0624, 0Xf40e_3585, 0X106a_a070, 0X19a4_c116, 0X1e37_6c08, 0X2748_774c, 0X34b0_bcb5, 0X391c_0cb3, 0X4ed8_aa4a, 0X5b9c_ca4f, 0X682e_6ff3, 0X748f_82ee, 0X78a5_636f, 0X84c8_7814, 0X8cc7_0208, 0X90be_fffa, 0Xa450_6ceb, 0Xbef9_a3f7, 0Xc671_78f2, ] a_ : List[Any] = self.preprocessing(self.data ) self.final_hash() @staticmethod def SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE__ : bytes ) -> bytes: a_ : List[Any] = B"\x80" + (B"\x00" * (6_3 - (len(lowerCAmelCase__ ) + 8) % 6_4)) a_ : List[Any] = struct.pack('>Q' , (len(lowerCAmelCase__ ) * 8) ) return data + padding + big_endian_integer def SCREAMING_SNAKE_CASE ( self : int ) -> None: a_ : Dict = [ self.preprocessed_data[x : x + 6_4] for x in range(0 , len(self.preprocessed_data ) , 6_4 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers a_ : Optional[int] = list(struct.unpack('>16L' , lowerCAmelCase__ ) ) # add 48 0-ed integers words += [0] * 4_8 a_ : Any = self.hashes for index in range(0 , 6_4 ): if index > 1_5: # modify the zero-ed indexes at the end of the array a_ : Any = ( self.ror(words[index - 1_5] , 7 ) ^ self.ror(words[index - 1_5] , 1_8 ) ^ (words[index - 1_5] >> 3) ) a_ : Optional[int] = ( self.ror(words[index - 2] , 1_7 ) ^ self.ror(words[index - 2] , 1_9 ) ^ (words[index - 2] >> 1_0) ) a_ : Dict = ( words[index - 1_6] + sa + words[index - 7] + sa ) % 0X1_0000_0000 # Compression a_ : Union[str, Any] = self.ror(lowerCAmelCase__ , 6 ) ^ self.ror(lowerCAmelCase__ , 1_1 ) ^ self.ror(lowerCAmelCase__ , 2_5 ) a_ : List[Any] = (e & f) ^ ((~e & 0Xffff_ffff) & g) a_ : Optional[Any] = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0000_0000 a_ : Tuple = self.ror(lowerCAmelCase__ , 2 ) ^ self.ror(lowerCAmelCase__ , 1_3 ) ^ self.ror(lowerCAmelCase__ , 2_2 ) a_ : Dict = (a & b) ^ (a & c) ^ (b & c) a_ : Optional[int] = (sa + maj) % 0X1_0000_0000 a_ : Any = ( g, f, e, ((d + tempa) % 0X1_0000_0000), c, b, a, ((tempa + tempa) % 0X1_0000_0000), ) a_ : List[str] = [a, b, c, d, e, f, g, h] # Modify final values a_ : Union[str, Any] = [ ((element + mutated_hash_values[index]) % 0X1_0000_0000) for index, element in enumerate(self.hashes ) ] a_ : List[Any] = "".join([hex(lowerCAmelCase__ )[2:].zfill(8 ) for value in self.hashes] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: return 0Xffff_ffff & (value << (3_2 - rotations)) | (value >> rotations) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : int ) -> None: import hashlib a_ : Optional[int] = bytes('Test String' , 'utf-8' ) self.assertEqual(SHAaaa(lowerCAmelCase__ ).hash , hashlib.shaaaa(lowerCAmelCase__ ).hexdigest() ) def SCREAMING_SNAKE_CASE_ ( ) -> Dict: """simple docstring""" import doctest doctest.testmod() a_ : str = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) a_ : Dict = parser.parse_args() a_ : Any = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: a_ : Dict = f.read() else: a_ : Optional[int] = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
570
import os _lowercase = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000} def UpperCamelCase ( snake_case__): lowerCAmelCase_ : List[str] = 0 lowerCAmelCase_ : Any = 0 while index < len(snake_case__) - 1: lowerCAmelCase_ : Optional[Any] = SYMBOLS[numerals[index]] lowerCAmelCase_ : int = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def UpperCamelCase ( snake_case__): lowerCAmelCase_ : Optional[int] = "" lowerCAmelCase_ : Tuple = num // 10_00 numerals += m_count * "M" num %= 10_00 lowerCAmelCase_ : int = num // 1_00 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_00 lowerCAmelCase_ : int = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def UpperCamelCase ( snake_case__ = "/p089_roman.txt"): lowerCAmelCase_ : int = 0 with open(os.path.dirname(snake_case__) + roman_numerals_filename) as filea: lowerCAmelCase_ : List[Any] = filea.readlines() for line in lines: lowerCAmelCase_ : Any = line.strip() lowerCAmelCase_ : Tuple = parse_roman_numerals(snake_case__) lowerCAmelCase_ : List[Any] = generate_roman_numerals(snake_case__) savings += len(snake_case__) - len(snake_case__) return savings if __name__ == "__main__": print(f"{solution() = }")
659
0
"""simple docstring""" import mpmath # for roots of unity import numpy as np class __lowercase : def __init__( self : List[Any] ,A : Dict=None ,A : Optional[int]=None ): '''simple docstring''' UpperCAmelCase__ : Any = list(poly_a or [0] )[:] UpperCAmelCase__ : Dict = list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() UpperCAmelCase__ : int = len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() UpperCAmelCase__ : List[str] = len(self.polyB ) # Add 0 to make lengths equal a power of 2 UpperCAmelCase__ : Tuple = int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform UpperCAmelCase__ : Optional[int] = complex(mpmath.root(x=1 ,n=self.c_max_length ,k=1 ) ) # The product UpperCAmelCase__ : str = self.__multiply() def __lowercase ( self : Optional[Any] ,A : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : Tuple = [[x] for x in self.polyA] if which == '''A''' else [[x] for x in self.polyB] # Corner case if len(A ) <= 1: return dft[0] # UpperCAmelCase__ : List[Any] = self.c_max_length // 2 while next_ncol > 0: UpperCAmelCase__ : str = [[] for i in range(A )] UpperCAmelCase__ : List[str] = self.root**next_ncol # First half of next step UpperCAmelCase__ : Union[str, Any] = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(A ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step UpperCAmelCase__ : Any = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(A ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update UpperCAmelCase__ : Tuple = new_dft UpperCAmelCase__ : List[Any] = next_ncol // 2 return dft[0] def __lowercase ( self : int ): '''simple docstring''' UpperCAmelCase__ : List[Any] = self.__dft("""A""" ) UpperCAmelCase__ : Union[str, Any] = self.__dft("""B""" ) UpperCAmelCase__ : Any = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT UpperCAmelCase__ : Tuple = 2 while next_ncol <= self.c_max_length: UpperCAmelCase__ : Tuple = [[] for i in range(A )] UpperCAmelCase__ : Tuple = self.root ** (next_ncol // 2) UpperCAmelCase__ : Optional[int] = 1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update UpperCAmelCase__ : List[Any] = new_inverse_c next_ncol *= 2 # Unpack UpperCAmelCase__ : List[str] = [round(x[0].real ,8 ) + round(x[0].imag ,8 ) * 1J for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = '''A = ''' + ''' + '''.join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A] ) ) UpperCAmelCase__ : List[str] = '''B = ''' + ''' + '''.join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B] ) ) UpperCAmelCase__ : Optional[Any] = '''A*B = ''' + ''' + '''.join( f"{coef}*x^{i}" for coef, i in enumerate(self.product ) ) return f"{a}\n{b}\n{c}" # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
708
"""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_roberta': ['ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaConfig', 'RobertaOnnxConfig'], 'tokenization_roberta': ['RobertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ['RobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaForCausalLM', 'RobertaForMaskedLM', 'RobertaForMultipleChoice', 'RobertaForQuestionAnswering', 'RobertaForSequenceClassification', 'RobertaForTokenClassification', 'RobertaModel', 'RobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaForCausalLM', 'TFRobertaForMaskedLM', 'TFRobertaForMultipleChoice', 'TFRobertaForQuestionAnswering', 'TFRobertaForSequenceClassification', 'TFRobertaForTokenClassification', 'TFRobertaMainLayer', 'TFRobertaModel', 'TFRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'FlaxRobertaForCausalLM', 'FlaxRobertaForMaskedLM', 'FlaxRobertaForMultipleChoice', 'FlaxRobertaForQuestionAnswering', 'FlaxRobertaForSequenceClassification', 'FlaxRobertaForTokenClassification', 'FlaxRobertaModel', 'FlaxRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
194
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase_ (__A , __A , unittest.TestCase ): __magic_name__ = StableDiffusionPanoramaPipeline __magic_name__ = TEXT_TO_IMAGE_PARAMS __magic_name__ = TEXT_TO_IMAGE_BATCH_PARAMS __magic_name__ = TEXT_TO_IMAGE_IMAGE_PARAMS __magic_name__ = TEXT_TO_IMAGE_IMAGE_PARAMS def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: torch.manual_seed(0 ) UpperCAmelCase_ : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) UpperCAmelCase_ : Tuple = DDIMScheduler() torch.manual_seed(0 ) UpperCAmelCase_ : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) UpperCAmelCase_ : Any = CLIPTextModel(lowerCAmelCase_ ) UpperCAmelCase_ : int = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) UpperCAmelCase_ : Union[str, Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[int]=0 ) -> List[Any]: UpperCAmelCase_ : Dict = torch.manual_seed(lowerCAmelCase_ ) UpperCAmelCase_ : Tuple = { "prompt": "a photo of the dolomites", "generator": generator, # Setting height and width to None to prevent OOMs on CPU. "height": None, "width": None, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _SCREAMING_SNAKE_CASE ( self : int ) -> int: UpperCAmelCase_ : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : str = self.get_dummy_components() UpperCAmelCase_ : int = StableDiffusionPanoramaPipeline(**lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) UpperCAmelCase_ : Optional[int] = self.get_dummy_inputs(lowerCAmelCase_ ) UpperCAmelCase_ : Optional[int] = sd_pipe(**lowerCAmelCase_ ).images UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : List[Any] = np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25e-3 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: UpperCAmelCase_ : str = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : List[Any] = self.get_dummy_components() UpperCAmelCase_ : Optional[int] = StableDiffusionPanoramaPipeline(**lowerCAmelCase_ ) UpperCAmelCase_ : str = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) UpperCAmelCase_ : Any = self.get_dummy_inputs(lowerCAmelCase_ ) UpperCAmelCase_ : Any = "french fries" UpperCAmelCase_ : Optional[Any] = sd_pipe(**lowerCAmelCase_ , negative_prompt=lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = output.images UpperCAmelCase_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : Dict = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: UpperCAmelCase_ : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : List[str] = self.get_dummy_components() UpperCAmelCase_ : Optional[int] = StableDiffusionPanoramaPipeline(**lowerCAmelCase_ ) UpperCAmelCase_ : List[str] = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) UpperCAmelCase_ : Dict = self.get_dummy_inputs(lowerCAmelCase_ ) UpperCAmelCase_ : Any = sd_pipe(**lowerCAmelCase_ , view_batch_size=2 ) UpperCAmelCase_ : int = output.images UpperCAmelCase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : str = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: UpperCAmelCase_ : str = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : Tuple = self.get_dummy_components() UpperCAmelCase_ : Dict = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" ) UpperCAmelCase_ : str = StableDiffusionPanoramaPipeline(**lowerCAmelCase_ ) UpperCAmelCase_ : Tuple = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) UpperCAmelCase_ : int = self.get_dummy_inputs(lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = sd_pipe(**lowerCAmelCase_ ).images UpperCAmelCase_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : str = np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: UpperCAmelCase_ : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : Optional[int] = self.get_dummy_components() UpperCAmelCase_ : List[Any] = PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" , skip_prk_steps=lowerCAmelCase_ ) UpperCAmelCase_ : int = StableDiffusionPanoramaPipeline(**lowerCAmelCase_ ) UpperCAmelCase_ : Any = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) UpperCAmelCase_ : List[str] = self.get_dummy_inputs(lowerCAmelCase_ ) UpperCAmelCase_ : Dict = sd_pipe(**lowerCAmelCase_ ).images UpperCAmelCase_ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : Dict = np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class UpperCamelCase_ (unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : str=0 ) -> Dict: UpperCAmelCase_ : Dict = torch.manual_seed(lowerCAmelCase_ ) UpperCAmelCase_ : Dict = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: UpperCAmelCase_ : Tuple = "stabilityai/stable-diffusion-2-base" UpperCAmelCase_ : str = DDIMScheduler.from_pretrained(lowerCAmelCase_ , subfolder="scheduler" ) UpperCAmelCase_ : Tuple = StableDiffusionPanoramaPipeline.from_pretrained(lowerCAmelCase_ , scheduler=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() UpperCAmelCase_ : List[str] = self.get_inputs() UpperCAmelCase_ : Optional[Any] = pipe(**lowerCAmelCase_ ).images UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2_048, 3) UpperCAmelCase_ : Dict = np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: UpperCAmelCase_ : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained( "stabilityai/stable-diffusion-2-base" , safety_checker=lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() UpperCAmelCase_ : List[str] = self.get_inputs() UpperCAmelCase_ : Union[str, Any] = pipe(**lowerCAmelCase_ ).images UpperCAmelCase_ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2_048, 3) UpperCAmelCase_ : Any = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: UpperCAmelCase_ : Any = 0 def callback_fn(lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : torch.FloatTensor ) -> None: UpperCAmelCase_ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: UpperCAmelCase_ : Tuple = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) UpperCAmelCase_ : str = latents[0, -3:, -3:, -1] UpperCAmelCase_ : str = np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: UpperCAmelCase_ : List[str] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) UpperCAmelCase_ : List[Any] = latents[0, -3:, -3:, -1] UpperCAmelCase_ : Union[str, Any] = np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 UpperCAmelCase_ : Tuple = False UpperCAmelCase_ : List[str] = "stabilityai/stable-diffusion-2-base" UpperCAmelCase_ : Optional[int] = DDIMScheduler.from_pretrained(lowerCAmelCase_ , subfolder="scheduler" ) UpperCAmelCase_ : Any = StableDiffusionPanoramaPipeline.from_pretrained(lowerCAmelCase_ , scheduler=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ ) UpperCAmelCase_ : Optional[int] = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() UpperCAmelCase_ : List[Any] = self.get_inputs() pipe(**lowerCAmelCase_ , callback=lowerCAmelCase_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase_ : Optional[Any] = "stabilityai/stable-diffusion-2-base" UpperCAmelCase_ : Dict = DDIMScheduler.from_pretrained(lowerCAmelCase_ , subfolder="scheduler" ) UpperCAmelCase_ : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained(lowerCAmelCase_ , scheduler=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() UpperCAmelCase_ : Optional[Any] = self.get_inputs() UpperCAmelCase_ : str = pipe(**lowerCAmelCase_ ) UpperCAmelCase_ : str = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
95
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a : Optional[int] = logging.get_logger(__name__) _a : int = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Any = "big_bird" def __init__( self , a__=50358 , a__=768 , a__=12 , a__=12 , a__=3072 , a__="gelu_new" , a__=0.1 , a__=0.1 , a__=4096 , a__=2 , a__=0.0_2 , a__=1e-12 , a__=True , a__=0 , a__=1 , a__=2 , a__=66 , a__="block_sparse" , a__=True , a__=False , a__=64 , a__=3 , a__=None , **a__ , ): super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , sep_token_id=a__ , **a__ , ) _lowerCAmelCase : List[str] = vocab_size _lowerCAmelCase : List[str] = max_position_embeddings _lowerCAmelCase : Optional[int] = hidden_size _lowerCAmelCase : Dict = num_hidden_layers _lowerCAmelCase : str = num_attention_heads _lowerCAmelCase : Any = intermediate_size _lowerCAmelCase : Any = hidden_act _lowerCAmelCase : str = hidden_dropout_prob _lowerCAmelCase : int = attention_probs_dropout_prob _lowerCAmelCase : str = initializer_range _lowerCAmelCase : Optional[int] = type_vocab_size _lowerCAmelCase : Optional[Any] = layer_norm_eps _lowerCAmelCase : Optional[int] = use_cache _lowerCAmelCase : List[Any] = rescale_embeddings _lowerCAmelCase : Any = attention_type _lowerCAmelCase : List[Any] = use_bias _lowerCAmelCase : Dict = block_size _lowerCAmelCase : Dict = num_random_blocks _lowerCAmelCase : str = classifier_dropout class __A ( SCREAMING_SNAKE_CASE_ ): @property def __A ( self ): if self.task == "multiple-choice": _lowerCAmelCase : Any = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCAmelCase : List[Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
213
0
'''simple docstring''' import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def _lowerCamelCase (__lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple=5 ) -> Optional[Any]: assert masked_input.count("<mask>" ) == 1 a__ = torch.tensor(tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ ) ).unsqueeze(0 ) # Batch size 1 a__ = model(lowercase__ )[0] # The last hidden-state is the first element of the output tuple a__ = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() a__ = logits[0, masked_index, :] a__ = logits.softmax(dim=0 ) a__ , a__ = prob.topk(k=lowercase__ , dim=0 ) a__ = " ".join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(lowercase__ ) )] ) a__ = tokenizer.mask_token a__ = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(" " ) ): a__ = predicted_token_bpe.replace("\u2581" , " " ) if " {0}".format(lowercase__ ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(" {0}".format(lowercase__ ) , lowercase__ ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(lowercase__ , lowercase__ ), values[index].item(), predicted_token, ) ) return topk_filled_outputs lowerCAmelCase_ : List[Any] = CamembertTokenizer.from_pretrained("camembert-base") lowerCAmelCase_ : List[str] = CamembertForMaskedLM.from_pretrained("camembert-base") model.eval() lowerCAmelCase_ : str = "Le camembert est <mask> :)" print(fill_mask(masked_input, model, tokenizer, topk=3))
702
'''simple docstring''' class UpperCamelCase__ : def __init__( self : str , lowerCamelCase : int , lowerCamelCase : List[str]=None , lowerCamelCase : int=None ): '''simple docstring''' a__ = data a__ = previous a__ = next_node def __str__( self : List[Any] ): '''simple docstring''' return F'''{self.data}''' def __a ( self : List[Any] ): '''simple docstring''' return self.data def __a ( self : Tuple ): '''simple docstring''' return self.next def __a ( self : Union[str, Any] ): '''simple docstring''' return self.previous class UpperCamelCase__ : def __init__( self : int , lowerCamelCase : Tuple ): '''simple docstring''' a__ = head def __iter__( self : Any ): '''simple docstring''' return self def __a ( self : List[Any] ): '''simple docstring''' if not self.current: raise StopIteration else: a__ = self.current.get_data() a__ = self.current.get_next() return value class UpperCamelCase__ : def __init__( self : Tuple ): '''simple docstring''' a__ = None # First node in list a__ = None # Last node in list def __str__( self : Any ): '''simple docstring''' a__ = self.head a__ = [] while current is not None: nodes.append(current.get_data() ) a__ = current.get_next() return " ".join(str(lowerCamelCase ) for node in nodes ) def __contains__( self : Optional[int] , lowerCamelCase : int ): '''simple docstring''' a__ = self.head while current: if current.get_data() == value: return True a__ = current.get_next() return False def __iter__( self : int ): '''simple docstring''' return LinkedListIterator(self.head ) def __a ( self : str ): '''simple docstring''' if self.head: return self.head.get_data() return None def __a ( self : Union[str, Any] ): '''simple docstring''' if self.tail: return self.tail.get_data() return None def __a ( self : List[Any] , lowerCamelCase : Node ): '''simple docstring''' if self.head is None: a__ = node a__ = node else: self.insert_before_node(self.head , lowerCamelCase ) def __a ( self : List[str] , lowerCamelCase : Node ): '''simple docstring''' if self.head is None: self.set_head(lowerCamelCase ) else: self.insert_after_node(self.tail , lowerCamelCase ) def __a ( self : List[str] , lowerCamelCase : int ): '''simple docstring''' a__ = Node(lowerCamelCase ) if self.head is None: self.set_head(lowerCamelCase ) else: self.set_tail(lowerCamelCase ) def __a ( self : Any , lowerCamelCase : Node , lowerCamelCase : Node ): '''simple docstring''' a__ = node a__ = node.previous if node.get_previous() is None: a__ = node_to_insert else: a__ = node_to_insert a__ = node_to_insert def __a ( self : Tuple , lowerCamelCase : Node , lowerCamelCase : Node ): '''simple docstring''' a__ = node a__ = node.next if node.get_next() is None: a__ = node_to_insert else: a__ = node_to_insert a__ = node_to_insert def __a ( self : Union[str, Any] , lowerCamelCase : int , lowerCamelCase : int ): '''simple docstring''' a__ = 1 a__ = Node(lowerCamelCase ) a__ = self.head while node: if current_position == position: self.insert_before_node(lowerCamelCase , lowerCamelCase ) return current_position += 1 a__ = node.next self.insert_after_node(self.tail , lowerCamelCase ) def __a ( self : List[Any] , lowerCamelCase : int ): '''simple docstring''' a__ = self.head while node: if node.get_data() == item: return node a__ = node.get_next() raise Exception("Node not found" ) def __a ( self : List[Any] , lowerCamelCase : List[str] ): '''simple docstring''' if (node := self.get_node(lowerCamelCase )) is not None: if node == self.head: a__ = self.head.get_next() if node == self.tail: a__ = self.tail.get_previous() self.remove_node_pointers(lowerCamelCase ) @staticmethod def __a ( lowerCamelCase : Node ): '''simple docstring''' if node.get_next(): a__ = node.previous if node.get_previous(): a__ = node.next a__ = None a__ = None def __a ( self : List[str] ): '''simple docstring''' return self.head is None def _lowerCamelCase () -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
289
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "google/mobilenet_v2_1.4_224": "https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json", "google/mobilenet_v2_1.0_224": "https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json", "google/mobilenet_v2_0.75_160": "https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json", "google/mobilenet_v2_0.35_96": "https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class lowerCamelCase__ ( lowerCamelCase_ ): a__ : Union[str, Any] = """mobilenet_v2""" def __init__( self , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=224 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=6 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu6" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.8 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=0.0_01 , SCREAMING_SNAKE_CASE=255 , **SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) if depth_multiplier <= 0: raise ValueError("depth_multiplier must be greater than zero." ) snake_case : List[str] = num_channels snake_case : Optional[int] = image_size snake_case : Dict = depth_multiplier snake_case : Union[str, Any] = depth_divisible_by snake_case : Any = min_depth snake_case : List[Any] = expand_ratio snake_case : Dict = output_stride snake_case : Union[str, Any] = first_layer_is_expansion snake_case : Tuple = finegrained_output snake_case : Any = hidden_act snake_case : int = tf_padding snake_case : str = classifier_dropout_prob snake_case : Any = initializer_range snake_case : Union[str, Any] = layer_norm_eps snake_case : Any = semantic_loss_ignore_index class lowerCamelCase__ ( lowerCamelCase_ ): a__ : List[str] = version.parse("""1.11""" ) @property def lowerCamelCase_ ( self ): """simple docstring""" return OrderedDict([("pixel_values", {0: "batch"})] ) @property def lowerCamelCase_ ( self ): """simple docstring""" if self.task == "image-classification": return OrderedDict([("logits", {0: "batch"})] ) else: return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] ) @property def lowerCamelCase_ ( self ): """simple docstring""" return 1E-4
134
"""simple docstring""" from itertools import count def UpperCamelCase__ ( lowercase__ : int = 50 ): snake_case : List[str] = [1] * min_block_length for n in count(lowercase__ ): fill_count_functions.append(1 ) for block_length in range(lowercase__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 100_0000: break return n if __name__ == "__main__": print(f'{solution() = }')
134
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class __lowercase ( A ): '''simple docstring''' _A : Union[List[np.ndarray], torch.FloatTensor] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
591
from __future__ import annotations def lowerCamelCase_ ( UpperCamelCase__ : list[float], UpperCamelCase__ : int ): '''simple docstring''' print(F"""Vertex\tShortest Distance from vertex {src}""" ) for i, d in enumerate(UpperCamelCase__ ): print(F"""{i}\t\t{d}""" ) def lowerCamelCase_ ( UpperCamelCase__ : list[dict[str, int]], UpperCamelCase__ : list[float], UpperCamelCase__ : int ): '''simple docstring''' for j in range(UpperCamelCase__ ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: return True return False def lowerCamelCase_ ( UpperCamelCase__ : list[dict[str, int]], UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int ): '''simple docstring''' UpperCamelCase__ = [float('''inf''' )] * vertex_count UpperCamelCase__ = 0.0 for _ in range(vertex_count - 1 ): for j in range(UpperCamelCase__ ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: UpperCamelCase__ = distance[u] + w UpperCamelCase__ = check_negative_cycle(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) if negative_cycle_exists: raise Exception('''Negative cycle found''' ) return distance if __name__ == "__main__": import doctest doctest.testmod() lowercase = int(input("""Enter number of vertices: """).strip()) lowercase = int(input("""Enter number of edges: """).strip()) lowercase = [{} for _ in range(E)] for i in range(E): print("""Edge """, i + 1) lowercase , lowercase , lowercase = ( int(x) for x in input("""Enter source, destination, weight: """).strip().split(""" """) ) lowercase = {"""src""": src, """dst""": dest, """weight""": weight} lowercase = int(input("""\nEnter shortest path source:""").strip()) lowercase = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
591
1
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class _UpperCamelCase ( a__ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str=0.01 , SCREAMING_SNAKE_CASE_ : Any=1_0_0_0 ): _a = p_stop _a = max_length def __iter__( self : List[Any] ): _a = 0 _a = False while not stop and count < self.max_length: yield count count += 1 _a = random.random() < self.p_stop class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def _UpperCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int]=False , SCREAMING_SNAKE_CASE_ : Optional[int]=True ): _a = [ BatchSamplerShard(lowerCamelCase_ , 2 , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) for i in range(2 ) ] _a = [list(lowerCamelCase_ ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(lowerCamelCase_ ) for shard in batch_sampler_shards] , [len(lowerCamelCase_ ) for e in expected] ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) def _UpperCAmelCase ( self : List[Any] ): # Check the shards when the dataset is a round multiple of total batch size. _a = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 2_2, 2_3]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) _a = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=lowerCamelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _a = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [0, 1, 2]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) _a = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _a = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 0, 1]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) _a = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _a = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [1, 2, 3]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) _a = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) # Check the shards when the dataset is very small. _a = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) _a = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [[], []] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ ) def _UpperCAmelCase ( self : Union[str, Any] ): # Check the shards when the dataset is a round multiple of batch size. _a = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [2_2, 2_3]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=lowerCamelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size. _a = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [0, 1]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _a = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 0]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [1, 2]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) # Check the shards when the dataset is very small. _a = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) _a = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [[], []] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ ) def _UpperCAmelCase ( self : List[str] ): # Check the shards when the dataset is a round multiple of total batch size. _a = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 2_2, 2_3]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=lowerCamelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _a = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _a = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _a = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) # Check the shards when the dataset is very small. _a = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [[[0, 1]], []] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCamelCase_ ) _a = [[], []] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , even_batches=lowerCamelCase_ ) def _UpperCAmelCase ( self : Union[str, Any] ): # Check the shards when the dataset is a round multiple of batch size. _a = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [2_2, 2_3]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=lowerCamelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size. _a = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _a = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) # Check the shards when the dataset is very small. _a = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [[[0, 1]], []] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) _a = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = [[], []] self.check_batch_sampler_shards(lowerCamelCase_ , lowerCamelCase_ , split_batches=lowerCamelCase_ , even_batches=lowerCamelCase_ ) def _UpperCAmelCase ( self : Any ): _a = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 1_0, 1_1], [1_2, 1_3]] _a = [BatchSamplerShard(lowerCamelCase_ , 2 , lowerCamelCase_ , even_batches=lowerCamelCase_ ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [1_2, 1_3]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 1_0, 1_1]] ) def _UpperCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any=False , SCREAMING_SNAKE_CASE_ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE_ : Tuple=False ): random.seed(lowerCamelCase_ ) _a = list(lowerCamelCase_ ) _a = [ IterableDatasetShard( lowerCamelCase_ , batch_size=lowerCamelCase_ , drop_last=lowerCamelCase_ , num_processes=lowerCamelCase_ , process_index=lowerCamelCase_ , split_batches=lowerCamelCase_ , ) for i in range(lowerCamelCase_ ) ] _a = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(lowerCamelCase_ ) iterable_dataset_lists.append(list(lowerCamelCase_ ) ) _a = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size _a = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) self.assertTrue(len(lowerCamelCase_ ) % shard_batch_size == 0 ) _a = [] for idx in range(0 , len(lowerCamelCase_ ) , lowerCamelCase_ ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(lowerCamelCase_ ) < len(lowerCamelCase_ ): reference += reference self.assertListEqual(lowerCamelCase_ , reference[: len(lowerCamelCase_ )] ) def _UpperCAmelCase ( self : str ): _a = 4_2 _a = RandomIterableDataset() self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) # Edge case with a very small dataset _a = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) self.check_iterable_dataset_shards(lowerCamelCase_ , lowerCamelCase_ , batch_size=4 , drop_last=lowerCamelCase_ , split_batches=lowerCamelCase_ ) def _UpperCAmelCase ( self : int ): _a = BatchSampler(range(1_6 ) , batch_size=4 , drop_last=lowerCamelCase_ ) _a = SkipBatchSampler(lowerCamelCase_ , 2 ) self.assertListEqual(list(lowerCamelCase_ ) , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def _UpperCAmelCase ( self : Union[str, Any] ): _a = SkipDataLoader(list(range(1_6 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def _UpperCAmelCase ( self : Dict ): _a = DataLoader(list(range(1_6 ) ) , batch_size=4 ) _a = skip_first_batches(lowerCamelCase_ , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def _UpperCAmelCase ( self : Optional[int] ): _a = DataLoaderShard(list(range(1_6 ) ) , batch_size=4 ) for idx, _ in enumerate(lowerCamelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(lowerCamelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def _UpperCAmelCase ( self : int ): Accelerator() _a = DataLoaderDispatcher(range(1_6 ) , batch_size=4 ) for idx, _ in enumerate(lowerCamelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(lowerCamelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
562
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a__ ( a__ , a__ , a__ , unittest.TestCase ): '''simple docstring''' lowercase__ : Optional[Any] = AltDiffusionPipeline lowercase__ : Dict = TEXT_TO_IMAGE_PARAMS lowercase__ : str = TEXT_TO_IMAGE_BATCH_PARAMS lowercase__ : Any = TEXT_TO_IMAGE_IMAGE_PARAMS lowercase__ : List[str] = TEXT_TO_IMAGE_IMAGE_PARAMS def __SCREAMING_SNAKE_CASE ( self ) -> str: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=lowerCamelCase_ , set_alpha_to_one=lowerCamelCase_ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=50_02 , ) lowerCAmelCase__ = CLIPTextModel(lowerCamelCase_ ) lowerCAmelCase__ = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) lowerCAmelCase__ = 77 lowerCAmelCase__ = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_=0 ) -> List[str]: if str(lowerCamelCase_ ).startswith('''mps''' ): lowerCAmelCase__ = torch.manual_seed(lowerCamelCase_ ) else: lowerCAmelCase__ = torch.Generator(device=lowerCamelCase_ ).manual_seed(lowerCamelCase_ ) lowerCAmelCase__ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __SCREAMING_SNAKE_CASE ( self ) -> List[str]: lowerCAmelCase__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() torch.manual_seed(0 ) lowerCAmelCase__ = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=50_02 , ) # TODO: remove after fixing the non-deterministic text encoder lowerCAmelCase__ = RobertaSeriesModelWithTransformation(lowerCamelCase_ ) lowerCAmelCase__ = text_encoder lowerCAmelCase__ = AltDiffusionPipeline(**lowerCamelCase_ ) lowerCAmelCase__ = alt_pipe.to(lowerCamelCase_ ) alt_pipe.set_progress_bar_config(disable=lowerCamelCase_ ) lowerCAmelCase__ = self.get_dummy_inputs(lowerCamelCase_ ) lowerCAmelCase__ = '''A photo of an astronaut''' lowerCAmelCase__ = alt_pipe(**lowerCamelCase_ ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase__ = np.array( [0.5_748_162, 0.60_447_145, 0.48_821_217, 0.50_100_636, 0.5_431_185, 0.45_763_683, 0.49_657_696, 0.48_132_733, 0.47_573_093] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: lowerCAmelCase__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = PNDMScheduler(skip_prk_steps=lowerCamelCase_ ) torch.manual_seed(0 ) lowerCAmelCase__ = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=50_02 , ) # TODO: remove after fixing the non-deterministic text encoder lowerCAmelCase__ = RobertaSeriesModelWithTransformation(lowerCamelCase_ ) lowerCAmelCase__ = text_encoder lowerCAmelCase__ = AltDiffusionPipeline(**lowerCamelCase_ ) lowerCAmelCase__ = alt_pipe.to(lowerCamelCase_ ) alt_pipe.set_progress_bar_config(disable=lowerCamelCase_ ) lowerCAmelCase__ = self.get_dummy_inputs(lowerCamelCase_ ) lowerCAmelCase__ = alt_pipe(**lowerCamelCase_ ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase__ = np.array( [0.51_605_093, 0.5_707_241, 0.47_365_507, 0.50_578_886, 0.5_633_877, 0.4_642_503, 0.5_182_081, 0.48_763_484, 0.49_084_237] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class a__ ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: # make sure here that pndm scheduler skips prk lowerCAmelCase__ = AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion''' , safety_checker=lowerCamelCase_ ) lowerCAmelCase__ = alt_pipe.to(lowerCamelCase_ ) alt_pipe.set_progress_bar_config(disable=lowerCamelCase_ ) lowerCAmelCase__ = '''A painting of a squirrel eating a burger''' lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = alt_pipe([prompt] , generator=lowerCamelCase_ , guidance_scale=6.0 , num_inference_steps=20 , output_type='''np''' ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowerCAmelCase__ = np.array([0.1_010, 0.0_800, 0.0_794, 0.0_885, 0.0_843, 0.0_762, 0.0_769, 0.0_729, 0.0_586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __SCREAMING_SNAKE_CASE ( self ) -> Any: lowerCAmelCase__ = DDIMScheduler.from_pretrained('''BAAI/AltDiffusion''' , subfolder='''scheduler''' ) lowerCAmelCase__ = AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion''' , scheduler=lowerCamelCase_ , safety_checker=lowerCamelCase_ ) lowerCAmelCase__ = alt_pipe.to(lowerCamelCase_ ) alt_pipe.set_progress_bar_config(disable=lowerCamelCase_ ) lowerCAmelCase__ = '''A painting of a squirrel eating a burger''' lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = alt_pipe([prompt] , generator=lowerCamelCase_ , num_inference_steps=2 , output_type='''numpy''' ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowerCAmelCase__ = np.array([0.4_019, 0.4_052, 0.3_810, 0.4_119, 0.3_916, 0.3_982, 0.4_651, 0.4_195, 0.5_323] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
90
0
from __future__ import annotations from collections.abc import Iterator class _a : """simple docstring""" def __init__( self : List[Any] , a : int ) ->None: SCREAMING_SNAKE_CASE__ : Optional[int] = value SCREAMING_SNAKE_CASE__ : Node | None = None SCREAMING_SNAKE_CASE__ : Node | None = None class _a : """simple docstring""" def __init__( self : Tuple , a : Node ) ->None: SCREAMING_SNAKE_CASE__ : int = tree def A_ ( self : str , a : Node | None ) ->int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : Optional[Any] ) ->Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
714
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def UpperCAmelCase ( _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : PreTrainedTokenizer , _lowerCamelCase : int , _lowerCamelCase : Optional[int] = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = {} if train_file is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = [train_file] if eval_file is not None: SCREAMING_SNAKE_CASE__ : int = [eval_file] if test_file is not None: SCREAMING_SNAKE_CASE__ : int = [test_file] SCREAMING_SNAKE_CASE__ : Optional[int] = datasets.load_dataset("csv" , data_files=_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = list(ds[list(files.keys() )[0]].features.keys() ) SCREAMING_SNAKE_CASE__ : int = features_name.pop(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = list(set(ds[list(files.keys() )[0]][label_name] ) ) SCREAMING_SNAKE_CASE__ : List[str] = {label: i for i, label in enumerate(_lowerCamelCase )} SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.model_input_names SCREAMING_SNAKE_CASE__ : Any = {} if len(_lowerCamelCase ) == 1: for k in files.keys(): SCREAMING_SNAKE_CASE__ : List[Any] = ds[k].map( lambda _lowerCamelCase : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=_lowerCamelCase , max_length=_lowerCamelCase , padding="max_length" ) , batched=_lowerCamelCase , ) elif len(_lowerCamelCase ) == 2: for k in files.keys(): SCREAMING_SNAKE_CASE__ : Any = ds[k].map( lambda _lowerCamelCase : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=_lowerCamelCase , max_length=_lowerCamelCase , padding="max_length" , ) , batched=_lowerCamelCase , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: SCREAMING_SNAKE_CASE__ : Tuple = {k: v for k, v in ex.items() if k in input_names} SCREAMING_SNAKE_CASE__ : List[Any] = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: SCREAMING_SNAKE_CASE__ : int = {k: v for k, v in ex.items() if k in input_names} SCREAMING_SNAKE_CASE__ : Optional[int] = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: SCREAMING_SNAKE_CASE__ : int = {k: v for k, v in ex.items() if k in input_names} SCREAMING_SNAKE_CASE__ : Optional[Any] = labelaid[ex[label_name]] yield (d, label) SCREAMING_SNAKE_CASE__ : Tuple = ( tf.data.Dataset.from_generator( _lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: SCREAMING_SNAKE_CASE__ : Any = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ( tf.data.Dataset.from_generator( _lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) SCREAMING_SNAKE_CASE__ : Dict = ( tf.data.Dataset.from_generator( _lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: SCREAMING_SNAKE_CASE__ : Dict = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid __lowercase :List[Any] = logging.getLogger(__name__) @dataclass class _a : """simple docstring""" snake_case_ = field(metadata={"help": "Which column contains the label"} ) snake_case_ = field(default=lowercase__ , metadata={"help": "The path of the training file"} ) snake_case_ = field(default=lowercase__ , metadata={"help": "The path of the development file"} ) snake_case_ = field(default=lowercase__ , metadata={"help": "The path of the test file"} ) snake_case_ = field( default=1_28 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case_ = field( default=lowercase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) @dataclass class _a : """simple docstring""" snake_case_ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case_ = field( default=lowercase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case_ = field( default=lowercase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case_ = field(default=lowercase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case_ = field( default=lowercase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) def UpperCAmelCase ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" " --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.info( f"""n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, """ f"""16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Any = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=_lowerCamelCase , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) SCREAMING_SNAKE_CASE__ : str = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(_lowerCamelCase ) , labelaid=_lowerCamelCase , idalabel={id: label for label, id in labelaid.items()} , finetuning_task="text-classification" , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): SCREAMING_SNAKE_CASE__ : Optional[Any] = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool(".bin" in model_args.model_name_or_path ) , config=_lowerCamelCase , cache_dir=model_args.cache_dir , ) def compute_metrics(_lowerCamelCase : EvalPrediction ) -> Dict: SCREAMING_SNAKE_CASE__ : Dict = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer SCREAMING_SNAKE_CASE__ : str = TFTrainer( model=_lowerCamelCase , args=_lowerCamelCase , train_dataset=_lowerCamelCase , eval_dataset=_lowerCamelCase , compute_metrics=_lowerCamelCase , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE__ : Dict = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) SCREAMING_SNAKE_CASE__ : str = trainer.evaluate() SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(training_args.output_dir , "eval_results.txt" ) with open(_lowerCamelCase , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(f""" {key} = {value}""" ) writer.write(f"""{key} = {value}\n""" ) results.update(_lowerCamelCase ) return results if __name__ == "__main__": main()
26
0
"""simple docstring""" import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __UpperCAmelCase ="""__DUMMY_TRANSFORMERS_USER__""" __UpperCAmelCase ="""Dummy User""" __UpperCAmelCase ="""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""" __UpperCAmelCase ="""https://hub-ci.huggingface.co""" __UpperCAmelCase =CI_HUB_ENDPOINT + """/datasets/{repo_id}/resolve/{revision}/{path}""" __UpperCAmelCase =CI_HUB_ENDPOINT + """/{repo_id}/resolve/{revision}/{filename}""" __UpperCAmelCase =Path("""~/.huggingface/hub_ci_token""").expanduser() @pytest.fixture def __a ( A ) -> Any: '''simple docstring''' monkeypatch.setattr( "huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE" , A ) @pytest.fixture def __a ( A ) -> List[Any]: '''simple docstring''' monkeypatch.setattr("datasets.config.HF_ENDPOINT" , A ) monkeypatch.setattr("datasets.config.HUB_DATASETS_URL" , A ) @pytest.fixture def __a ( A ) -> Any: '''simple docstring''' monkeypatch.setattr("huggingface_hub.hf_api.HfFolder.path_token" , A ) @pytest.fixture def __a ( A , A ) -> List[str]: '''simple docstring''' HfFolder.save_token(A ) yield HfFolder.delete_token() @pytest.fixture(scope="session" ) def __a ( ) -> Dict: '''simple docstring''' return HfApi(endpoint=A ) @pytest.fixture(scope="session" ) def __a ( A ) -> int: '''simple docstring''' A__ = HfFolder.get_token() HfFolder.save_token(A ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(A ) @pytest.fixture def __a ( A ) -> int: '''simple docstring''' def _cleanup_repo(A ): hf_api.delete_repo(A , token=A , repo_type="dataset" ) return _cleanup_repo @pytest.fixture def __a ( A ) -> Optional[Any]: '''simple docstring''' @contextmanager def _temporary_repo(A ): try: yield repo_id finally: cleanup_repo(A ) return _temporary_repo @pytest.fixture(scope="session" ) def __a ( A , A , A ) -> Any: '''simple docstring''' A__ = f"""repo_txt_data-{int(time.time() * 1_0E3 )}""" A__ = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(A , token=A , repo_type="dataset" , private=A ) hf_api.upload_file( token=A , path_or_fileobj=str(A ) , path_in_repo="data/text_data.txt" , repo_id=A , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(A , token=A , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __a ( A , A , A ) -> Dict: '''simple docstring''' return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope="session" ) def __a ( A , A , A ) -> Dict: '''simple docstring''' A__ = f"""repo_zipped_txt_data-{int(time.time() * 1_0E3 )}""" A__ = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(A , token=A , repo_type="dataset" , private=A ) hf_api.upload_file( token=A , path_or_fileobj=str(A ) , path_in_repo="data.zip" , repo_id=A , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(A , token=A , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __a ( A , A , A ) -> List[str]: '''simple docstring''' return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope="session" ) def __a ( A , A , A ) -> str: '''simple docstring''' A__ = f"""repo_zipped_img_data-{int(time.time() * 1_0E3 )}""" A__ = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(A , token=A , repo_type="dataset" , private=A ) hf_api.upload_file( token=A , path_or_fileobj=str(A ) , path_in_repo="data.zip" , repo_id=A , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(A , token=A , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __a ( A , A , A ) -> Any: '''simple docstring''' return hf_private_dataset_repo_zipped_img_data_
337
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device __UpperCAmelCase =False class lowerCAmelCase__ ( unittest.TestCase ): pass @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def lowercase_ ( self ): '''simple docstring''' A__ = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) A__ = torch.manual_seed(0 ) A__ = pipe( image=UpperCamelCase__ , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" , ).images A__ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) A__ = np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
337
1
from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=_lowercase ): A__ = ['torch', 'torchsde'] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ): requires_backends(self , ['''torch''', '''torchsde'''] ) @classmethod def __magic_name__( cls , *__UpperCAmelCase , **__UpperCAmelCase ): requires_backends(cls , ['''torch''', '''torchsde'''] ) @classmethod def __magic_name__( cls , *__UpperCAmelCase , **__UpperCAmelCase ): requires_backends(cls , ['''torch''', '''torchsde'''] )
470
def __lowerCAmelCase ( UpperCamelCase ) -> bool: if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(UpperCamelCase ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(UpperCamelCase ) == 1: return True lowerCAmelCase__ : Tuple = series[1] - series[0] for index in range(len(UpperCamelCase ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def __lowerCAmelCase ( UpperCamelCase ) -> float: if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(UpperCamelCase ) == 0: raise ValueError('''Input list must be a non empty list''' ) lowerCAmelCase__ : int = 0 for val in series: answer += val return answer / len(UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
470
1
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ = 1000 ) -> int: '''simple docstring''' return sum(e for e in range(3 , SCREAMING_SNAKE_CASE__ ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f"{solution() = }")
638
'''simple docstring''' from __future__ import annotations from PIL import Image # Define glider example lowercase__ = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example lowercase__ = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> list[list[int]]: '''simple docstring''' snake_case : Optional[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): snake_case : str = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours snake_case : Any = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(SCREAMING_SNAKE_CASE__ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(SCREAMING_SNAKE_CASE__ ) - 1: neighbour_count += cells[i + 1][j] if i < len(SCREAMING_SNAKE_CASE__ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. snake_case : List[Any] = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(SCREAMING_SNAKE_CASE__ ) return next_generation def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> list[Image.Image]: '''simple docstring''' snake_case : Tuple = [] for _ in range(SCREAMING_SNAKE_CASE__ ): # Create output image snake_case : List[Any] = Image.new('''RGB''' , (len(cells[0] ), len(SCREAMING_SNAKE_CASE__ )) ) snake_case : Optional[Any] = img.load() # Save cells to image for x in range(len(SCREAMING_SNAKE_CASE__ ) ): for y in range(len(cells[0] ) ): snake_case : str = 255 - cells[y][x] * 255 snake_case : List[str] = (colour, colour, colour) # Save image images.append(SCREAMING_SNAKE_CASE__ ) snake_case : Dict = new_generation(SCREAMING_SNAKE_CASE__ ) return images if __name__ == "__main__": lowercase__ = generate_images(GLIDER, 1_6) images[0].save("out.gif", save_all=True, append_images=images[1:])
638
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Union[str, Any] = { '''configuration_convbert''': ['''CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConvBertConfig''', '''ConvBertOnnxConfig'''], '''tokenization_convbert''': ['''ConvBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = ['''ConvBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : str = [ '''CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConvBertForMaskedLM''', '''ConvBertForMultipleChoice''', '''ConvBertForQuestionAnswering''', '''ConvBertForSequenceClassification''', '''ConvBertForTokenClassification''', '''ConvBertLayer''', '''ConvBertModel''', '''ConvBertPreTrainedModel''', '''load_tf_weights_in_convbert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ '''TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFConvBertForMaskedLM''', '''TFConvBertForMultipleChoice''', '''TFConvBertForQuestionAnswering''', '''TFConvBertForSequenceClassification''', '''TFConvBertForTokenClassification''', '''TFConvBertLayer''', '''TFConvBertModel''', '''TFConvBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
516
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def A__ ( __A : str = "isbn/0140328726" ) ->dict: __A =olid.strip().strip('''/''' ) # Remove leading/trailing whitespace & slashes if new_olid.count('''/''' ) != 1: __A =F'''{olid} is not a valid Open Library olid''' raise ValueError(__A ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def A__ ( __A : dict ) ->dict: __A ={ '''title''': '''Title''', '''publish_date''': '''Publish date''', '''authors''': '''Authors''', '''number_of_pages''': '''Number of pages:''', '''first_sentence''': '''First sentence''', '''isbn_10''': '''ISBN (10)''', '''isbn_13''': '''ISBN (13)''', } __A ={better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __A =[ get_openlibrary_data(author['''key'''] )['''name'''] for author in data['''Authors'''] ] __A =data['''First sentence''']['''value'''] for key, value in data.items(): if isinstance(__A , __A ): __A =''', '''.join(__A ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowerCamelCase : Union[str, Any] = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"""Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.""") continue print(F"""\nSearching Open Library for ISBN: {isbn}...\n""") try: _lowerCamelCase : Tuple = summarize_book(get_openlibrary_data(F"""isbn/{isbn}""")) print('''\n'''.join(F"""{key}: {value}""" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"""Sorry, there are no results for ISBN: {isbn}.""")
516
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __A ( UpperCamelCase__ , unittest.TestCase ): UpperCamelCase = ShapEPipeline UpperCamelCase = ["""prompt"""] UpperCamelCase = ["""prompt"""] UpperCamelCase = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] UpperCamelCase = False @property def A__ ( self :Dict ): '''simple docstring''' return 32 @property def A__ ( self :Optional[Any] ): '''simple docstring''' return 32 @property def A__ ( self :Any ): '''simple docstring''' return self.time_input_dim * 4 @property def A__ ( self :Optional[int] ): '''simple docstring''' return 8 @property def A__ ( self :Any ): '''simple docstring''' __magic_name__ : Any =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def A__ ( self :List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __magic_name__ : Any =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModelWithProjection(__snake_case ) @property def A__ ( self :List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __magic_name__ : Union[str, Any] ={ """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } __magic_name__ : Optional[Any] =PriorTransformer(**__snake_case ) return model @property def A__ ( self :int ): '''simple docstring''' torch.manual_seed(0 ) __magic_name__ : Optional[int] ={ """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } __magic_name__ : Any =ShapERenderer(**__snake_case ) return model def A__ ( self :Dict ): '''simple docstring''' __magic_name__ : List[str] =self.dummy_prior __magic_name__ : str =self.dummy_text_encoder __magic_name__ : Dict =self.dummy_tokenizer __magic_name__ : Union[str, Any] =self.dummy_renderer __magic_name__ : List[str] =HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=10_24 , prediction_type="""sample""" , use_karras_sigmas=__snake_case , clip_sample=__snake_case , clip_sample_range=1.0 , ) __magic_name__ : Union[str, Any] ={ """prior""": prior, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """renderer""": renderer, """scheduler""": scheduler, } return components def A__ ( self :Any , __snake_case :Optional[Any] , __snake_case :Optional[int]=0 ): '''simple docstring''' if str(__snake_case ).startswith("""mps""" ): __magic_name__ : Union[str, Any] =torch.manual_seed(__snake_case ) else: __magic_name__ : List[Any] =torch.Generator(device=__snake_case ).manual_seed(__snake_case ) __magic_name__ : str ={ """prompt""": """horse""", """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def A__ ( self :List[Any] ): '''simple docstring''' __magic_name__ : str ="""cpu""" __magic_name__ : str =self.get_dummy_components() __magic_name__ : Optional[int] =self.pipeline_class(**__snake_case ) __magic_name__ : Dict =pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__ : str =pipe(**self.get_dummy_inputs(__snake_case ) ) __magic_name__ : Dict =output.images[0] __magic_name__ : str =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __magic_name__ : Union[str, Any] =np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A__ ( self :Optional[int] ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A__ ( self :List[str] ): '''simple docstring''' __magic_name__ : Optional[int] =torch_device == """cpu""" __magic_name__ : Optional[int] =True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__snake_case , relax_max_difference=__snake_case , ) def A__ ( self :List[str] ): '''simple docstring''' __magic_name__ : int =self.get_dummy_components() __magic_name__ : List[Any] =self.pipeline_class(**__snake_case ) __magic_name__ : int =pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__ : List[Any] =1 __magic_name__ : Optional[int] =2 __magic_name__ : Any =self.get_dummy_inputs(__snake_case ) for key in inputs.keys(): if key in self.batch_params: __magic_name__ : List[str] =batch_size * [inputs[key]] __magic_name__ : List[str] =pipe(**__snake_case , num_images_per_prompt=__snake_case )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __A ( unittest.TestCase ): def A__ ( self :str ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self :Optional[Any] ): '''simple docstring''' __magic_name__ : Any =load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_np_out.npy""" ) __magic_name__ : List[Any] =ShapEPipeline.from_pretrained("""openai/shap-e""" ) __magic_name__ : str =pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__ : int =torch.Generator(device=__snake_case ).manual_seed(0 ) __magic_name__ : List[Any] =pipe( """a shark""" , generator=__snake_case , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__snake_case , __snake_case )
21
import math import tensorflow as tf from packaging import version def lowerCAmelCase_ ( lowerCamelCase ): __magic_name__ : str =tf.convert_to_tensor(lowerCamelCase ) __magic_name__ : List[str] =0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def lowerCAmelCase_ ( lowerCamelCase ): __magic_name__ : str =tf.convert_to_tensor(lowerCamelCase ) __magic_name__ : Optional[Any] =tf.cast(math.pi , x.dtype ) __magic_name__ : int =tf.cast(0.0_4_4_7_1_5 , x.dtype ) __magic_name__ : Tuple =0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(lowerCamelCase , 3 )) )) return x * cdf def lowerCAmelCase_ ( lowerCamelCase ): __magic_name__ : Any =tf.convert_to_tensor(lowerCamelCase ) return x * tf.tanh(tf.math.softplus(lowerCamelCase ) ) def lowerCAmelCase_ ( lowerCamelCase ): __magic_name__ : Optional[Any] =tf.convert_to_tensor(lowerCamelCase ) __magic_name__ : Union[str, Any] =tf.cast(0.0_4_4_7_1_5 , x.dtype ) __magic_name__ : Tuple =tf.cast(0.7_9_7_8_8_4_5_6_0_8 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def lowerCAmelCase_ ( lowerCamelCase ): __magic_name__ : List[str] =tf.convert_to_tensor(lowerCamelCase ) __magic_name__ : Dict =tf.cast(1.7_0_2 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def lowerCAmelCase_ ( lowerCamelCase ): return tf.clip_by_value(_gelu(lowerCamelCase ) , -10 , 10 ) def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase=-1 ): __magic_name__ , __magic_name__ : List[Any] =tf.split(lowerCamelCase , 2 , axis=lowerCamelCase ) return a * tf.math.sigmoid(lowerCamelCase ) if version.parse(tf.version.VERSION) >= version.parse("2.4"): def lowerCAmelCase_ ( lowerCamelCase ): return tf.keras.activations.gelu(lowerCamelCase , approximate=lowerCamelCase ) UpperCAmelCase_ : List[str] = tf.keras.activations.gelu UpperCAmelCase_ : Dict = approximate_gelu_wrap else: UpperCAmelCase_ : Dict = _gelu UpperCAmelCase_ : str = _gelu_new UpperCAmelCase_ : Any = { "gelu": gelu, "gelu_10": gelu_aa, "gelu_fast": gelu_fast, "gelu_new": gelu_new, "glu": glu, "mish": mish, "quick_gelu": quick_gelu, "relu": tf.keras.activations.relu, "sigmoid": tf.keras.activations.sigmoid, "silu": tf.keras.activations.swish, "swish": tf.keras.activations.swish, "tanh": tf.keras.activations.tanh, } def lowerCAmelCase_ ( lowerCamelCase ): if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(F"function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}" )
21
1
import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" snake_case_ = 1 snake_case_ = 3 snake_case_ = (32, 32) snake_case_ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_UpperCAmelCase ) return image @property def lowerCAmelCase ( self : Dict ) ->Dict: """simple docstring""" torch.manual_seed(0 ) snake_case_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) return model @property def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" torch.manual_seed(0 ) snake_case_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" torch.manual_seed(0 ) snake_case_ = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_006 , ) return RobertaSeriesModelWithTransformation(_UpperCAmelCase ) @property def lowerCAmelCase ( self : str ) ->str: """simple docstring""" def extract(*UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[Any] ): class __A : '''simple docstring''' def __init__( self : Optional[Any] ) ->str: """simple docstring""" snake_case_ = torch.ones([0] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Optional[int] ) ->List[Any]: """simple docstring""" self.pixel_values.to(_UpperCAmelCase ) return self return Out() return extract def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" # ensure determinism for the device-dependent torch.Generator snake_case_ = self.dummy_cond_unet snake_case_ = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) snake_case_ = self.dummy_vae snake_case_ = self.dummy_text_encoder snake_case_ = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""" ) snake_case_ = 77 snake_case_ = self.dummy_image.to(_UpperCAmelCase ) snake_case_ = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk snake_case_ = AltDiffusionImgaImgPipeline( unet=_UpperCAmelCase , scheduler=_UpperCAmelCase , vae=_UpperCAmelCase , text_encoder=_UpperCAmelCase , tokenizer=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=self.dummy_extractor , ) snake_case_ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=_UpperCAmelCase ) snake_case_ = alt_pipe.to(_UpperCAmelCase ) alt_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) snake_case_ = """A painting of a squirrel eating a burger""" snake_case_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) snake_case_ = alt_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , image=_UpperCAmelCase , ) snake_case_ = output.images snake_case_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) snake_case_ = alt_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , image=_UpperCAmelCase , return_dict=_UpperCAmelCase , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case_ = np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5E-3 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = self.dummy_cond_unet snake_case_ = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) snake_case_ = self.dummy_vae snake_case_ = self.dummy_text_encoder snake_case_ = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""" ) snake_case_ = 77 snake_case_ = self.dummy_image.to(_UpperCAmelCase ) # put models in fp16 snake_case_ = unet.half() snake_case_ = vae.half() snake_case_ = bert.half() # make sure here that pndm scheduler skips prk snake_case_ = AltDiffusionImgaImgPipeline( unet=_UpperCAmelCase , scheduler=_UpperCAmelCase , vae=_UpperCAmelCase , text_encoder=_UpperCAmelCase , tokenizer=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=self.dummy_extractor , ) snake_case_ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=_UpperCAmelCase ) snake_case_ = alt_pipe.to(_UpperCAmelCase ) alt_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) snake_case_ = """A painting of a squirrel eating a burger""" snake_case_ = torch.manual_seed(0 ) snake_case_ = alt_pipe( [prompt] , generator=_UpperCAmelCase , num_inference_steps=2 , output_type="""np""" , image=_UpperCAmelCase , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) # resize to resolution that is divisible by 8 but not 16 or 32 snake_case_ = init_image.resize((760, 504) ) snake_case_ = """BAAI/AltDiffusion""" snake_case_ = AltDiffusionImgaImgPipeline.from_pretrained( _UpperCAmelCase , safety_checker=_UpperCAmelCase , ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() snake_case_ = """A fantasy landscape, trending on artstation""" snake_case_ = torch.manual_seed(0 ) snake_case_ = pipe( prompt=_UpperCAmelCase , image=_UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , generator=_UpperCAmelCase , output_type="""np""" , ) snake_case_ = output.images[0] snake_case_ = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) snake_case_ = np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) snake_case_ = init_image.resize((768, 512) ) snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy""" ) snake_case_ = """BAAI/AltDiffusion""" snake_case_ = AltDiffusionImgaImgPipeline.from_pretrained( _UpperCAmelCase , safety_checker=_UpperCAmelCase , ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() snake_case_ = """A fantasy landscape, trending on artstation""" snake_case_ = torch.manual_seed(0 ) snake_case_ = pipe( prompt=_UpperCAmelCase , image=_UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , generator=_UpperCAmelCase , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1E-2
713
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
0
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowerCAmelCase_ ( _a ): def snake_case_ ( self ) -> Dict: UpperCamelCase : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'tf_padding' ) ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'depth_multiplier' ) ) class lowerCAmelCase_ : def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=13, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=32, SCREAMING_SNAKE_CASE_=0.25, SCREAMING_SNAKE_CASE_=8, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=1024, SCREAMING_SNAKE_CASE_=32, SCREAMING_SNAKE_CASE_="relu6", SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=0.02, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=10, SCREAMING_SNAKE_CASE_=None, ) -> Union[str, Any]: UpperCamelCase : List[Any] = parent UpperCamelCase : int = batch_size UpperCamelCase : Tuple = num_channels UpperCamelCase : Dict = image_size UpperCamelCase : Tuple = depth_multiplier UpperCamelCase : str = min_depth UpperCamelCase : Tuple = tf_padding UpperCamelCase : Optional[int] = int(last_hidden_size * depth_multiplier ) UpperCamelCase : str = output_stride UpperCamelCase : str = hidden_act UpperCamelCase : str = classifier_dropout_prob UpperCamelCase : Dict = use_labels UpperCamelCase : int = is_training UpperCamelCase : Tuple = num_labels UpperCamelCase : Dict = initializer_range UpperCamelCase : Tuple = scope def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase : Dict = None UpperCamelCase : List[str] = None if self.use_labels: UpperCamelCase : Any = ids_tensor([self.batch_size], self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels ) UpperCamelCase : Optional[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def snake_case_ ( self ) -> List[str]: return MobileNetVaConfig( num_channels=self.num_channels, image_size=self.image_size, depth_multiplier=self.depth_multiplier, min_depth=self.min_depth, tf_padding=self.tf_padding, hidden_act=self.hidden_act, classifier_dropout_prob=self.classifier_dropout_prob, initializer_range=self.initializer_range, ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase : int = MobileNetVaModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.last_hidden_state.shape, ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ), ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase : Optional[int] = self.num_labels UpperCamelCase : Union[str, Any] = MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_, labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : List[Any] = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Dict = config_and_inputs UpperCamelCase : List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _a , _a , unittest.TestCase ): UpperCAmelCase__ : int = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () UpperCAmelCase__ : Dict = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Optional[int] = False UpperCAmelCase__ : Union[str, Any] = False UpperCAmelCase__ : Union[str, Any] = False def snake_case_ ( self ) -> str: UpperCamelCase : Optional[Any] = MobileNetVaModelTester(self ) UpperCamelCase : List[Any] = MobileNetVaConfigTester(self, config_class=SCREAMING_SNAKE_CASE_, has_text_modality=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> List[Any]: self.config_tester.run_common_tests() @unittest.skip(reason='MobileNetV1 does not use inputs_embeds' ) def snake_case_ ( self ) -> Dict: pass @unittest.skip(reason='MobileNetV1 does not support input and output embeddings' ) def snake_case_ ( self ) -> Optional[Any]: pass @unittest.skip(reason='MobileNetV1 does not output attentions' ) def snake_case_ ( self ) -> str: pass def snake_case_ ( self ) -> Any: UpperCamelCase , UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : Optional[Any] = [*signature.parameters.keys()] UpperCamelCase : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1], SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> List[Any]: UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> int: def check_hidden_states_output(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase : int = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = outputs.hidden_states UpperCamelCase : int = 26 self.assertEqual(len(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Dict = True check_hidden_states_output(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase : List[str] = True check_hidden_states_output(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Dict: UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) @slow def snake_case_ ( self ) -> Union[str, Any]: for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = MobileNetVaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase ( ) -> Union[str, Any]: UpperCamelCase : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class lowerCAmelCase_ ( unittest.TestCase ): @cached_property def snake_case_ ( self ) -> Optional[int]: return ( MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224' ) if is_vision_available() else None ) @slow def snake_case_ ( self ) -> int: UpperCamelCase : Optional[Any] = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.default_image_processor UpperCamelCase : int = prepare_img() UpperCamelCase : Optional[int] = image_processor(images=SCREAMING_SNAKE_CASE_, return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase : Optional[int] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3], SCREAMING_SNAKE_CASE_, atol=1e-4 ) )
40
"""simple docstring""" import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( _a , unittest.TestCase ): _a = BertJapaneseTokenizer _a = False _a = True def __lowercase ( self : Any ): super().setUp() lowerCAmelCase = [ """[UNK]""", """[CLS]""", """[SEP]""", """こんにちは""", """こん""", """にちは""", """ばんは""", """##こん""", """##にちは""", """##ばんは""", """世界""", """##世界""", """、""", """##、""", """。""", """##。""", ] lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def __lowercase ( self : int , lowerCAmelCase : List[Any] ): lowerCAmelCase = """こんにちは、世界。 \nこんばんは、世界。""" lowerCAmelCase = """こんにちは 、 世界 。 こんばんは 、 世界 。""" return input_text, output_text def __lowercase ( self : Optional[Any] , lowerCAmelCase : List[Any] ): lowerCAmelCase , lowerCAmelCase = self.get_input_output_texts(lowerCAmelCase ) lowerCAmelCase = tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.decode(lowerCAmelCase , clean_up_tokenization_spaces=lowerCAmelCase ) return text, ids def __lowercase ( self : List[str] ): pass # TODO add if relevant def __lowercase ( self : Optional[Any] ): pass # TODO add if relevant def __lowercase ( self : Any ): pass # TODO add if relevant def __lowercase ( self : List[Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file ) lowerCAmelCase = tokenizer.tokenize("""こんにちは、世界。\nこんばんは、世界。""" ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def __lowercase ( self : int ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""mecab""" ) self.assertIsNotNone(lowerCAmelCase ) lowerCAmelCase = """こんにちは、世界。\nこんばんは、世界。""" lowerCAmelCase = tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) lowerCAmelCase = os.path.join(self.tmpdirname , """tokenizer.bin""" ) with open(lowerCAmelCase , """wb""" ) as handle: pickle.dump(lowerCAmelCase , lowerCAmelCase ) with open(lowerCAmelCase , """rb""" ) as handle: lowerCAmelCase = pickle.load(lowerCAmelCase ) lowerCAmelCase = tokenizer_new.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) def __lowercase ( self : str ): lowerCAmelCase = MecabTokenizer(mecab_dic="""ipadic""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : int ): try: lowerCAmelCase = MecabTokenizer(mecab_dic="""unidic_lite""" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : Optional[int] ): try: lowerCAmelCase = MecabTokenizer(mecab_dic="""unidic""" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : Any ): lowerCAmelCase = MecabTokenizer(do_lower_case=lowerCAmelCase , mecab_dic="""ipadic""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iphone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : Optional[int] ): try: lowerCAmelCase = MecabTokenizer( do_lower_case=lowerCAmelCase , normalize_text=lowerCAmelCase , mecab_option="""-d /usr/local/lib/mecab/dic/jumandic""" ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) def __lowercase ( self : int ): lowerCAmelCase = MecabTokenizer(normalize_text=lowerCAmelCase , mecab_dic="""ipadic""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """ """, """。"""] , ) @require_sudachi def __lowercase ( self : List[Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""sudachi""" ) self.assertIsNotNone(lowerCAmelCase ) lowerCAmelCase = """こんにちは、世界。\nこんばんは、世界。""" lowerCAmelCase = tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) lowerCAmelCase = os.path.join(self.tmpdirname , """tokenizer.bin""" ) with open(lowerCAmelCase , """wb""" ) as handle: pickle.dump(lowerCAmelCase , lowerCAmelCase ) with open(lowerCAmelCase , """rb""" ) as handle: lowerCAmelCase = pickle.load(lowerCAmelCase ) lowerCAmelCase = tokenizer_new.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) @require_sudachi def __lowercase ( self : str ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iPhone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """ """, """。""", """ """, """ """] , ) @require_sudachi def __lowercase ( self : str ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""A""" ) self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国""", """人""", """参政""", """権"""] ) @require_sudachi def __lowercase ( self : Dict ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""B""" ) self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国人""", """参政権"""] ) @require_sudachi def __lowercase ( self : int ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""C""" ) self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国人参政権"""] ) @require_sudachi def __lowercase ( self : str ): lowerCAmelCase = SudachiTokenizer(do_lower_case=lowerCAmelCase , sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iphone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """ """, """。""", """ """, """ """] , ) @require_sudachi def __lowercase ( self : Tuple ): lowerCAmelCase = SudachiTokenizer(normalize_text=lowerCAmelCase , sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iPhone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """\u3000""", """。""", """ """, """ """] , ) @require_sudachi def __lowercase ( self : List[Any] ): lowerCAmelCase = SudachiTokenizer(trim_whitespace=lowerCAmelCase , sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) @require_jumanpp def __lowercase ( self : List[Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""jumanpp""" ) self.assertIsNotNone(lowerCAmelCase ) lowerCAmelCase = """こんにちは、世界。\nこんばんは、世界。""" lowerCAmelCase = tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) lowerCAmelCase = os.path.join(self.tmpdirname , """tokenizer.bin""" ) with open(lowerCAmelCase , """wb""" ) as handle: pickle.dump(lowerCAmelCase , lowerCAmelCase ) with open(lowerCAmelCase , """rb""" ) as handle: lowerCAmelCase = pickle.load(lowerCAmelCase ) lowerCAmelCase = tokenizer_new.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) @require_jumanpp def __lowercase ( self : Optional[Any] ): lowerCAmelCase = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) @require_jumanpp def __lowercase ( self : Optional[Any] ): lowerCAmelCase = JumanppTokenizer(do_lower_case=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iphone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) @require_jumanpp def __lowercase ( self : int ): lowerCAmelCase = JumanppTokenizer(normalize_text=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""ア""", """ッ""", """フ""", """゚""", """ル""", """ストア""", """で""", """iPhone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) @require_jumanpp def __lowercase ( self : Any ): lowerCAmelCase = JumanppTokenizer(trim_whitespace=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れた""", """。"""] , ) @require_jumanpp def __lowercase ( self : Tuple ): lowerCAmelCase = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize("""ありがとうございますm(_ _)m見つけるのが大変です。""" ) , ["""ありがとう""", """ございます""", """m(_ _)m""", """見つける""", """の""", """が""", """大変です""", """。"""] , ) def __lowercase ( self : str ): lowerCAmelCase = ["""[UNK]""", """[CLS]""", """[SEP]""", """こんにちは""", """こん""", """にちは""", """ばんは""", """##こん""", """##にちは""", """##ばんは"""] lowerCAmelCase = {} for i, token in enumerate(lowerCAmelCase ): lowerCAmelCase = i lowerCAmelCase = WordpieceTokenizer(vocab=lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""こんにちは""" ) , ["""こんにちは"""] ) self.assertListEqual(tokenizer.tokenize("""こんばんは""" ) , ["""こん""", """##ばんは"""] ) self.assertListEqual(tokenizer.tokenize("""こんばんは こんばんにちは こんにちは""" ) , ["""こん""", """##ばんは""", """[UNK]""", """こんにちは"""] ) def __lowercase ( self : Dict ): lowerCAmelCase = BertJapaneseTokenizer.from_pretrained("""nlp-waseda/roberta-base-japanese-with-auto-jumanpp""" ) lowerCAmelCase = tokenizer.subword_tokenizer lowerCAmelCase = subword_tokenizer.tokenize("""国境 の 長い トンネル を 抜ける と 雪国 であった 。""" ) self.assertListEqual(lowerCAmelCase , ["""▁国境""", """▁の""", """▁長い""", """▁トンネル""", """▁を""", """▁抜ける""", """▁と""", """▁雪""", """国""", """▁であった""", """▁。"""] ) lowerCAmelCase = subword_tokenizer.tokenize("""こんばんは こんばん にち は こんにちは""" ) self.assertListEqual(lowerCAmelCase , ["""▁こん""", """ばん""", """は""", """▁こん""", """ばん""", """▁に""", """ち""", """▁は""", """▁こんにちは"""] ) def __lowercase ( self : str ): lowerCAmelCase = self.tokenizer_class.from_pretrained("""cl-tohoku/bert-base-japanese""" ) lowerCAmelCase = tokenizer.encode("""ありがとう。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.encode("""どういたしまして。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase , lowerCAmelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( _a , unittest.TestCase ): _a = BertJapaneseTokenizer _a = False def __lowercase ( self : Union[str, Any] ): super().setUp() lowerCAmelCase = ["""[UNK]""", """[CLS]""", """[SEP]""", """こ""", """ん""", """に""", """ち""", """は""", """ば""", """世""", """界""", """、""", """。"""] lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def __lowercase ( self : Optional[int] , **lowerCAmelCase : Optional[Any] ): return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type="""character""" , **lowerCAmelCase ) def __lowercase ( self : List[str] , lowerCAmelCase : Union[str, Any] ): lowerCAmelCase = """こんにちは、世界。 \nこんばんは、世界。""" lowerCAmelCase = """こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。""" return input_text, output_text def __lowercase ( self : List[Any] ): pass # TODO add if relevant def __lowercase ( self : Optional[Any] ): pass # TODO add if relevant def __lowercase ( self : int ): pass # TODO add if relevant def __lowercase ( self : Union[str, Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , subword_tokenizer_type="""character""" ) lowerCAmelCase = tokenizer.tokenize("""こんにちは、世界。 \nこんばんは、世界。""" ) self.assertListEqual( lowerCAmelCase , ["""こ""", """ん""", """に""", """ち""", """は""", """、""", """世""", """界""", """。""", """こ""", """ん""", """ば""", """ん""", """は""", """、""", """世""", """界""", """。"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def __lowercase ( self : Any ): lowerCAmelCase = ["""[UNK]""", """[CLS]""", """[SEP]""", """こ""", """ん""", """に""", """ち""", """は""", """ば""", """世""", """界""", """、""", """。"""] lowerCAmelCase = {} for i, token in enumerate(lowerCAmelCase ): lowerCAmelCase = i lowerCAmelCase = CharacterTokenizer(vocab=lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""こんにちは""" ) , ["""こ""", """ん""", """に""", """ち""", """は"""] ) self.assertListEqual(tokenizer.tokenize("""こんにちほ""" ) , ["""こ""", """ん""", """に""", """ち""", """[UNK]"""] ) def __lowercase ( self : Tuple ): lowerCAmelCase = self.tokenizer_class.from_pretrained("""cl-tohoku/bert-base-japanese-char""" ) lowerCAmelCase = tokenizer.encode("""ありがとう。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.encode("""どういたしまして。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase , lowerCAmelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowercase ( self : Optional[int] ): lowerCAmelCase = """cl-tohoku/bert-base-japanese""" lowerCAmelCase = AutoTokenizer.from_pretrained(lowerCAmelCase ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowercase ( self : List[str] ): lowerCAmelCase = """cl-tohoku/bert-base-japanese""" with self.assertLogs("""transformers""" , level="""WARNING""" ) as cm: BertTokenizer.from_pretrained(lowerCAmelCase ) self.assertTrue( cm.records[0].message.startswith( """The tokenizer class you load from this checkpoint is not the same type as the class this function""" """ is called from.""" ) ) lowerCAmelCase = """bert-base-cased""" with self.assertLogs("""transformers""" , level="""WARNING""" ) as cm: BertJapaneseTokenizer.from_pretrained(lowerCAmelCase ) self.assertTrue( cm.records[0].message.startswith( """The tokenizer class you load from this checkpoint is not the same type as the class this function""" """ is called from.""" ) )
169
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
703
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __lowercase : lowercase = LEDConfig lowercase = {} lowercase = 'gelu' def __init__( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict=13 , __lowerCamelCase : Optional[Any]=7 , __lowerCamelCase : Any=True , __lowerCamelCase : List[str]=False , __lowerCamelCase : Any=99 , __lowerCamelCase : Any=32 , __lowerCamelCase : str=2 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Union[str, Any]=37 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : Optional[int]=20 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : Any=1 , __lowerCamelCase : Optional[int]=0 , __lowerCamelCase : Any=4 , ) -> str: '''simple docstring''' lowercase = parent lowercase = batch_size lowercase = seq_length lowercase = is_training lowercase = use_labels lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = eos_token_id lowercase = pad_token_id lowercase = bos_token_id lowercase = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after lowercase = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests lowercase = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __a ( self : Optional[int] ) -> Tuple: '''simple docstring''' lowercase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowercase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowercase = tf.concat([input_ids, eos_tensor] , axis=1 ) lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) lowercase = prepare_led_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) lowercase = tf.concat( [tf.zeros_like(__lowerCamelCase )[:, :-1], tf.ones_like(__lowerCamelCase )[:, -1:]] , axis=-1 , ) lowercase = global_attention_mask return config, inputs_dict def __a ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Dict ) -> Optional[Any]: '''simple docstring''' lowercase = TFLEDModel(config=__lowerCamelCase ).get_decoder() lowercase = inputs_dict['''input_ids'''] lowercase = input_ids[:1, :] lowercase = inputs_dict['''attention_mask'''][:1, :] lowercase = 1 # first forward pass lowercase = model(__lowerCamelCase , attention_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) lowercase ,lowercase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowercase = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowercase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowercase = tf.concat([input_ids, next_tokens] , axis=-1 ) lowercase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowercase = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] lowercase = 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 lowercase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowercase = output_from_no_past[:, -3:, random_slice_idx] lowercase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1E-3 ) def __UpperCAmelCase ( UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase=None, UpperCAmelCase=None, UpperCAmelCase=None, UpperCAmelCase=None, )-> str: """simple docstring""" if attention_mask is None: lowercase = tf.cast(tf.math.not_equal(UpperCAmelCase, config.pad_token_id ), tf.inta ) if decoder_attention_mask is None: lowercase = 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: lowercase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowercase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __lowercase ( _A , _A , unittest.TestCase ): lowercase = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () lowercase = (TFLEDForConditionalGeneration,) if is_tf_available() else () lowercase = ( { 'conversational': TFLEDForConditionalGeneration, 'feature-extraction': TFLEDModel, 'summarization': TFLEDForConditionalGeneration, 'text2text-generation': TFLEDForConditionalGeneration, 'translation': TFLEDForConditionalGeneration, } if is_tf_available() else {} ) lowercase = True lowercase = False lowercase = False lowercase = False def __a ( self : Dict ) -> int: '''simple docstring''' lowercase = TFLEDModelTester(self ) lowercase = ConfigTester(self , config_class=__lowerCamelCase ) def __a ( self : Optional[Any] ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def __a ( self : List[str] ) -> Any: '''simple docstring''' lowercase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) def __a ( self : List[Any] ) -> Tuple: '''simple docstring''' lowercase ,lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = tf.zeros_like(inputs_dict['''attention_mask'''] ) lowercase = 2 lowercase = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) lowercase = True lowercase = self.model_tester.seq_length lowercase = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__lowerCamelCase : int ): lowercase = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__lowerCamelCase : Optional[Any] ): lowercase = [t.numpy() for t in outputs.encoder_attentions] lowercase = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: lowercase = True lowercase = False lowercase = False lowercase = model_class(__lowerCamelCase ) lowercase = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) lowercase = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: lowercase = model_class(__lowerCamelCase ) lowercase = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] lowercase = True lowercase = model_class(__lowerCamelCase ) lowercase = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine lowercase = True lowercase = True lowercase = model_class(__lowerCamelCase ) lowercase = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def __a ( self : Dict ) -> str: '''simple docstring''' pass def __a ( self : List[Any] ) -> Optional[int]: '''simple docstring''' pass def __UpperCAmelCase ( UpperCAmelCase )-> Optional[Any]: """simple docstring""" return tf.constant(UpperCAmelCase, dtype=tf.intaa ) A_ = 1e-4 @slow @require_tf class __lowercase ( unittest.TestCase ): def __a ( self : List[Any] ) -> str: '''simple docstring''' lowercase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here lowercase = _long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] ) lowercase = _long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] ) lowercase = prepare_led_inputs_dict(model.config , __lowerCamelCase , __lowerCamelCase ) lowercase = model(**__lowerCamelCase )[0] lowercase = (1, 10_24, 7_68) self.assertEqual(output.shape , __lowerCamelCase ) # change to expected output here lowercase = tf.convert_to_tensor( [[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] , ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-3 ) def __a ( self : str ) -> Optional[Any]: '''simple docstring''' lowercase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here lowercase = _long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] ) lowercase = _long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] ) lowercase = prepare_led_inputs_dict(model.config , __lowerCamelCase , __lowerCamelCase ) lowercase = model(**__lowerCamelCase )[0] lowercase = (1, 10_24, model.config.vocab_size) self.assertEqual(output.shape , __lowerCamelCase ) # change to expected output here lowercase = tf.convert_to_tensor( [[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] , ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-3 , rtol=1E-3 )
479
0
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=__UpperCamelCase ) class _A ( __UpperCamelCase ): lowercase__: int = field(default='''question-answering-extractive''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) lowercase__: Dict = Features({'''question''': Value('''string''' ), '''context''': Value('''string''' )} ) lowercase__: List[str] = Features( { '''answers''': Sequence( { '''text''': Value('''string''' ), '''answer_start''': Value('''int32''' ), } ) } ) lowercase__: Optional[int] = '''question''' lowercase__: List[str] = '''context''' lowercase__: List[str] = '''answers''' @property def lowercase__ ( self : int ) -> Dict[str, str]: """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
26
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_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ = MvpTokenizer UpperCamelCase_ = MvpTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = filter_roberta_detectors def lowerCAmelCase__ ( self) -> Optional[int]: super().setUp() UpperCamelCase__ : Dict = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] UpperCamelCase__ : int = dict(zip(UpperCamelCase , range(len(UpperCamelCase)))) UpperCamelCase__ : List[str] = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] UpperCamelCase__ : Union[str, Any] = {'unk_token': '<unk>'} UpperCamelCase__ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) UpperCamelCase__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file']) with open(self.vocab_file , 'w' , encoding='utf-8') as fp: fp.write(json.dumps(UpperCamelCase) + '\n') with open(self.merges_file , 'w' , encoding='utf-8') as fp: fp.write('\n'.join(UpperCamelCase)) def lowerCAmelCase__ ( self , **UpperCamelCase) -> int: kwargs.update(self.special_tokens_map) return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCamelCase) def lowerCAmelCase__ ( self , **UpperCamelCase) -> Optional[Any]: kwargs.update(self.special_tokens_map) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **UpperCamelCase) def lowerCAmelCase__ ( self , UpperCamelCase) -> str: return "lower newer", "lower newer" @cached_property def lowerCAmelCase__ ( self) -> Dict: return MvpTokenizer.from_pretrained('RUCAIBox/mvp') @cached_property def lowerCAmelCase__ ( self) -> Union[str, Any]: return MvpTokenizerFast.from_pretrained('RUCAIBox/mvp') @require_torch def lowerCAmelCase__ ( self) -> Optional[Any]: UpperCamelCase__ : Union[str, Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] UpperCamelCase__ : 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]: UpperCamelCase__ : Dict = tokenizer(UpperCamelCase , max_length=len(UpperCamelCase) , padding=UpperCamelCase , return_tensors='pt') self.assertIsInstance(UpperCamelCase , UpperCamelCase) self.assertEqual((2, 9) , batch.input_ids.shape) self.assertEqual((2, 9) , batch.attention_mask.shape) UpperCamelCase__ : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(UpperCamelCase , UpperCamelCase) # Test that special tokens are reset @require_torch def lowerCAmelCase__ ( self) -> Any: UpperCamelCase__ : List[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ : int = tokenizer(UpperCamelCase , padding=UpperCamelCase , return_tensors='pt') # check if input_ids are returned and no labels self.assertIn('input_ids' , UpperCamelCase) self.assertIn('attention_mask' , UpperCamelCase) self.assertNotIn('labels' , UpperCamelCase) self.assertNotIn('decoder_attention_mask' , UpperCamelCase) @require_torch def lowerCAmelCase__ ( self) -> List[str]: UpperCamelCase__ : List[Any] = [ 'Summary of the text.', 'Another summary.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ : Any = tokenizer(text_target=UpperCamelCase , max_length=32 , padding='max_length' , return_tensors='pt') self.assertEqual(32 , targets['input_ids'].shape[1]) @require_torch def lowerCAmelCase__ ( self) -> int: for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ : Optional[Any] = tokenizer( ['I am a small frog' * 10_24, 'I am a small frog'] , padding=UpperCamelCase , truncation=UpperCamelCase , return_tensors='pt') self.assertIsInstance(UpperCamelCase , UpperCamelCase) self.assertEqual(batch.input_ids.shape , (2, 10_24)) @require_torch def lowerCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase__ : Dict = ['A long paragraph for summarization.'] UpperCamelCase__ : Union[str, Any] = [ 'Summary of the text.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ : List[Any] = tokenizer(UpperCamelCase , text_target=UpperCamelCase , return_tensors='pt') UpperCamelCase__ : List[str] = inputs['input_ids'] UpperCamelCase__ : 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) -> List[Any]: pass def lowerCAmelCase__ ( self) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""): UpperCamelCase__ : List[str] = self.rust_tokenizer_class.from_pretrained(UpperCamelCase , **UpperCamelCase) UpperCamelCase__ : Tuple = self.tokenizer_class.from_pretrained(UpperCamelCase , **UpperCamelCase) UpperCamelCase__ : Tuple = 'A, <mask> AllenNLP sentence.' UpperCamelCase__ : Optional[Any] = tokenizer_r.encode_plus(UpperCamelCase , add_special_tokens=UpperCamelCase , return_token_type_ids=UpperCamelCase) UpperCamelCase__ : Union[str, Any] = tokenizer_p.encode_plus(UpperCamelCase , add_special_tokens=UpperCamelCase , return_token_type_ids=UpperCamelCase) # 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']) , ) UpperCamelCase__ : Any = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids']) UpperCamelCase__ : Dict = 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( UpperCamelCase , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>']) self.assertSequenceEqual( UpperCamelCase , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'])
410
0
from random import randint from tempfile import TemporaryFile import numpy as np def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = 0 if start < end: lowercase = randint(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase = a[end] lowercase = a[pivot] lowercase = temp lowercase , lowercase = _in_place_partition(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) count += _in_place_quick_sort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , p - 1 ) count += _in_place_quick_sort(__SCREAMING_SNAKE_CASE , p + 1 , __SCREAMING_SNAKE_CASE ) return count def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = 0 lowercase = randint(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase = a[end] lowercase = a[pivot] lowercase = temp lowercase = start - 1 for index in range(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowercase = new_pivot_index + 1 lowercase = a[new_pivot_index] lowercase = a[index] lowercase = temp lowercase = a[new_pivot_index + 1] lowercase = a[end] lowercase = temp return new_pivot_index + 1, count UpperCAmelCase = TemporaryFile() UpperCAmelCase = 100 # 1000 elements are to be sorted UpperCAmelCase , UpperCAmelCase = 0, 1 # mean and standard deviation UpperCAmelCase = np.random.normal(mu, sigma, p) np.save(outfile, X) print('''The array is''') print(X) outfile.seek(0) # using the same array UpperCAmelCase = np.load(outfile) UpperCAmelCase = len(M) - 1 UpperCAmelCase = _in_place_quick_sort(M, 0, r) print( '''No of Comparisons for 100 elements selected from a standard normal distribution''' '''is :''' ) print(z)
565
import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger UpperCAmelCase = '''<<<<<<< This should probably be modified because it mentions: ''' UpperCAmelCase = '''======= >>>>>>> ''' UpperCAmelCase = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] UpperCAmelCase = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ): return ConvertCommand(args.tfds_path , args.datasets_directory ) class A_ ( __lowerCamelCase ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case ): lowercase = parser.add_parser( 'convert' , help='Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.' , ) train_parser.add_argument( '--tfds_path' , type=snake_case , required=snake_case , help='Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.' , ) train_parser.add_argument( '--datasets_directory' , type=snake_case , required=snake_case , help='Path to the HuggingFace Datasets folder.' ) train_parser.set_defaults(func=snake_case ) def __init__( self , snake_case , snake_case , *snake_case ): lowercase = get_logger('datasets-cli/converting' ) lowercase = tfds_path lowercase = datasets_directory def SCREAMING_SNAKE_CASE__ ( self ): if os.path.isdir(self._tfds_path ): lowercase = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): lowercase = os.path.dirname(self._tfds_path ) else: raise ValueError('--tfds_path is neither a directory nor a file. Please check path.' ) lowercase = os.path.abspath(self._datasets_directory ) self._logger.info(F'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) lowercase = [] lowercase = [] lowercase = {} if os.path.isdir(self._tfds_path ): lowercase = os.listdir(snake_case ) else: lowercase = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(F'''Looking at file {f_name}''' ) lowercase = os.path.join(snake_case , snake_case ) lowercase = os.path.join(snake_case , snake_case ) if not os.path.isfile(snake_case ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('Skipping file' ) continue with open(snake_case , encoding='utf-8' ) as f: lowercase = f.readlines() lowercase = [] lowercase = False lowercase = False lowercase = [] for line in lines: lowercase = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: lowercase = 'import datasets\n' elif "import tensorflow" in out_line: # order is important here lowercase = '' continue elif "from absl import logging" in out_line: lowercase = 'from datasets import logging\n' elif "getLogger" in out_line: lowercase = out_line.replace('getLogger' , 'get_logger' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): lowercase = True lowercase = list(filter(lambda snake_case : e in out_line , snake_case ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(snake_case ) + '\n' ) out_lines.append(snake_case ) out_lines.append(snake_case ) continue else: for pattern, replacement in TO_CONVERT: lowercase = re.sub(snake_case , snake_case , snake_case ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: lowercase = re.match(r'from\stensorflow_datasets.*import\s([^\.\r\n]+)' , snake_case ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(',' ) ) lowercase = 'from . import ' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(F'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: lowercase = True out_lines.append(snake_case ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset lowercase = f_name.replace('.py' , '' ) lowercase = os.path.join(snake_case , snake_case ) lowercase = os.path.join(snake_case , snake_case ) os.makedirs(snake_case , exist_ok=snake_case ) self._logger.info(F'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(snake_case ) if needs_manual_update: with_manual_update.append(snake_case ) with open(snake_case , 'w' , encoding='utf-8' ) as f: f.writelines(snake_case ) self._logger.info(F'''Converted in {output_file}''' ) for utils_file in utils_files: try: lowercase = os.path.basename(snake_case ) lowercase = imports_to_builder_map[f_name.replace('.py' , '' )] self._logger.info(F'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(snake_case , snake_case ) except KeyError: self._logger.error(F'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( F'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
565
1
"""simple docstring""" import os def lowercase ( ) -> int: with open(os.path.dirname(SCREAMING_SNAKE_CASE__ ) + '''/p022_names.txt''' ) as file: __magic_name__ = str(file.readlines()[0] ) __magic_name__ = names.replace('''\"''' , '''''' ).split(''',''' ) names.sort() __magic_name__ = 0 __magic_name__ = 0 for i, name in enumerate(SCREAMING_SNAKE_CASE__ ): for letter in name: name_score += ord(SCREAMING_SNAKE_CASE__ ) - 64 total_score += (i + 1) * name_score __magic_name__ = 0 return total_score if __name__ == "__main__": print(solution())
490
"""simple docstring""" import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __lowercase ( _UpperCAmelCase): """simple docstring""" @require_torch def __UpperCamelCase (self ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched snake_case_ : int = """ from transformers import BertConfig, BertModel, BertTokenizer, pipeline """ snake_case_ : Any = """ mname = \"hf-internal-testing/tiny-random-bert\" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task=\"fill-mask\", model=mname) print(\"success\") """ snake_case_ : Dict = """ import socket def offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\") socket.socket = offline_socket """ # Force fetching the files so that we can use the cache snake_case_ : Tuple = """hf-internal-testing/tiny-random-bert""" BertConfig.from_pretrained(lowercase__ ) BertModel.from_pretrained(lowercase__ ) BertTokenizer.from_pretrained(lowercase__ ) pipeline(task="""fill-mask""" , model=lowercase__ ) # baseline - just load from_pretrained with normal network snake_case_ : Optional[Any] = [sys.executable, """-c""", """\n""".join([load, run, mock] )] # should succeed snake_case_ : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files snake_case_ : str = """1""" snake_case_ : List[Any] = subprocess.run(lowercase__ , env=lowercase__ , check=lowercase__ , capture_output=lowercase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def __UpperCamelCase (self ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched snake_case_ : List[str] = """ from transformers import BertConfig, BertModel, BertTokenizer, pipeline """ snake_case_ : int = """ mname = \"hf-internal-testing/tiny-random-bert\" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task=\"fill-mask\", model=mname) print(\"success\") """ snake_case_ : Optional[int] = """ import socket def offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\") socket.socket = offline_socket """ # Force fetching the files so that we can use the cache snake_case_ : Optional[int] = """hf-internal-testing/tiny-random-bert""" BertConfig.from_pretrained(lowercase__ ) BertModel.from_pretrained(lowercase__ ) BertTokenizer.from_pretrained(lowercase__ ) pipeline(task="""fill-mask""" , model=lowercase__ ) # baseline - just load from_pretrained with normal network snake_case_ : int = [sys.executable, """-c""", """\n""".join([load, run, mock] )] # should succeed snake_case_ : List[Any] = self.get_env() snake_case_ : Dict = subprocess.run(lowercase__ , env=lowercase__ , check=lowercase__ , capture_output=lowercase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def __UpperCamelCase (self ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched snake_case_ : Optional[int] = """ from transformers import BertConfig, BertModel, BertTokenizer """ snake_case_ : Dict = """ mname = \"hf-internal-testing/tiny-random-bert-sharded\" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) print(\"success\") """ snake_case_ : int = """ import socket def offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\") socket.socket = offline_socket """ # baseline - just load from_pretrained with normal network snake_case_ : List[Any] = [sys.executable, """-c""", """\n""".join([load, run] )] # should succeed snake_case_ : List[str] = self.get_env() snake_case_ : str = subprocess.run(lowercase__ , env=lowercase__ , check=lowercase__ , capture_output=lowercase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) # next emulate no network snake_case_ : Any = [sys.executable, """-c""", """\n""".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files snake_case_ : Optional[Any] = """1""" snake_case_ : int = subprocess.run(lowercase__ , env=lowercase__ , check=lowercase__ , capture_output=lowercase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def __UpperCamelCase (self ): snake_case_ : str = """ from transformers import pipeline """ snake_case_ : Dict = """ mname = \"hf-internal-testing/tiny-random-bert\" pipe = pipeline(model=mname) """ snake_case_ : Dict = """ import socket def offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\") socket.socket = offline_socket """ snake_case_ : List[str] = self.get_env() snake_case_ : Dict = """1""" snake_case_ : int = [sys.executable, """-c""", """\n""".join([load, mock, run] )] snake_case_ : Optional[int] = subprocess.run(lowercase__ , env=lowercase__ , check=lowercase__ , capture_output=lowercase__ ) self.assertEqual(result.returncode , 1 , result.stderr ) self.assertIn( """You cannot infer task automatically within `pipeline` when using offline mode""" , result.stderr.decode().replace("""\n""" , """""" ) , ) @require_torch def __UpperCamelCase (self ): snake_case_ : int = """ from transformers import AutoModel """ snake_case_ : Optional[int] = """ mname = \"hf-internal-testing/test_dynamic_model\" AutoModel.from_pretrained(mname, trust_remote_code=True) print(\"success\") """ # baseline - just load from_pretrained with normal network snake_case_ : Dict = [sys.executable, """-c""", """\n""".join([load, run] )] # should succeed snake_case_ : Optional[Any] = self.get_env() snake_case_ : List[str] = subprocess.run(lowercase__ , env=lowercase__ , check=lowercase__ , capture_output=lowercase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files snake_case_ : Any = """1""" snake_case_ : Dict = subprocess.run(lowercase__ , env=lowercase__ , check=lowercase__ , capture_output=lowercase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() )
480
0
'''simple docstring''' def a ( lowerCamelCase__ ): '''simple docstring''' if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError("""Input value must be an 'int' type""" ) A_ : str = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
686
'''simple docstring''' import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _lowerCAmelCase ( __UpperCAmelCase ): def __init__(self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , **lowercase , ): super().__init__( lowercase , split=lowercase , features=lowercase , cache_dir=lowercase , keep_in_memory=lowercase , streaming=lowercase , num_proc=lowercase , **lowercase , ) A_ : Optional[int] = field A_ : Dict = path_or_paths if isinstance(lowercase , lowercase ) else {self.split: path_or_paths} A_ : Optional[Any] = Json( cache_dir=lowercase , data_files=lowercase , features=lowercase , field=lowercase , **lowercase , ) def _a (self ): # Build iterable dataset if self.streaming: A_ : Optional[int] = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: A_ : int = None A_ : Union[str, Any] = None A_ : int = None A_ : List[str] = None self.builder.download_and_prepare( download_config=lowercase , download_mode=lowercase , verification_mode=lowercase , base_path=lowercase , num_proc=self.num_proc , ) A_ : str = self.builder.as_dataset( split=self.split , verification_mode=lowercase , in_memory=self.keep_in_memory ) return dataset class _lowerCAmelCase : def __init__(self , lowercase , lowercase , lowercase = None , lowercase = None , **lowercase , ): if num_proc is not None and num_proc <= 0: raise ValueError(F'num_proc {num_proc} must be an integer > 0.' ) A_ : Any = dataset A_ : List[str] = path_or_buf A_ : List[str] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE A_ : Optional[Any] = num_proc A_ : List[Any] = """utf-8""" A_ : int = to_json_kwargs def _a (self ): A_ : Tuple = self.to_json_kwargs.pop("""path_or_buf""" , lowercase ) A_ : Tuple = self.to_json_kwargs.pop("""orient""" , """records""" ) A_ : Union[str, Any] = self.to_json_kwargs.pop("""lines""" , True if orient == """records""" else False ) A_ : Union[str, Any] = self.to_json_kwargs.pop("""index""" , False if orient in ["""split""", """table"""] else True ) A_ : Dict = self.to_json_kwargs.pop("""compression""" , lowercase ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(F'`datasets` currently does not support {compression} compression' ) if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf , """wb""" , compression=lowercase ) as buffer: A_ : Tuple = self._write(file_obj=lowercase , orient=lowercase , lines=lowercase , index=lowercase , **self.to_json_kwargs ) else: if compression: raise NotImplementedError( F'The compression parameter is not supported when writing to a buffer, but compression={compression}' """ was passed. Please provide a local path instead.""" ) A_ : Union[str, Any] = self._write( file_obj=self.path_or_buf , orient=lowercase , lines=lowercase , index=lowercase , **self.to_json_kwargs ) return written def _a (self , lowercase ): A_, A_, A_, A_, A_ : List[str] = args A_ : List[str] = query_table( table=self.dataset.data , key=slice(lowercase , offset + self.batch_size ) , indices=self.dataset._indices , ) A_ : Any = batch.to_pandas().to_json( path_or_buf=lowercase , orient=lowercase , lines=lowercase , index=lowercase , **lowercase ) if not json_str.endswith("""\n""" ): json_str += "\n" return json_str.encode(self.encoding ) def _a (self , lowercase , lowercase , lowercase , lowercase , **lowercase , ): A_ : Dict = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating json from Arrow format""" , ): A_ : Optional[int] = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(lowercase ) else: A_, A_ : Tuple = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , lowercase , lowercase )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating json from Arrow format""" , ): written += file_obj.write(lowercase ) return written
686
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
443
'''simple docstring''' from ..utils import DummyObject, requires_backends class lowerCamelCase_ ( metaclass=__a ): lowerCAmelCase__ = ['torch', 'torchsde'] def __init__( self : Tuple , *_A : Any , **_A : Optional[Any] ): '''simple docstring''' requires_backends(self , ['''torch''', '''torchsde'''] ) @classmethod def lowercase_ ( cls : List[Any] , *_A : Tuple , **_A : Tuple ): '''simple docstring''' requires_backends(cls , ['''torch''', '''torchsde'''] ) @classmethod def lowercase_ ( cls : List[str] , *_A : Optional[int] , **_A : Any ): '''simple docstring''' requires_backends(cls , ['''torch''', '''torchsde'''] )
75
0
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() __lowerCamelCase : int = logging.get_logger(__name__) __lowerCamelCase : Dict = ["""model.decoder.embed_positions.weights"""] def A_ ( _lowerCAmelCase ) -> int: if "emb" in name: UpperCamelCase : Union[str, Any] = name.replace("emb" , "model.decoder.embed_tokens" ) if "transformer" in name: UpperCamelCase : str = name.replace("transformer" , "model.decoder" ) if "cross_attention" in name: UpperCamelCase : List[str] = name.replace("cross_attention" , "encoder_attn" ) if "linear1" in name: UpperCamelCase : Tuple = name.replace("linear1" , "fc1" ) if "linear2" in name: UpperCamelCase : int = name.replace("linear2" , "fc2" ) if "norm1" in name: UpperCamelCase : Tuple = name.replace("norm1" , "self_attn_layer_norm" ) if "norm_cross" in name: UpperCamelCase : List[str] = name.replace("norm_cross" , "encoder_attn_layer_norm" ) if "norm2" in name: UpperCamelCase : Dict = name.replace("norm2" , "final_layer_norm" ) if "out_norm" in name: UpperCamelCase : Union[str, Any] = name.replace("out_norm" , "model.decoder.layer_norm" ) if "linears" in name: UpperCamelCase : int = name.replace("linears" , "lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: UpperCamelCase : int = name.replace("condition_provider.conditioners.description.output_proj" , "enc_to_dec_proj" ) return name def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Tuple[Dict, Dict]: UpperCamelCase : Dict = list(state_dict.keys() ) UpperCamelCase : Dict = {} for key in keys: UpperCamelCase : List[str] = state_dict.pop(__UpperCamelCase ) UpperCamelCase : Optional[int] = rename_keys(__UpperCamelCase ) if "in_proj_weight" in key: # split fused qkv proj UpperCamelCase : str = val[:hidden_size, :] UpperCamelCase : List[str] = val[hidden_size : 2 * hidden_size, :] UpperCamelCase : List[str] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: UpperCamelCase : List[str] = val else: UpperCamelCase : Optional[int] = val return state_dict, enc_dec_proj_state_dict def A_ ( _lowerCAmelCase ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values UpperCamelCase : Dict = 1024 UpperCamelCase : str = 24 UpperCamelCase : Optional[int] = 16 elif checkpoint == "medium": UpperCamelCase : Tuple = 1536 UpperCamelCase : str = 48 UpperCamelCase : List[Any] = 24 elif checkpoint == "large": UpperCamelCase : List[str] = 2048 UpperCamelCase : Dict = 48 UpperCamelCase : Any = 32 else: raise ValueError(F"""Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.""" ) UpperCamelCase : int = MusicgenDecoderConfig( hidden_size=__UpperCamelCase , ffn_dim=hidden_size * 4 , num_hidden_layers=__UpperCamelCase , num_attention_heads=__UpperCamelCase , ) return config @torch.no_grad() def A_ ( _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase="cpu" ) -> Tuple: UpperCamelCase : Union[str, Any] = MusicGen.get_pretrained(__UpperCamelCase , device=__UpperCamelCase ) UpperCamelCase : int = decoder_config_from_checkpoint(__UpperCamelCase ) UpperCamelCase : Any = fairseq_model.lm.state_dict() UpperCamelCase , UpperCamelCase : Union[str, Any] = rename_state_dict( __UpperCamelCase , hidden_size=decoder_config.hidden_size ) UpperCamelCase : List[Any] = TaEncoderModel.from_pretrained("t5-base" ) UpperCamelCase : Optional[int] = EncodecModel.from_pretrained("facebook/encodec_32khz" ) UpperCamelCase : str = MusicgenForCausalLM(__UpperCamelCase ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection UpperCamelCase , UpperCamelCase : int = decoder.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__UpperCamelCase ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model UpperCamelCase : Union[str, Any] = MusicgenForConditionalGeneration(text_encoder=__UpperCamelCase , audio_encoder=__UpperCamelCase , decoder=__UpperCamelCase ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__UpperCamelCase ) # check we can do a forward pass UpperCamelCase : str = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) UpperCamelCase : Optional[int] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): UpperCamelCase : str = model(input_ids=__UpperCamelCase , decoder_input_ids=__UpperCamelCase ).logits if logits.shape != (8, 1, 2048): raise ValueError("Incorrect shape for logits" ) # now construct the processor UpperCamelCase : Dict = AutoTokenizer.from_pretrained("t5-base" ) UpperCamelCase : Optional[Any] = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" , padding_side="left" ) UpperCamelCase : int = MusicgenProcessor(feature_extractor=__UpperCamelCase , tokenizer=__UpperCamelCase ) # set the appropriate bos/pad token ids UpperCamelCase : Dict = 2048 UpperCamelCase : int = 2048 # set other default generation config params UpperCamelCase : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) UpperCamelCase : Optional[int] = True UpperCamelCase : List[Any] = 3.0 if pytorch_dump_folder is not None: Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__UpperCamelCase ) processor.save_pretrained(__UpperCamelCase ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__UpperCamelCase ) processor.push_to_hub(__UpperCamelCase ) if __name__ == "__main__": __lowerCamelCase : Any = 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.""" ) __lowerCamelCase : Any = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
707
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=2 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ): '''simple docstring''' UpperCamelCase : Dict = parent UpperCamelCase : str = 13 UpperCamelCase : int = 7 UpperCamelCase : str = True UpperCamelCase : Dict = True UpperCamelCase : str = True UpperCamelCase : Tuple = True UpperCamelCase : List[str] = 99 UpperCamelCase : Optional[Any] = 384 UpperCamelCase : Tuple = 2 UpperCamelCase : Union[str, Any] = 4 UpperCamelCase : Dict = 37 UpperCamelCase : Any = "gelu" UpperCamelCase : List[Any] = 0.1 UpperCamelCase : int = 0.1 UpperCamelCase : Tuple = 512 UpperCamelCase : List[Any] = 16 UpperCamelCase : int = 2 UpperCamelCase : Dict = 0.02 UpperCamelCase : Optional[Any] = 3 UpperCamelCase : List[Any] = 4 UpperCamelCase : Dict = 128 UpperCamelCase : Optional[Any] = 2 UpperCamelCase : Optional[int] = 9 UpperCamelCase : Optional[int] = 1 UpperCamelCase : Union[str, Any] = None def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : str = None if self.use_input_mask: UpperCamelCase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Optional[int] = None UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None if self.use_labels: UpperCamelCase : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Any = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=A_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = TFConvBertModel(config=A_ ) UpperCamelCase : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} UpperCamelCase : Optional[int] = [input_ids, input_mask] UpperCamelCase : Any = model(A_ ) UpperCamelCase : int = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Tuple = TFConvBertForMaskedLM(config=A_ ) UpperCamelCase : int = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : Dict = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Dict = self.num_labels UpperCamelCase : int = TFConvBertForSequenceClassification(config=A_ ) UpperCamelCase : List[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : Optional[Any] = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : List[str] = self.num_choices UpperCamelCase : str = TFConvBertForMultipleChoice(config=A_ ) UpperCamelCase : List[Any] = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Dict = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Any = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : List[str] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } UpperCamelCase : Optional[Any] = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Dict = self.num_labels UpperCamelCase : str = TFConvBertForTokenClassification(config=A_ ) UpperCamelCase : List[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : str = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : List[str] = TFConvBertForQuestionAnswering(config=A_ ) UpperCamelCase : Union[str, Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : Union[str, Any] = model(A_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[Any] = config_and_inputs UpperCamelCase : int = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A__ ( __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :Dict = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) _UpperCAmelCase :Optional[Any] = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) _UpperCAmelCase :Any = False _UpperCAmelCase :int = False _UpperCAmelCase :str = False def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = TFConvBertModelTester(self ) UpperCamelCase : Dict = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase , UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Optional[Any] = True UpperCamelCase : Any = True if hasattr(A_ , "use_cache" ): UpperCamelCase : List[str] = True UpperCamelCase : List[Any] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Any = getattr(self.model_tester , "key_length" , A_ ) for model_class in self.all_model_classes: UpperCamelCase : List[Any] = self._prepare_for_class(A_ , A_ ) UpperCamelCase : Dict = model_class(A_ ) UpperCamelCase : Optional[int] = len(model(A_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(A_ , saved_model=A_ ) UpperCamelCase : Union[str, Any] = os.path.join(A_ , "saved_model" , "1" ) UpperCamelCase : Dict = tf.keras.models.load_model(A_ ) UpperCamelCase : str = model(A_ ) if self.is_encoder_decoder: UpperCamelCase : Union[str, Any] = outputs["encoder_hidden_states"] UpperCamelCase : Any = outputs["encoder_attentions"] else: UpperCamelCase : Any = outputs["hidden_states"] UpperCamelCase : List[str] = outputs["attentions"] self.assertEqual(len(A_ ) , A_ ) UpperCamelCase : int = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(A_ ) , A_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase , UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Dict = True UpperCamelCase : int = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Optional[int] = getattr(self.model_tester , "key_length" , A_ ) UpperCamelCase : Optional[Any] = getattr(self.model_tester , "key_length" , A_ ) def check_decoder_attentions_output(A_ ): UpperCamelCase : Optional[Any] = len(A_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase : Any = outputs.decoder_attentions self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(A_ ): UpperCamelCase : Dict = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase : Union[str, Any] = True UpperCamelCase : List[Any] = False UpperCamelCase : Dict = model_class(A_ ) UpperCamelCase : Dict = model(self._prepare_for_class(A_ , A_ ) ) UpperCamelCase : List[str] = len(A_ ) self.assertEqual(config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) if self.is_encoder_decoder: UpperCamelCase : int = model_class(A_ ) UpperCamelCase : Tuple = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(config.output_hidden_states , A_ ) check_decoder_attentions_output(A_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase : Tuple = True UpperCamelCase : int = model_class(A_ ) UpperCamelCase : Dict = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) # Check attention is always last and order is fine UpperCamelCase : Optional[int] = True UpperCamelCase : List[str] = True UpperCamelCase : Optional[int] = model_class(A_ ) UpperCamelCase : Optional[Any] = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(A_ ) ) self.assertEqual(model.config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) @require_tf class A__ ( unittest.TestCase ): @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) UpperCamelCase : str = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase : List[str] = model(A_ )[0] UpperCamelCase : int = [1, 6, 768] self.assertEqual(output.shape , A_ ) UpperCamelCase : List[str] = tf.constant( [ [ [-0.03_47_54_93, -0.4_68_60_34, -0.30_63_88_32], [0.22_63_72_48, -0.26_98_86_46, -0.7_42_34_24], [0.10_32_48_68, -0.45_01_35_08, -0.58_28_07_84], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , A_ , atol=1e-4 )
38
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" snake_case = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" snake_case = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case , _snake_case = 1 , _snake_case = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_snake_case , hypotheses=_snake_case , min_len=_snake_case , max_len=_snake_case ) }
424
class __A : '''simple docstring''' def __init__( self ): _lowerCAmelCase : Dict = "" _lowerCAmelCase : Optional[Any] = "" _lowerCAmelCase : List[Any] = [] def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: _lowerCAmelCase : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: _lowerCAmelCase : Optional[int] = self.__min_dist_top_down_dp(_snake_case , n - 1 ) _lowerCAmelCase : List[str] = self.__min_dist_top_down_dp(m - 1 , _snake_case ) _lowerCAmelCase : str = self.__min_dist_top_down_dp(m - 1 , n - 1 ) _lowerCAmelCase : Optional[int] = 1 + min(_snake_case , _snake_case , _snake_case ) return self.dp[m][n] def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case ): _lowerCAmelCase : Union[str, Any] = worda _lowerCAmelCase : int = worda _lowerCAmelCase : Tuple = [[-1 for _ in range(len(_snake_case ) )] for _ in range(len(_snake_case ) )] return self.__min_dist_top_down_dp(len(_snake_case ) - 1 , len(_snake_case ) - 1 ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case ): _lowerCAmelCase : str = worda _lowerCAmelCase : Union[str, Any] = worda _lowerCAmelCase : str = len(_snake_case ) _lowerCAmelCase : List[Any] = len(_snake_case ) _lowerCAmelCase : str = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty _lowerCAmelCase : int = j elif j == 0: # second string is empty _lowerCAmelCase : Optional[Any] = i elif worda[i - 1] == worda[j - 1]: # last characters are equal _lowerCAmelCase : Union[str, Any] = self.dp[i - 1][j - 1] else: _lowerCAmelCase : Tuple = self.dp[i][j - 1] _lowerCAmelCase : Dict = self.dp[i - 1][j] _lowerCAmelCase : List[Any] = self.dp[i - 1][j - 1] _lowerCAmelCase : Tuple = 1 + min(_snake_case , _snake_case , _snake_case ) return self.dp[m][n] if __name__ == "__main__": snake_case = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() snake_case = input("Enter the first string: ").strip() snake_case = input("Enter the second string: ").strip() print() print(F'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(F'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
424
1
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() SCREAMING_SNAKE_CASE = 2 class A_ : '''simple docstring''' def __init__( self , *, # begin keyword-only arguments _A="<s>" , _A="<pad>" , _A="</s>" , _A="<unk>" , _A=None , ) -> str: """simple docstring""" _UpperCAmelCase : Optional[Any] = bos, unk, pad, eos _UpperCAmelCase : Optional[int] = [] _UpperCAmelCase : List[str] = [] _UpperCAmelCase : Dict = {} _UpperCAmelCase : Optional[Any] = self.add_symbol(_A) _UpperCAmelCase : Union[str, Any] = self.add_symbol(_A) _UpperCAmelCase : Optional[int] = self.add_symbol(_A) _UpperCAmelCase : Tuple = self.add_symbol(_A) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(_A) _UpperCAmelCase : Any = len(self.symbols) def __eq__( self , _A) -> Union[str, Any]: """simple docstring""" return self.indices == other.indices def __getitem__( self , _A) -> List[Any]: """simple docstring""" if idx < len(self.symbols): return self.symbols[idx] return self.unk_word def __len__( self) -> Optional[int]: """simple docstring""" return len(self.symbols) def __contains__( self , _A) -> Dict: """simple docstring""" return sym in self.indices @classmethod def snake_case__ ( cls , _A) -> str: """simple docstring""" _UpperCAmelCase : Tuple = cls() d.add_from_file(_A) return d def snake_case__ ( self , _A , _A=1 , _A=False) -> Tuple: """simple docstring""" if word in self.indices and not overwrite: _UpperCAmelCase : Union[str, Any] = self.indices[word] _UpperCAmelCase : str = self.count[idx] + n return idx else: _UpperCAmelCase : Dict = len(self.symbols) _UpperCAmelCase : Tuple = idx self.symbols.append(_A) self.count.append(_A) return idx def snake_case__ ( self , _A) -> Tuple: """simple docstring""" return 0 def snake_case__ ( self , _A) -> Optional[int]: """simple docstring""" if isinstance(_A , _A): try: with open(_A , '''r''' , encoding='''utf-8''') as fd: self.add_from_file(_A) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('''Incorrect encoding detected in {}, please rebuild the dataset'''.format(_A)) return _UpperCAmelCase : List[str] = f.readlines() _UpperCAmelCase : Tuple = self._load_meta(_A) for line in lines[indices_start_line:]: try: _UpperCAmelCase : Union[str, Any] = line.rstrip().rsplit(''' ''' , 1) if field == "#fairseq:overwrite": _UpperCAmelCase : Optional[int] = True _UpperCAmelCase : Tuple = line.rsplit(''' ''' , 1) else: _UpperCAmelCase : Union[str, Any] = False _UpperCAmelCase : Dict = int(_A) _UpperCAmelCase : int = line if word in self and not overwrite: raise RuntimeError( '''Duplicate word found when loading Dictionary: \'{}\'. ''' '''Duplicate words can overwrite earlier ones by adding the ''' '''#fairseq:overwrite flag at the end of the corresponding row ''' '''in the dictionary file. If using the Camembert model, please ''' '''download an updated copy of the model file.'''.format(_A)) self.add_symbol(_A , n=_A , overwrite=_A) except ValueError: raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt> [flags]\'''') def _lowerCamelCase ( __A : Union[str, Any] ) -> Dict: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} _UpperCAmelCase : List[Any] = dict((re.sub(r'''@@$''' , '''''' , __A ), v) if k.endswith('''@@''' ) else (re.sub(r'''$''' , '''</w>''' , __A ), v) for k, v in d.items() ) _UpperCAmelCase : Tuple = '''<s> <pad> </s> <unk>'''.split() # restore the special tokens for k in keep_keys: del da[f'''{k}</w>'''] _UpperCAmelCase : List[Any] = d[k] # restore return da def _lowerCamelCase ( __A : List[Any] , __A : Tuple ) -> Tuple: # prep if not os.path.exists(__A ): raise ValueError(f'''path {biogpt_checkpoint_path} does not exist!''' ) os.makedirs(__A , exist_ok=__A ) print(f'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models _UpperCAmelCase : str = os.path.join(__A , '''checkpoint.pt''' ) if not os.path.isfile(__A ): raise ValueError(f'''path to the file {checkpoint_file} does not exist!''' ) _UpperCAmelCase : Tuple = torch.load(__A , map_location='''cpu''' ) _UpperCAmelCase : List[Any] = chkpt['''cfg''']['''model'''] # dicts _UpperCAmelCase : Optional[int] = os.path.join(__A , '''dict.txt''' ) if not os.path.isfile(__A ): raise ValueError(f'''path to the file {dict_file} does not exist!''' ) _UpperCAmelCase : List[str] = Dictionary.load(__A ) _UpperCAmelCase : Tuple = rewrite_dict_keys(src_dict.indices ) _UpperCAmelCase : List[Any] = len(__A ) _UpperCAmelCase : Union[str, Any] = os.path.join(__A , VOCAB_FILES_NAMES['''vocab_file'''] ) print(f'''Generating {src_vocab_file} of {src_vocab_size} records''' ) with open(__A , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__A , ensure_ascii=__A , indent=__A ) ) # merges_file (bpecodes) _UpperCAmelCase : List[Any] = os.path.join(__A , '''bpecodes''' ) if not os.path.isfile(__A ): raise ValueError(f'''path to the file {bpecodes_file} does not exist!''' ) _UpperCAmelCase : Optional[Any] = os.path.join(__A , VOCAB_FILES_NAMES['''merges_file'''] ) shutil.copyfile(__A , __A ) # model config _UpperCAmelCase : Dict = os.path.join(__A , '''config.json''' ) _UpperCAmelCase : Tuple = { '''activation_dropout''': args['''activation_dropout'''], '''architectures''': ['''BioGptForCausalLM'''], '''attention_probs_dropout_prob''': args['''attention_dropout'''], '''bos_token_id''': 0, '''eos_token_id''': 2, '''hidden_act''': args['''activation_fn'''], '''hidden_dropout_prob''': args['''dropout'''], '''hidden_size''': args['''decoder_embed_dim'''], '''initializer_range''': 0.02, '''intermediate_size''': args['''decoder_ffn_embed_dim'''], '''layer_norm_eps''': 1e-12, '''layerdrop''': args['''decoder_layerdrop'''], '''max_position_embeddings''': args['''max_target_positions'''], '''model_type''': '''biogpt''', '''num_attention_heads''': args['''decoder_attention_heads'''], '''num_hidden_layers''': args['''decoder_layers'''], '''pad_token_id''': 1, '''scale_embedding''': not args['''no_scale_embedding'''], '''tie_word_embeddings''': args['''share_decoder_input_output_embed'''], '''vocab_size''': src_vocab_size, } # good hparam defaults to start with print(f'''Generating {biogpt_model_config_file}''' ) with open(__A , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__A , ensure_ascii=__A , indent=__A ) ) # tokenizer config _UpperCAmelCase : List[str] = os.path.join(__A , __A ) _UpperCAmelCase : int = { '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''model_max_length''': 1_024, '''pad_token''': '''<pad>''', '''special_tokens_map_file''': None, '''tokenizer_class''': '''BioGptTokenizer''', '''unk_token''': '''<unk>''', } print(f'''Generating {biogpt_tokenizer_config_file}''' ) with open(__A , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__A , ensure_ascii=__A , indent=__A ) ) # model _UpperCAmelCase : int = chkpt['''model'''] # remove unneeded keys _UpperCAmelCase : Tuple = [ '''decoder.version''', ] for k in ignore_keys: model_state_dict.pop(__A , __A ) _UpperCAmelCase : Union[str, Any] = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('''output_projection.weight''' ): _UpperCAmelCase : List[str] = model_state_dict.pop(__A ) else: _UpperCAmelCase : int = model_state_dict.pop(__A ) _UpperCAmelCase : Optional[int] = BioGptConfig.from_pretrained(__A ) _UpperCAmelCase : List[str] = BioGptForCausalLM(__A ) # check that it loads ok model_new.load_state_dict(__A ) # save _UpperCAmelCase : Union[str, Any] = os.path.join(__A , __A ) print(f'''Generating {pytorch_weights_dump_path}''' ) torch.save(__A , __A ) print('''Conversion is done!''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--biogpt_checkpoint_path', default=None, type=str, required=True, help=( 'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,' ' bpecodes, etc.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) SCREAMING_SNAKE_CASE = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
715
from __future__ import annotations def _lowerCamelCase ( __A : int ) -> list[int]: _UpperCAmelCase : List[str] = [True] * limit _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Dict = False _UpperCAmelCase : List[str] = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): _UpperCAmelCase : List[str] = i * 2 while index < limit: _UpperCAmelCase : Union[str, Any] = False _UpperCAmelCase : int = index + i _UpperCAmelCase : Optional[int] = [2] for i in range(3 , __A , 2 ): if is_prime[i]: primes.append(__A ) return primes def _lowerCamelCase ( __A : int = 1_000_000 ) -> int: _UpperCAmelCase : Any = prime_sieve(__A ) _UpperCAmelCase : Optional[Any] = 0 _UpperCAmelCase : Tuple = 0 for i in range(len(__A ) ): for j in range(i + length , len(__A ) ): _UpperCAmelCase : List[Any] = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: _UpperCAmelCase : List[str] = j - i _UpperCAmelCase : Optional[Any] = sol return largest if __name__ == "__main__": print(F'{solution() = }')
186
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase_ = { """configuration_biogpt""": ["""BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BioGptConfig"""], """tokenization_biogpt""": ["""BioGptTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ """BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BioGptForCausalLM""", """BioGptForTokenClassification""", """BioGptForSequenceClassification""", """BioGptModel""", """BioGptPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def _snake_case ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[str] ) -> Tuple: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file lowerCamelCase_ : Optional[Any] =TapasConfig.from_json_file(lowerCamelCase__ ) # set absolute/relative position embeddings parameter lowerCamelCase_ : Optional[int] =reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": lowerCamelCase_ : Any =TapasForQuestionAnswering(config=lowerCamelCase__ ) elif task == "WTQ": # run_task_main.py hparams lowerCamelCase_ : Optional[Any] =4 lowerCamelCase_ : Optional[int] =True # hparam_utils.py hparams lowerCamelCase_ : Dict =0.66_4694 lowerCamelCase_ : List[Any] =0.20_7951 lowerCamelCase_ : int =0.12_1194 lowerCamelCase_ : Union[str, Any] =True lowerCamelCase_ : List[Any] =True lowerCamelCase_ : str =False lowerCamelCase_ : int =0.035_2513 lowerCamelCase_ : str =TapasForQuestionAnswering(config=lowerCamelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams lowerCamelCase_ : List[Any] =4 lowerCamelCase_ : int =False # hparam_utils.py hparams lowerCamelCase_ : Tuple =36.4519 lowerCamelCase_ : List[str] =0.90_3421 lowerCamelCase_ : Optional[int] =222.088 lowerCamelCase_ : int =True lowerCamelCase_ : Any =True lowerCamelCase_ : List[str] =True lowerCamelCase_ : Any =0.76_3141 lowerCamelCase_ : Dict =TapasForQuestionAnswering(config=lowerCamelCase__ ) elif task == "TABFACT": lowerCamelCase_ : Dict =TapasForSequenceClassification(config=lowerCamelCase__ ) elif task == "MLM": lowerCamelCase_ : Optional[Any] =TapasForMaskedLM(config=lowerCamelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": lowerCamelCase_ : str =TapasModel(config=lowerCamelCase__ ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(lowerCamelCase__ ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) lowerCamelCase_ : List[Any] =TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + "vocab.txt" , model_max_length=512 ) tokenizer.save_pretrained(lowerCamelCase__ ) print("Used relative position embeddings:" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": A__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) A__ : Dict = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
153
0
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self ) -> Optional[Any]: A = tempfile.mkdtemp() # fmt: off A = ["""""", """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on A = dict(zip(lowerCamelCase_ ,range(len(lowerCamelCase_ ) ) ) ) A = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] A = {"""unk_token""": """<unk>"""} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""vocab_file"""] ) A = 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_ ) ) A = { """do_resize""": True, """size""": 2_0, """do_center_crop""": True, """crop_size""": 1_8, """do_normalize""": True, """image_mean""": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], """image_std""": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } A = os.path.join(self.tmpdirname ,lowerCamelCase_ ) with open(self.image_processor_file ,"""w""" ,encoding="""utf-8""" ) as fp: json.dump(lowerCamelCase_ ,lowerCamelCase_ ) def UpperCamelCase__ ( self ,**lowerCamelCase_ ) -> List[str]: return CLIPTokenizer.from_pretrained(self.tmpdirname ,pad_token="""!""" ,**lowerCamelCase_ ) def UpperCamelCase__ ( self ,**lowerCamelCase_ ) -> Optional[Any]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname ,pad_token="""!""" ,**lowerCamelCase_ ) def UpperCamelCase__ ( self ,**lowerCamelCase_ ) -> str: return OwlViTImageProcessor.from_pretrained(self.tmpdirname ,**lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> Union[str, Any]: shutil.rmtree(self.tmpdirname ) def UpperCamelCase__ ( self ) -> List[str]: A = [np.random.randint(2_5_5 ,size=(3, 3_0, 4_0_0) ,dtype=np.uinta )] A = [Image.fromarray(np.moveaxis(lowerCamelCase_ ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase__ ( self ) -> Optional[Any]: A = self.get_tokenizer() A = self.get_rust_tokenizer() A = self.get_image_processor() A = OwlViTProcessor(tokenizer=lowerCamelCase_ ,image_processor=lowerCamelCase_ ) processor_slow.save_pretrained(self.tmpdirname ) A = OwlViTProcessor.from_pretrained(self.tmpdirname ,use_fast=lowerCamelCase_ ) A = OwlViTProcessor(tokenizer=lowerCamelCase_ ,image_processor=lowerCamelCase_ ) processor_fast.save_pretrained(self.tmpdirname ) A = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() ,tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() ,tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() ,tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer ,lowerCamelCase_ ) self.assertIsInstance(processor_fast.tokenizer ,lowerCamelCase_ ) self.assertEqual(processor_slow.image_processor.to_json_string() ,image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() ,image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor ,lowerCamelCase_ ) self.assertIsInstance(processor_fast.image_processor ,lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> Dict: A = OwlViTProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A = self.get_tokenizer(bos_token="""(BOS)""" ,eos_token="""(EOS)""" ) A = self.get_image_processor(do_normalize=lowerCamelCase_ ) A = OwlViTProcessor.from_pretrained( self.tmpdirname ,bos_token="""(BOS)""" ,eos_token="""(EOS)""" ,do_normalize=lowerCamelCase_ ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,lowerCamelCase_ ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> List[str]: A = self.get_image_processor() A = self.get_tokenizer() A = OwlViTProcessor(tokenizer=lowerCamelCase_ ,image_processor=lowerCamelCase_ ) A = self.prepare_image_inputs() A = image_processor(lowerCamelCase_ ,return_tensors="""np""" ) A = processor(images=lowerCamelCase_ ,return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) def UpperCamelCase__ ( self ) -> Tuple: A = self.get_image_processor() A = self.get_tokenizer() A = OwlViTProcessor(tokenizer=lowerCamelCase_ ,image_processor=lowerCamelCase_ ) A = """lower newer""" A = processor(text=lowerCamelCase_ ,return_tensors="""np""" ) A = tokenizer(lowerCamelCase_ ,return_tensors="""np""" ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() ,encoded_processor[key][0].tolist() ) def UpperCamelCase__ ( self ) -> Optional[int]: A = self.get_image_processor() A = self.get_tokenizer() A = OwlViTProcessor(tokenizer=lowerCamelCase_ ,image_processor=lowerCamelCase_ ) A = """lower newer""" A = self.prepare_image_inputs() A = processor(text=lowerCamelCase_ ,images=lowerCamelCase_ ) self.assertListEqual(list(inputs.keys() ) ,["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase_ ): processor() def UpperCamelCase__ ( self ) -> List[Any]: A = """google/owlvit-base-patch32""" A = OwlViTProcessor.from_pretrained(lowerCamelCase_ ) A = ["""cat""", """nasa badge"""] A = processor(text=lowerCamelCase_ ) A = 1_6 self.assertListEqual(list(inputs.keys() ) ,["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape ,(2, seq_length) ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase_ ): processor() def UpperCamelCase__ ( self ) -> Tuple: A = """google/owlvit-base-patch32""" A = OwlViTProcessor.from_pretrained(lowerCamelCase_ ) A = [["""cat""", """nasa badge"""], ["""person"""]] A = processor(text=lowerCamelCase_ ) A = 1_6 A = len(lowerCamelCase_ ) A = max([len(lowerCamelCase_ ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) ,["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape ,(batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase_ ): processor() def UpperCamelCase__ ( self ) -> Union[str, Any]: A = """google/owlvit-base-patch32""" A = OwlViTProcessor.from_pretrained(lowerCamelCase_ ) A = ["""cat""", """nasa badge"""] A = processor(text=lowerCamelCase_ ) A = 1_6 A = inputs["""input_ids"""] A = [ [4_9_4_0_6, 2_3_6_8, 4_9_4_0_7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_9_4_0_6, 6_8_4_1, 1_1_3_0_1, 4_9_4_0_7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) ,["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape ,(2, seq_length) ) self.assertListEqual(list(input_ids[0] ) ,predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) ,predicted_ids[1] ) def UpperCamelCase__ ( self ) -> Dict: A = self.get_image_processor() A = self.get_tokenizer() A = OwlViTProcessor(tokenizer=lowerCamelCase_ ,image_processor=lowerCamelCase_ ) A = self.prepare_image_inputs() A = self.prepare_image_inputs() A = processor(images=lowerCamelCase_ ,query_images=lowerCamelCase_ ) self.assertListEqual(list(inputs.keys() ) ,["""query_pixel_values""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase_ ): processor() def UpperCamelCase__ ( self ) -> str: A = self.get_image_processor() A = self.get_tokenizer() A = OwlViTProcessor(tokenizer=lowerCamelCase_ ,image_processor=lowerCamelCase_ ) A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A = processor.batch_decode(lowerCamelCase_ ) A = tokenizer.batch_decode(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
721
"""simple docstring""" def _A ( _a : int , _a : int ): """simple docstring""" while a != 0: A , A = b % a, a return b def _A ( _a : int , _a : int ): """simple docstring""" if gcd(_a , _a ) != 1: A = f'mod inverse of {a!r} and {m!r} does not exist' raise ValueError(_a ) A , A , A = 1, 0, a A , A , A = 0, 1, m while va != 0: A = ua // va A , A , A , A , A , A = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
255
0
'''simple docstring''' from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake lowercase : Union[str, Any] = numpy.array([0, 0]) lowercase : Optional[Any] = numpy.array([0.5, 0.8_6_6_0_2_5_4]) lowercase : Optional[int] = numpy.array([1, 0]) lowercase : int = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def __a ( A__ , A__ ) -> int: lowerCAmelCase = initial_vectors for _ in range(UpperCAmelCase__ ): lowerCAmelCase = iteration_step(UpperCAmelCase__ ) return vectors def __a ( A__ ) -> Optional[Any]: lowerCAmelCase = [] for i, start_vector in enumerate(vectors[:-1] ): lowerCAmelCase = vectors[i + 1] new_vectors.append(UpperCAmelCase__ ) lowerCAmelCase = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def __a ( A__ , A__ ) -> List[Any]: lowerCAmelCase = numpy.radians(UpperCAmelCase__ ) lowerCAmelCase = numpy.cos(UpperCAmelCase__ ), numpy.sin(UpperCAmelCase__ ) lowerCAmelCase = numpy.array(((c, -s), (s, c)) ) return numpy.dot(UpperCAmelCase__ , UpperCAmelCase__ ) def __a ( A__ ) -> Dict: lowerCAmelCase = plt.gca() axes.set_aspect("equal" ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() lowerCAmelCase = zip(*UpperCAmelCase__ ) plt.plot(UpperCAmelCase__ , UpperCAmelCase__ ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() lowercase : List[Any] = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
649
'''simple docstring''' import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __snake_case ( a__): _lowerCAmelCase = (UnCLIPScheduler,) def UpperCAmelCase_ ( self, **A ): """simple docstring""" lowerCamelCase : Tuple = { 'num_train_timesteps': 1000, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**A ) return config def UpperCAmelCase_ ( self ): """simple docstring""" for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=A, prev_timestep=A ) def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : List[str] = self.scheduler_classes[0] lowerCamelCase : Tuple = self.get_scheduler_config(variance_type='fixed_small_log' ) lowerCamelCase : Dict = scheduler_class(**A ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.00_00e-10 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1e-5 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[int] = self.scheduler_classes[0] lowerCamelCase : Optional[Any] = self.get_scheduler_config(variance_type='learned_range' ) lowerCamelCase : Optional[Any] = scheduler_class(**A ) lowerCamelCase : List[Any] = 0.5 assert scheduler._get_variance(1, predicted_variance=A ) - -10.171_2790 < 1e-5 assert scheduler._get_variance(487, predicted_variance=A ) - -5.799_8052 < 1e-5 assert scheduler._get_variance(999, predicted_variance=A ) - -0.001_0011 < 1e-5 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[int] = self.scheduler_classes[0] lowerCamelCase : Dict = self.get_scheduler_config() lowerCamelCase : Optional[Any] = scheduler_class(**A ) lowerCamelCase : Optional[int] = scheduler.timesteps lowerCamelCase : Optional[Any] = self.dummy_model() lowerCamelCase : int = self.dummy_sample_deter lowerCamelCase : str = torch.manual_seed(0 ) for i, t in enumerate(A ): # 1. predict noise residual lowerCamelCase : List[Any] = model(A, A ) # 2. predict previous mean of sample x_t-1 lowerCamelCase : int = scheduler.step(A, A, A, generator=A ).prev_sample lowerCamelCase : List[Any] = pred_prev_sample lowerCamelCase : Tuple = torch.sum(torch.abs(A ) ) lowerCamelCase : List[str] = torch.mean(torch.abs(A ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1e-2 assert abs(result_mean.item() - 0.328_4743 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[int] = self.scheduler_classes[0] lowerCamelCase : Union[str, Any] = self.get_scheduler_config() lowerCamelCase : Optional[int] = scheduler_class(**A ) scheduler.set_timesteps(25 ) lowerCamelCase : str = scheduler.timesteps lowerCamelCase : Optional[int] = self.dummy_model() lowerCamelCase : Tuple = self.dummy_sample_deter lowerCamelCase : int = torch.manual_seed(0 ) for i, t in enumerate(A ): # 1. predict noise residual lowerCamelCase : Union[str, Any] = model(A, A ) if i + 1 == timesteps.shape[0]: lowerCamelCase : Dict = None else: lowerCamelCase : Optional[int] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 lowerCamelCase : Optional[int] = scheduler.step( A, A, A, prev_timestep=A, generator=A ).prev_sample lowerCamelCase : str = pred_prev_sample lowerCamelCase : Any = torch.sum(torch.abs(A ) ) lowerCamelCase : Union[str, Any] = torch.mean(torch.abs(A ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1e-2 assert abs(result_mean.item() - 0.336_2038 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" pass def UpperCAmelCase_ ( self ): """simple docstring""" pass
320
0
import math def _UpperCAmelCase (UpperCamelCase_ : int ): '''simple docstring''' _lowerCAmelCase : int = [] _lowerCAmelCase : List[Any] = 2 _lowerCAmelCase : Union[str, Any] = int(math.sqrt(UpperCamelCase_ ) ) # Size of every segment _lowerCAmelCase : int = [True] * (end + 1) _lowerCAmelCase : Optional[int] = [] while start <= end: if temp[start] is True: in_prime.append(UpperCamelCase_ ) for i in range(start * start , end + 1 , UpperCamelCase_ ): _lowerCAmelCase : Optional[Any] = False start += 1 prime += in_prime _lowerCAmelCase : str = end + 1 _lowerCAmelCase : Union[str, Any] = min(2 * end , UpperCamelCase_ ) while low <= n: _lowerCAmelCase : Optional[Any] = [True] * (high - low + 1) for each in in_prime: _lowerCAmelCase : str = math.floor(low / each ) * each if t < low: t += each for j in range(UpperCamelCase_ , high + 1 , UpperCamelCase_ ): _lowerCAmelCase : Union[str, Any] = False for j in range(len(UpperCamelCase_ ) ): if temp[j] is True: prime.append(j + low ) _lowerCAmelCase : int = high + 1 _lowerCAmelCase : Union[str, Any] = min(high + end , UpperCamelCase_ ) return prime print(sieve(1_0**6))
196
import sys _lowerCamelCase : Optional[Any] = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def _UpperCAmelCase (UpperCamelCase_ : str = N ): '''simple docstring''' _lowerCAmelCase : List[str] = -sys.maxsize - 1 for i in range(len(UpperCamelCase_ ) - 12 ): _lowerCAmelCase : List[str] = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: _lowerCAmelCase : Any = product return largest_product if __name__ == "__main__": print(F'''{solution() = }''')
196
1
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 SCREAMING_SNAKE_CASE_ = { 'return_dict': False, 'output_hidden_states': True, 'output_attentions': True, 'torchscript': True, 'torch_dtype': 'float16', 'use_bfloat16': True, 'tf_legacy_loss': True, 'pruned_heads': {'a': 1}, 'tie_word_embeddings': False, 'is_decoder': True, 'cross_attention_hidden_size': 128, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 50, 'min_length': 3, 'do_sample': True, 'early_stopping': True, 'num_beams': 3, 'num_beam_groups': 3, 'diversity_penalty': 0.5, 'temperature': 2.0, 'top_k': 10, 'top_p': 0.7, 'typical_p': 0.2, 'repetition_penalty': 0.8, 'length_penalty': 0.8, 'no_repeat_ngram_size': 5, 'encoder_no_repeat_ngram_size': 5, 'bad_words_ids': [1, 2, 3], 'num_return_sequences': 3, 'chunk_size_feed_forward': 5, 'output_scores': True, 'return_dict_in_generate': True, 'forced_bos_token_id': 2, 'forced_eos_token_id': 3, 'remove_invalid_values': True, 'architectures': ['BertModel'], 'finetuning_task': 'translation', 'id2label': {0: 'label'}, 'label2id': {'label': '0'}, 'tokenizer_class': 'BertTokenizerFast', 'prefix': 'prefix', 'bos_token_id': 6, 'pad_token_id': 7, 'eos_token_id': 8, 'sep_token_id': 9, 'decoder_start_token_id': 10, 'exponential_decay_length_penalty': (5, 1.01), 'suppress_tokens': [0, 1], 'begin_suppress_tokens': 2, 'task_specific_params': {'translation': 'some_params'}, 'problem_type': 'regression', } @is_staging_test class snake_case_ ( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase__ ( cls) -> Dict: UpperCamelCase = TOKEN HfFolder.save_token(lowerCamelCase_) @classmethod def UpperCAmelCase__ ( cls) -> Union[str, Any]: try: delete_repo(token=cls._token , repo_id='''test-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-config-org''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-config''') except HTTPError: pass def UpperCAmelCase__ ( self) -> int: UpperCamelCase = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7) config.push_to_hub('''test-config''' , use_auth_token=self._token) UpperCamelCase = BertConfig.from_pretrained(F'{USER}/test-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase_ , repo_id='''test-config''' , push_to_hub=lowerCamelCase_ , use_auth_token=self._token) UpperCamelCase = BertConfig.from_pretrained(F'{USER}/test-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_)) def UpperCAmelCase__ ( self) -> List[str]: UpperCamelCase = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7) config.push_to_hub('''valid_org/test-config-org''' , use_auth_token=self._token) UpperCamelCase = BertConfig.from_pretrained('''valid_org/test-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowerCamelCase_ , repo_id='''valid_org/test-config-org''' , push_to_hub=lowerCamelCase_ , use_auth_token=self._token) UpperCamelCase = BertConfig.from_pretrained('''valid_org/test-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_)) def UpperCAmelCase__ ( self) -> Tuple: CustomConfig.register_for_auto_class() UpperCamelCase = CustomConfig(attribute=4_2) config.push_to_hub('''test-dynamic-config''' , use_auth_token=self._token) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'''AutoConfig''': '''custom_configuration.CustomConfig'''}) UpperCamelCase = AutoConfig.from_pretrained(F'{USER}/test-dynamic-config' , trust_remote_code=lowerCamelCase_) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , '''CustomConfig''') self.assertEqual(new_config.attribute , 4_2) class snake_case_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self) -> Dict: UpperCamelCase = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated UpperCamelCase = c.n_embd + 1 # int UpperCamelCase = c.resid_pdrop + 1.0 # float UpperCamelCase = not c.scale_attn_weights # bool UpperCamelCase = c.summary_type + '''foo''' # str c.update_from_string( F'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}') self.assertEqual(lowerCamelCase_ , c.n_embd , '''mismatch for key: n_embd''') self.assertEqual(lowerCamelCase_ , c.resid_pdrop , '''mismatch for key: resid_pdrop''') self.assertEqual(lowerCamelCase_ , c.scale_attn_weights , '''mismatch for key: scale_attn_weights''') self.assertEqual(lowerCamelCase_ , c.summary_type , '''mismatch for key: summary_type''') def UpperCAmelCase__ ( self) -> str: UpperCamelCase = PretrainedConfig() UpperCamelCase = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( lowerCamelCase_ , ['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version''']) UpperCamelCase = [key for key, value in config_common_kwargs.items() if value == getattr(lowerCamelCase_ , lowerCamelCase_)] if len(lowerCamelCase_) > 0: raise ValueError( '''The following keys are set with the default values in''' ''' `test_configuration_common.config_common_kwargs` pick another value for them:''' F' {", ".join(lowerCamelCase_)}.') def UpperCAmelCase__ ( self) -> str: with self.assertRaises(lowerCamelCase_): # config is in subfolder, the following should not work without specifying the subfolder UpperCamelCase = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''') UpperCamelCase = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' , subfolder='''bert''') self.assertIsNotNone(lowerCamelCase_) def UpperCAmelCase__ ( self) -> Union[str, Any]: # A mock response for an HTTP head request to emulate server down UpperCamelCase = mock.Mock() UpperCamelCase = 5_0_0 UpperCamelCase = {} UpperCamelCase = HTTPError UpperCamelCase = {} # Download this model to make sure it's in the cache. UpperCamelCase = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''') # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=lowerCamelCase_) as mock_head: UpperCamelCase = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''') # This check we did call the fake head request mock_head.assert_called() def UpperCAmelCase__ ( self) -> Optional[int]: # This test is for deprecated behavior and can be removed in v5 UpperCamelCase = BertConfig.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json''') def UpperCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase = AutoConfig.from_pretrained('''bert-base-cased''') UpperCamelCase = ['''config.4.0.0.json'''] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(lowerCamelCase_) UpperCamelCase = 2 json.dump(configuration.to_dict() , open(os.path.join(lowerCamelCase_ , '''config.4.0.0.json''') , '''w''')) # This should pick the new configuration file as the version of Transformers is > 4.0.0 UpperCamelCase = AutoConfig.from_pretrained(lowerCamelCase_) self.assertEqual(new_configuration.hidden_size , 2) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 UpperCamelCase = ['''config.42.0.0.json'''] UpperCamelCase = 7_6_8 configuration.save_pretrained(lowerCamelCase_) shutil.move(os.path.join(lowerCamelCase_ , '''config.4.0.0.json''') , os.path.join(lowerCamelCase_ , '''config.42.0.0.json''')) UpperCamelCase = AutoConfig.from_pretrained(lowerCamelCase_) self.assertEqual(new_configuration.hidden_size , 7_6_8) def UpperCAmelCase__ ( self) -> Optional[Any]: # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. UpperCamelCase = '''hf-internal-testing/test-two-configs''' import transformers as new_transformers UpperCamelCase = '''v4.0.0''' UpperCamelCase , UpperCamelCase = new_transformers.models.auto.AutoConfig.from_pretrained( lowerCamelCase_ , return_unused_kwargs=lowerCamelCase_) self.assertEqual(new_configuration.hidden_size , 2) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(lowerCamelCase_ , {}) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers UpperCamelCase = '''v3.0.0''' UpperCamelCase = old_transformers.models.auto.AutoConfig.from_pretrained(lowerCamelCase_) self.assertEqual(old_configuration.hidden_size , 7_6_8)
34
'''simple docstring''' import math lowerCamelCase :int = 1_0 lowerCamelCase :List[Any] = 7 lowerCamelCase :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def a ( lowerCamelCase__ = 20 ): '''simple docstring''' A_ : Dict = math.comb(lowerCamelCase__ , lowerCamelCase__ ) A_ : Optional[Any] = math.comb(NUM_BALLS - BALLS_PER_COLOUR , lowerCamelCase__ ) A_ : List[str] = NUM_COLOURS * (1 - missing_colour / total) return f'{result:.9f}' if __name__ == "__main__": print(solution(2_0))
667
0
'''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = [ 'VerificationMode', 'Version', 'disable_progress_bar', 'enable_progress_bar', 'is_progress_bar_enabled', 'experimental', ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
708
'''simple docstring''' import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): '''simple docstring''' __a : Dict = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) __a : Optional[int] = Vector() def __lowerCamelCase ( self ): '''simple docstring''' __a : Any = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(__UpperCamelCase ) , """(0,0,0,0,0,1)""" ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Tuple = Vector([1, 2, 3, 4] ) self.assertEqual(len(__UpperCamelCase ) , 4 ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Optional[Any] = Vector([1, 2] ) __a : List[str] = Vector([1, 2, 3, 4, 5] ) __a : Optional[int] = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) __a : Dict = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.2_3_6 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.4_1_6 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.6_1_6 , 3 ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Dict = Vector([1, 2, 3] ) __a : Union[str, Any] = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def __lowerCamelCase ( self ): '''simple docstring''' __a : List[str] = Vector([1, 2, 3] ) __a : Any = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Tuple = Vector([1, 2, 3] ) __a : Optional[Any] = Vector([2, -1, 4] ) # for test of dot product __a : Union[str, Any] = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , """(3.0,6.0,9.0)""" ) self.assertEqual((a * b) , 0 ) def __lowerCamelCase ( self ): '''simple docstring''' self.assertEqual(str(zero_vector(10 ) ).count("""0""" ) , 10 ) def __lowerCamelCase ( self ): '''simple docstring''' self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , """(0,1,0)""" ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Dict = Vector([1, 2, 3] ) __a : Optional[int] = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , __UpperCamelCase , __UpperCamelCase ) ) , """(3,4,7)""" ) def __lowerCamelCase ( self ): '''simple docstring''' __a : int = Vector([1, 0, 0, 0, 0, 0] ) __a : Any = x.copy() self.assertEqual(str(__UpperCamelCase ) , str(__UpperCamelCase ) ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Union[str, Any] = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(__UpperCamelCase ) , """(0,1,0)""" ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual("""|1,2,3|\n|2,4,5|\n|6,7,8|\n""" , str(__UpperCamelCase ) ) def __lowerCamelCase ( self ): '''simple docstring''' __a : List[Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __a : List[Any] = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(__UpperCamelCase , __UpperCamelCase ) ) def __lowerCamelCase ( self ): '''simple docstring''' __a : List[Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __a : Any = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(__UpperCamelCase , __UpperCamelCase ) ) def __lowerCamelCase ( self ): '''simple docstring''' __a : List[Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Any = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) __a : List[Any] = Vector([1, 2, 3] ) self.assertEqual("""(14,32,50)""" , str(a * x ) ) self.assertEqual("""|2,4,6|\n|8,10,12|\n|14,16,18|\n""" , str(a * 2 ) ) def __lowerCamelCase ( self ): '''simple docstring''' __a : List[str] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual("""|1,2,5|\n|2,4,5|\n|6,7,8|\n""" , str(__UpperCamelCase ) ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Tuple = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.0_1 ) def __lowerCamelCase ( self ): '''simple docstring''' __a : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __a : Union[str, Any] = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("""|2,4,10|\n|4,8,10|\n|12,14,18|\n""" , str(a + b ) ) def __lowerCamelCase ( self ): '''simple docstring''' __a : List[Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __a : List[str] = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("""|0,0,-4|\n|0,0,0|\n|0,0,-2|\n""" , str(a - b ) ) def __lowerCamelCase ( self ): '''simple docstring''' self.assertEqual( """|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n""" , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
697
0
def __snake_case ( _UpperCamelCase = 1_00 ) -> List[Any]: _a = n * (n + 1) * (2 * n + 1) / 6 _a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'''{solution() = }''')
487
from graphs.minimum_spanning_tree_kruskal import kruskal def lowerCamelCase_ ( ): '''simple docstring''' UpperCamelCase__ = 9 UpperCamelCase__ = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] UpperCamelCase__ = kruskal(UpperCamelCase__, UpperCamelCase__ ) UpperCamelCase__ = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(UpperCamelCase__ ) == sorted(UpperCamelCase__ )
240
0
import argparse import os import re import packaging.version __A = "examples/" __A = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } __A = { "init": "src/transformers/__init__.py", "setup": "setup.py", } __A = "README.md" def lowerCamelCase_ ( UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] ) -> Optional[Any]: """simple docstring""" with open(UpperCamelCase__ , 'r' , encoding='utf-8' , newline='\n' ) as f: __lowerCamelCase = f.read() __lowerCamelCase , __lowerCamelCase = REPLACE_PATTERNS[pattern] __lowerCamelCase = replace.replace('VERSION' , UpperCamelCase__ ) __lowerCamelCase = re_pattern.sub(UpperCamelCase__ , UpperCamelCase__ ) with open(UpperCamelCase__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(UpperCamelCase__ ) def lowerCamelCase_ ( UpperCamelCase__ : Tuple ) -> Any: """simple docstring""" for folder, directories, fnames in os.walk(UpperCamelCase__ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects' ) if "legacy" in directories: directories.remove('legacy' ) for fname in fnames: if fname.endswith('.py' ): update_version_in_file(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ , pattern='examples' ) def lowerCamelCase_ ( UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict=False ) -> Tuple: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not patch: update_version_in_examples(UpperCamelCase__ ) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" __lowerCamelCase = '🤗 Transformers currently provides the following architectures' __lowerCamelCase = '1. Want to contribute a new model?' with open(UpperCamelCase__ , 'r' , encoding='utf-8' , newline='\n' ) as f: __lowerCamelCase = f.readlines() # Find the start of the list. __lowerCamelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCamelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('1.' ): __lowerCamelCase = lines[index].replace( 'https://huggingface.co/docs/transformers/main/model_doc' , 'https://huggingface.co/docs/transformers/model_doc' , ) index += 1 with open(UpperCamelCase__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(UpperCamelCase__ ) def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" with open(REPLACE_FILES['init'] , 'r' ) as f: __lowerCamelCase = f.read() __lowerCamelCase = REPLACE_PATTERNS['init'][0].search(UpperCamelCase__ ).groups()[0] return packaging.version.parse(UpperCamelCase__ ) def lowerCamelCase_ ( UpperCamelCase__ : Optional[int]=False ) -> str: """simple docstring""" __lowerCamelCase = get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!' ) if default_version.is_devrelease: __lowerCamelCase = default_version.base_version elif patch: __lowerCamelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __lowerCamelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __lowerCamelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(UpperCamelCase__ ) == 0: __lowerCamelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(UpperCamelCase__ , patch=UpperCamelCase__ ) if not patch: print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() def lowerCamelCase_ ( ) -> Optional[int]: """simple docstring""" __lowerCamelCase = get_version() __lowerCamelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __lowerCamelCase = current_version.base_version # Check with the user we got that right. __lowerCamelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(UpperCamelCase__ ) == 0: __lowerCamelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(UpperCamelCase__ ) print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") __A = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
718
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def lowerCamelCase_ ( UpperCamelCase__ : Optional[Any] ) -> 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 def lowerCamelCase_ ( UpperCamelCase__ : str ) -> Dict: """simple docstring""" for char in word: __lowerCamelCase = ord(UpperCamelCase__ ) if not _is_chinese_char(UpperCamelCase__ ): return 0 return 1 def lowerCamelCase_ ( UpperCamelCase__ : List[str] ) -> Optional[Any]: """simple docstring""" __lowerCamelCase = set() for token in tokens: __lowerCamelCase = len(UpperCamelCase__ ) > 1 and is_chinese(UpperCamelCase__ ) if chinese_word: word_set.add(UpperCamelCase__ ) __lowerCamelCase = list(UpperCamelCase__ ) return word_list def lowerCamelCase_ ( UpperCamelCase__ : List[str] , UpperCamelCase__ : set() ) -> int: """simple docstring""" if not chinese_word_set: return bert_tokens __lowerCamelCase = max([len(UpperCamelCase__ ) for w in chinese_word_set] ) __lowerCamelCase = bert_tokens __lowerCamelCase , __lowerCamelCase = 0, len(UpperCamelCase__ ) while start < end: __lowerCamelCase = True if is_chinese(bert_word[start] ): __lowerCamelCase = min(end - start , UpperCamelCase__ ) for i in range(UpperCamelCase__ , 1 , -1 ): __lowerCamelCase = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): __lowerCamelCase = '##' + bert_word[j] __lowerCamelCase = start + i __lowerCamelCase = False break if single_word: start += 1 return bert_word def lowerCamelCase_ ( UpperCamelCase__ : List[str] , UpperCamelCase__ : LTP , UpperCamelCase__ : BertTokenizer ) -> List[str]: """simple docstring""" __lowerCamelCase = [] for i in range(0 , len(UpperCamelCase__ ) , 100 ): __lowerCamelCase = ltp_tokenizer.seg(lines[i : i + 100] )[0] __lowerCamelCase = [get_chinese_word(UpperCamelCase__ ) for r in res] ltp_res.extend(UpperCamelCase__ ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) __lowerCamelCase = [] for i in range(0 , len(UpperCamelCase__ ) , 100 ): __lowerCamelCase = bert_tokenizer(lines[i : i + 100] , add_special_tokens=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=512 ) bert_res.extend(res['input_ids'] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) __lowerCamelCase = [] for input_ids, chinese_word in zip(UpperCamelCase__ , UpperCamelCase__ ): __lowerCamelCase = [] for id in input_ids: __lowerCamelCase = bert_tokenizer._convert_id_to_token(UpperCamelCase__ ) input_tokens.append(UpperCamelCase__ ) __lowerCamelCase = add_sub_symbol(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(UpperCamelCase__ ): if token[:2] == "##": __lowerCamelCase = token[2:] # save chinese tokens' pos if len(UpperCamelCase__ ) == 1 and _is_chinese_char(ord(UpperCamelCase__ ) ): ref_id.append(UpperCamelCase__ ) ref_ids.append(UpperCamelCase__ ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) return ref_ids def lowerCamelCase_ ( UpperCamelCase__ : Optional[int] ) -> int: """simple docstring""" with open(args.file_name , 'r' , encoding='utf-8' ) as f: __lowerCamelCase = f.readlines() __lowerCamelCase = [line.strip() for line in data if len(UpperCamelCase__ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' __lowerCamelCase = LTP(args.ltp ) # faster in GPU device __lowerCamelCase = BertTokenizer.from_pretrained(args.bert ) __lowerCamelCase = prepare_ref(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: __lowerCamelCase = [json.dumps(UpperCamelCase__ ) + '\n' for ref in ref_ids] f.writelines(UpperCamelCase__ ) if __name__ == "__main__": __A = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path" ) parser.add_argument("--bert", type=str, default="./resources/robert", help="resources for Bert tokenizer") parser.add_argument("--save_path", type=str, default="./resources/ref.txt", help="path to save res") __A = parser.parse_args() main(args)
167
0
'''simple docstring''' import cmath import math def SCREAMING_SNAKE_CASE ( lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): lowercase = math.radians(lowercase_ ) lowercase = math.radians(lowercase_ ) # Convert voltage and current to rectangular form lowercase = cmath.rect(lowercase_ , lowercase_ ) lowercase = cmath.rect(lowercase_ , lowercase_ ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
588
'''simple docstring''' import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __UpperCamelCase (unittest.TestCase ): def _a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Dict: '''simple docstring''' self.assertEqual(len(_lowerCAmelCase ) , len(_lowerCAmelCase ) ) for a, b in zip(_lowerCAmelCase , _lowerCAmelCase ): self.assertAlmostEqual(_lowerCAmelCase , _lowerCAmelCase , delta=_lowerCAmelCase ) def _a ( self ) -> Optional[int]: '''simple docstring''' lowercase = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(_lowerCAmelCase ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def _a ( self ) -> int: '''simple docstring''' lowercase = None ops.enable_eager_execution_internal() lowercase = tf.config.list_physical_devices("""CPU""" ) if len(_lowerCAmelCase ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) lowercase = tf.config.list_logical_devices(device_type="""CPU""" ) lowercase = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): lowercase = GradientAccumulator() lowercase = tf.Variable([4.0, 3.0] ) lowercase , lowercase = create_optimizer(5E-5 , 10 , 5 ) lowercase = tf.Variable([0.0, 0.0] , trainable=_lowerCAmelCase ) def accumulate_on_replica(_lowerCAmelCase ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(_lowerCAmelCase , _lowerCAmelCase ): with strategy.scope(): lowercase = strategy.experimental_local_results(_lowerCAmelCase ) local_variables[0].assign(_lowerCAmelCase ) local_variables[1].assign(_lowerCAmelCase ) strategy.run(_lowerCAmelCase , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(_lowerCAmelCase ) def _check_local_values(_lowerCAmelCase , _lowerCAmelCase ): lowercase = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , _lowerCAmelCase , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , _lowerCAmelCase , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
588
1
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __lowerCamelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = torch.load(_lowerCAmelCase , map_location="cpu" ) if "model" in sd.keys(): _UpperCAmelCase = torch.load(_lowerCAmelCase , map_location="cpu" )["model"] # pop unnecessary weights _UpperCAmelCase = [ "decoder.version", "decoder.output_projection.weight", ] for key in keys_to_delete: if key in sd: sd.pop(_lowerCAmelCase ) _UpperCAmelCase = { "decoder.project_in_dim.weight": "decoder.project_in.weight", "decoder.project_out_dim.weight": "decoder.project_out.weight", "decoder.layer_norm.weight": "decoder.final_layer_norm.weight", "decoder.layer_norm.bias": "decoder.final_layer_norm.bias", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: _UpperCAmelCase = sd.pop(_lowerCAmelCase ) _UpperCAmelCase = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: _UpperCAmelCase = sd[key] # We split QKV in separate Q,K,V _UpperCAmelCase = key.replace(".qkv_proj." , ".q_proj." ) _UpperCAmelCase = key.replace(".qkv_proj." , ".k_proj." ) _UpperCAmelCase = key.replace(".qkv_proj." , ".v_proj." ) _UpperCAmelCase = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 _UpperCAmelCase = torch.split(_lowerCAmelCase , depth // 3 , dim=0 ) _UpperCAmelCase = q _UpperCAmelCase = k _UpperCAmelCase = v del sd[key] return sd @torch.no_grad() def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = load_checkpoint(_lowerCAmelCase ) if config is not None: _UpperCAmelCase = OPTConfig.from_pretrained(_lowerCAmelCase ) else: _UpperCAmelCase = OPTConfig() _UpperCAmelCase = OPTModel(_lowerCAmelCase ).half().eval() model.load_state_dict(_lowerCAmelCase ) # Check results Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) model.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--fairseq_path', type=str, help=( 'path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:' ' https://huggingface.co/models?other=opt_metasq' ), ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--hf_config', default=None, type=str, help='Define HF config.') __lowerCamelCase = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
711
import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.17.0.dev0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt') __lowerCamelCase = logging.getLogger(__name__) @dataclass class _UpperCamelCase: __A: Optional[str] = field( default="""tab_fact""" , metadata={"""help""": """The name of the dataset to use (via the datasets library)."""} ) __A: Optional[str] = field( default="""tab_fact""" , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} , ) __A: int = field( default=10_24 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __A: bool = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} ) __A: bool = field( default=SCREAMING_SNAKE_CASE , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) __A: Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) __A: Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) __A: Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of prediction examples to this """ """value if set.""" ) } , ) __A: Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """A csv or a json file containing the training data."""} ) __A: Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """A csv or a json file containing the validation data."""} ) __A: Optional[str] = field(default=SCREAMING_SNAKE_CASE , metadata={"""help""": """A csv or a json file containing the test data."""} ) def a__ ( self : List[str] ): if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError("Need either a GLUE task, a training/validation file or a dataset name." ) else: _UpperCAmelCase : Union[str, Any] = self.train_file.split("." )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." _UpperCAmelCase : Optional[Any] = self.validation_file.split("." )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class _UpperCamelCase: __A: str = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __A: Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) __A: Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) __A: Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) __A: bool = field( default=SCREAMING_SNAKE_CASE , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) __A: str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) __A: bool = field( default=SCREAMING_SNAKE_CASE , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) def lowerCAmelCase_ ( ) -> List[Any]: """simple docstring""" _UpperCAmelCase : str = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase : Any = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) _UpperCAmelCase : List[Any] = training_args.get_process_log_level() logger.setLevel(_SCREAMING_SNAKE_CASE ) datasets.utils.logging.set_verbosity(_SCREAMING_SNAKE_CASE ) transformers.utils.logging.set_verbosity(_SCREAMING_SNAKE_CASE ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. _UpperCAmelCase : List[str] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _UpperCAmelCase : Any = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. _UpperCAmelCase : List[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. _UpperCAmelCase : Any = {"train": data_args.train_file, "validation": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: _UpperCAmelCase : Optional[int] = data_args.train_file.split("." )[-1] _UpperCAmelCase : Optional[Any] = data_args.test_file.split("." )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." _UpperCAmelCase : Tuple = data_args.test_file else: raise ValueError("Need either a GLUE task or a test file for `do_predict`." ) for key in data_files.keys(): logger.info(F"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith(".csv" ): # Loading a dataset from local csv files _UpperCAmelCase : Tuple = load_dataset("csv" , data_files=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files _UpperCAmelCase : List[str] = load_dataset("json" , data_files=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels _UpperCAmelCase : Tuple = raw_datasets["train"].features["label"].names _UpperCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCAmelCase : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer _UpperCAmelCase : List[Any] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase : List[Any] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: _UpperCAmelCase : Optional[int] = "max_length" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch _UpperCAmelCase : Union[str, Any] = False # Some models have set the order of the labels to use, so let's make sure we do use it. _UpperCAmelCase : Tuple = {"Refused": 0, "Entailed": 1} _UpperCAmelCase : Union[str, Any] = {0: "Refused", 1: "Entailed"} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) _UpperCAmelCase : Dict = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(_SCREAMING_SNAKE_CASE ): # Tokenize the texts def _convert_table_text_to_pandas(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = [_table_row.split("#" ) for _table_row in _table_text.strip("\n" ).split("\n" )] _UpperCAmelCase : Dict = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd _UpperCAmelCase : List[str] = examples["statement"] _UpperCAmelCase : int = list(map(_convert_table_text_to_pandas , examples["table_text"] ) ) _UpperCAmelCase : Dict = tokenizer(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : List[str] = examples["label"] return result with training_args.main_process_first(desc="dataset map pre-processing" ): _UpperCAmelCase : Any = raw_datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , load_from_cache_file=not data_args.overwrite_cache , desc="Running tokenizer on dataset" , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) _UpperCAmelCase : Tuple = raw_datasets["train"] if data_args.max_train_samples is not None: _UpperCAmelCase : Any = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) _UpperCAmelCase : Tuple = raw_datasets["validation"] if data_args.max_eval_samples is not None: _UpperCAmelCase : Optional[int] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError("--do_predict requires a test dataset" ) _UpperCAmelCase : List[str] = raw_datasets["test"] if data_args.max_predict_samples is not None: _UpperCAmelCase : str = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(_SCREAMING_SNAKE_CASE ) ) , 3 ): logger.info(F"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = p.predictions[0] if isinstance(p.predictions , _SCREAMING_SNAKE_CASE ) else p.predictions _UpperCAmelCase : Tuple = np.argmax(_SCREAMING_SNAKE_CASE , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: _UpperCAmelCase : List[str] = default_data_collator elif training_args.fpaa: _UpperCAmelCase : Dict = DataCollatorWithPadding(_SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) else: _UpperCAmelCase : List[Any] = None # Initialize our Trainer _UpperCAmelCase : Union[str, Any] = Trainer( model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: _UpperCAmelCase : Optional[Any] = None if training_args.resume_from_checkpoint is not None: _UpperCAmelCase : str = training_args.resume_from_checkpoint elif last_checkpoint is not None: _UpperCAmelCase : int = last_checkpoint _UpperCAmelCase : List[Any] = trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : Union[str, Any] = train_result.metrics _UpperCAmelCase : List[Any] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase : Tuple = min(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("train" , _SCREAMING_SNAKE_CASE ) trainer.save_metrics("train" , _SCREAMING_SNAKE_CASE ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) _UpperCAmelCase : List[str] = trainer.evaluate(eval_dataset=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : Dict = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : Any = min(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ) trainer.log_metrics("eval" , _SCREAMING_SNAKE_CASE ) trainer.save_metrics("eval" , _SCREAMING_SNAKE_CASE ) if training_args.do_predict: logger.info("*** Predict ***" ) # Removing the `label` columns because it contains -1 and Trainer won't like that. _UpperCAmelCase : int = predict_dataset.remove_columns("label" ) _UpperCAmelCase : Union[str, Any] = trainer.predict(_SCREAMING_SNAKE_CASE , metric_key_prefix="predict" ).predictions _UpperCAmelCase : List[str] = np.argmax(_SCREAMING_SNAKE_CASE , axis=1 ) _UpperCAmelCase : Union[str, Any] = os.path.join(training_args.output_dir , "predict_results_tabfact.txt" ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , "w" ) as writer: logger.info("***** Predict Results *****" ) writer.write("index\tprediction\n" ) for index, item in enumerate(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = label_list[item] writer.write(F"""{index}\t{item}\n""" ) _UpperCAmelCase : Tuple = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"} if training_args.push_to_hub: trainer.push_to_hub(**_SCREAMING_SNAKE_CASE ) else: trainer.create_model_card(**_SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" main() if __name__ == "__main__": main()
328
0
def __a ( lowerCAmelCase_ : str ) -> Dict: '''simple docstring''' if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) UpperCAmelCase_= sum(lowerCamelCase_ ) / len(lowerCamelCase_ ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(lowerCamelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
593
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A : Optional[Any] = { """configuration_megatron_bert""": ["""MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MegatronBertConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Any = [ """MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MegatronBertForCausalLM""", """MegatronBertForMaskedLM""", """MegatronBertForMultipleChoice""", """MegatronBertForNextSentencePrediction""", """MegatronBertForPreTraining""", """MegatronBertForQuestionAnswering""", """MegatronBertForSequenceClassification""", """MegatronBertForTokenClassification""", """MegatronBertModel""", """MegatronBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys A : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
349
0
'''simple docstring''' import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _UpperCAmelCase ( a : Tuple , a : Union[str, Any]=1_0 ) -> List[str]: """simple docstring""" lowercase_ : int = [] for _ in range(a ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _UpperCAmelCase ( a : List[Any] , a : Union[str, Any]=1_0 ) -> Optional[int]: """simple docstring""" lowercase_ : Optional[Any] = [] for step in range(a ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Dict = os.path.join(a , 'schedule.bin' ) torch.save(scheduler.state_dict() , a ) lowercase_ : Tuple = torch.load(a ) scheduler.load_state_dict(a ) return lrs @require_torch class __magic_name__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase__ ( self , _lowercase , _lowercase , _lowercase ) -> Optional[Any]: self.assertEqual(len(_lowercase ) , len(_lowercase ) ) for a, b in zip(_lowercase , _lowercase ): self.assertAlmostEqual(_lowercase , _lowercase , delta=_lowercase ) def lowerCamelCase__ ( self ) -> int: lowercase_ : int = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_lowercase ) lowercase_ : List[Any] = torch.tensor([0.4, 0.2, -0.5] ) lowercase_ : List[Any] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowercase_ : int = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(100 ): lowercase_ : Optional[Any] = criterion(_lowercase , _lowercase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCamelCase__ ( self ) -> Dict: lowercase_ : List[Any] = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_lowercase ) lowercase_ : Optional[Any] = torch.tensor([0.4, 0.2, -0.5] ) lowercase_ : Dict = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowercase_ : Optional[Any] = Adafactor( params=[w] , lr=1E-2 , eps=(1E-3_0, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_lowercase , weight_decay=0.0 , relative_step=_lowercase , scale_parameter=_lowercase , warmup_init=_lowercase , ) for _ in range(1000 ): lowercase_ : str = criterion(_lowercase , _lowercase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class __magic_name__ ( unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = nn.Linear(5_0, 5_0 ) if is_torch_available() else None SCREAMING_SNAKE_CASE_ : Optional[Any] = AdamW(m.parameters(), lr=10.0 ) if is_torch_available() else None SCREAMING_SNAKE_CASE_ : Optional[Any] = 1_0 def lowerCamelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase=None ) -> Union[str, Any]: self.assertEqual(len(_lowercase ) , len(_lowercase ) ) for a, b in zip(_lowercase , _lowercase ): self.assertAlmostEqual(_lowercase , _lowercase , delta=_lowercase , msg=_lowercase ) def lowerCamelCase__ ( self ) -> int: lowercase_ : int = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) lowercase_ : Dict = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1E-7}, [0.0, 5.0, 10.0, 7.6_56, 5.6_25, 3.9_06, 2.5, 1.4_06, 0.6_25, 0.1_56], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.1_65, 7.0_71, 6.3_25, 5.7_74, 5.3_45, 5.0, 4.7_14], ), } for scheduler_func, data in scheds.items(): lowercase_ : Union[str, Any] = data lowercase_ : Tuple = scheduler_func(self.optimizer , **_lowercase ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) lowercase_ : Union[str, Any] = unwrap_schedule(_lowercase , self.num_steps ) self.assertListAlmostEqual( _lowercase , _lowercase , tol=1E-2 , msg=f"failed for {scheduler_func} in normal scheduler" , ) lowercase_ : int = scheduler_func(self.optimizer , **_lowercase ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_lowercase ) # wrap to test picklability of the schedule lowercase_ : List[Any] = unwrap_and_save_reload_schedule(_lowercase , self.num_steps ) self.assertListEqual(_lowercase , _lowercase , msg=f"failed for {scheduler_func} in save and reload" ) class __magic_name__ : """simple docstring""" def __init__( self , _lowercase ) -> int: lowercase_ : Dict = fn def __call__( self , *_lowercase , **_lowercase ) -> List[str]: return self.fn(*_lowercase , **_lowercase ) @classmethod def lowerCamelCase__ ( self , _lowercase ) -> Union[str, Any]: lowercase_ : Union[str, Any] = list(map(self , scheduler.lr_lambdas ) )
718
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A: Dict = logging.get_logger(__name__) A: Optional[Any] = { "google/vit-base-patch16-224": "https://huggingface.co/vit-base-patch16-224/resolve/main/config.json", # See all ViT models at https://huggingface.co/models?filter=vit } class __magic_name__ ( UpperCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = 'vit' def __init__( self , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1E-1_2 , _lowercase=224 , _lowercase=16 , _lowercase=3 , _lowercase=True , _lowercase=16 , **_lowercase , ) -> List[str]: super().__init__(**_lowercase ) lowercase_ : Optional[int] = hidden_size lowercase_ : str = num_hidden_layers lowercase_ : str = num_attention_heads lowercase_ : int = intermediate_size lowercase_ : List[Any] = hidden_act lowercase_ : Any = hidden_dropout_prob lowercase_ : List[str] = attention_probs_dropout_prob lowercase_ : str = initializer_range lowercase_ : List[str] = layer_norm_eps lowercase_ : Any = image_size lowercase_ : Tuple = patch_size lowercase_ : Optional[Any] = num_channels lowercase_ : str = qkv_bias lowercase_ : List[str] = encoder_stride class __magic_name__ ( UpperCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = version.parse('1.11' ) @property def lowerCamelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def lowerCamelCase__ ( self ) -> float: return 1E-4
7
0