code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class snake_case : def __init__( self : int , a_ : int , a_ : Union[str, Any]=13 , a_ : List[str]=7 , a_ : int=True , a_ : List[str]=True , a_ : List[Any]=False , a_ : Optional[Any]=True , a_ : Optional[Any]=99 , a_ : List[Any]=64 , a_ : Optional[int]=5 , a_ : str=4 , a_ : List[Any]=64 , a_ : int="gelu" , a_ : List[str]=0.1 , a_ : List[Any]=0.1 , a_ : Optional[Any]=512 , a_ : Union[str, Any]=16 , a_ : int=2 , a_ : Dict=0.02 , a_ : Optional[Any]=3 , a_ : List[Any]=4 , a_ : Optional[int]=None , )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = parent SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : int = use_input_mask SCREAMING_SNAKE_CASE__ : str = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_choices SCREAMING_SNAKE_CASE__ : List[Any] = scope def __lowercase( self : Dict )-> List[str]: """simple docstring""" return MPNetConfig.from_pretrained('microsoft/mpnet-base' ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" return MPNetConfig( 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 , initializer_range=self.initializer_range , ) def __lowercase( self : int , a_ : Any , a_ : Dict , a_ : Dict , a_ : Optional[Any] , a_ : List[Any] , a_ : Optional[int] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = MPNetModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowercase( self : Tuple , a_ : int , a_ : Union[str, Any] , a_ : List[str] , a_ : Optional[Any] , a_ : Tuple , a_ : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = MPNetForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model( a_ , attention_mask=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self : str , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Dict , a_ : int , a_ : List[Any] , a_ : List[str] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : int = MPNetForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : Optional[Any] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Dict , a_ : Optional[int] , a_ : Union[str, Any] , a_ : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_choices SCREAMING_SNAKE_CASE__ : Any = MPNetForMultipleChoice(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Tuple = model( a_ , attention_mask=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowercase( self : int , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : int , a_ : List[str] , a_ : Any )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Any = MPNetForTokenClassification(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Dict = config_and_inputs SCREAMING_SNAKE_CASE__ : str = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': MPNetModel, 'fill-mask': MPNetForMaskedLM, 'question-answering': MPNetForQuestionAnswering, 'text-classification': MPNetForSequenceClassification, 'token-classification': MPNetForTokenClassification, 'zero-shot': MPNetForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False lowercase_ = True def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = MPNetModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*a_ ) def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*a_ ) def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*a_ ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = MPNetModel.from_pretrained('microsoft/mpnet-base' ) SCREAMING_SNAKE_CASE__ : Any = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) SCREAMING_SNAKE_CASE__ : Tuple = model(a_ )[0] SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor( [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) )
85
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
1
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
85
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
1
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) set_seed(770) SCREAMING_SNAKE_CASE__ : List[Any] = { "c_attn": "att_proj", "c_proj": "out_proj", "c_fc": "in_proj", "transformer.": "", "h.": "layers.", "ln_1": "layernorm_1", "ln_2": "layernorm_2", "ln_f": "layernorm_final", "wpe": "position_embeds_layer", "wte": "input_embeds_layer", } SCREAMING_SNAKE_CASE__ : Optional[Any] = { "text_small": { "repo_id": "suno/bark", "file_name": "text.pt", }, "coarse_small": { "repo_id": "suno/bark", "file_name": "coarse.pt", }, "fine_small": { "repo_id": "suno/bark", "file_name": "fine.pt", }, "text": { "repo_id": "suno/bark", "file_name": "text_2.pt", }, "coarse": { "repo_id": "suno/bark", "file_name": "coarse_2.pt", }, "fine": { "repo_id": "suno/bark", "file_name": "fine_2.pt", }, } SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.dirname(os.path.abspath(__file__)) SCREAMING_SNAKE_CASE__ : int = os.path.join(os.path.expanduser("~"), ".cache") SCREAMING_SNAKE_CASE__ : int = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def _a ( lowercase__ : Optional[Any] , lowercase__ : Optional[Any]=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = model_type if use_small: key += "_small" return os.path.join(lowercase__ , REMOTE_MODEL_PATHS[key]['file_name'] ) def _a ( lowercase__ : Dict , lowercase__ : Dict ): '''simple docstring''' os.makedirs(lowercase__ , exist_ok=lowercase__ ) hf_hub_download(repo_id=lowercase__ , filename=lowercase__ , local_dir=lowercase__ ) def _a ( lowercase__ : Optional[int] , lowercase__ : Dict , lowercase__ : Any=False , lowercase__ : int="text" ): '''simple docstring''' if model_type == "text": SCREAMING_SNAKE_CASE__ : List[str] = BarkSemanticModel SCREAMING_SNAKE_CASE__ : Optional[int] = BarkSemanticConfig SCREAMING_SNAKE_CASE__ : Dict = BarkSemanticGenerationConfig elif model_type == "coarse": SCREAMING_SNAKE_CASE__ : Tuple = BarkCoarseModel SCREAMING_SNAKE_CASE__ : Union[str, Any] = BarkCoarseConfig SCREAMING_SNAKE_CASE__ : List[str] = BarkCoarseGenerationConfig elif model_type == "fine": SCREAMING_SNAKE_CASE__ : Tuple = BarkFineModel SCREAMING_SNAKE_CASE__ : Tuple = BarkFineConfig SCREAMING_SNAKE_CASE__ : Optional[Any] = BarkFineGenerationConfig else: raise NotImplementedError() SCREAMING_SNAKE_CASE__ : Tuple = f'''{model_type}_small''' if use_small else model_type SCREAMING_SNAKE_CASE__ : Dict = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(lowercase__ ): logger.info(f'''{model_type} model not found, downloading into `{CACHE_DIR}`.''' ) _download(model_info['repo_id'] , model_info['file_name'] ) SCREAMING_SNAKE_CASE__ : str = torch.load(lowercase__ , map_location=lowercase__ ) # this is a hack SCREAMING_SNAKE_CASE__ : Optional[Any] = checkpoint['model_args'] if "input_vocab_size" not in model_args: SCREAMING_SNAKE_CASE__ : List[Any] = model_args['vocab_size'] SCREAMING_SNAKE_CASE__ : str = model_args['vocab_size'] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments SCREAMING_SNAKE_CASE__ : Optional[Any] = model_args.pop('n_head' ) SCREAMING_SNAKE_CASE__ : Optional[int] = model_args.pop('n_embd' ) SCREAMING_SNAKE_CASE__ : List[Any] = model_args.pop('n_layer' ) SCREAMING_SNAKE_CASE__ : Dict = ConfigClass(**checkpoint['model_args'] ) SCREAMING_SNAKE_CASE__ : str = ModelClass(config=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = GenerationConfigClass() SCREAMING_SNAKE_CASE__ : List[str] = model_generation_config SCREAMING_SNAKE_CASE__ : List[Any] = checkpoint['model'] # fixup checkpoint SCREAMING_SNAKE_CASE__ : List[str] = '_orig_mod.' for k, v in list(state_dict.items() ): if k.startswith(lowercase__ ): # replace part of the key with corresponding layer name in HF implementation SCREAMING_SNAKE_CASE__ : Optional[int] = k[len(lowercase__ ) :] for old_layer_name in new_layer_name_dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = new_k.replace(lowercase__ , new_layer_name_dict[old_layer_name] ) SCREAMING_SNAKE_CASE__ : Dict = state_dict.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : int = set(state_dict.keys() ) - set(model.state_dict().keys() ) SCREAMING_SNAKE_CASE__ : Tuple = {k for k in extra_keys if not k.endswith('.attn.bias' )} SCREAMING_SNAKE_CASE__ : Any = set(model.state_dict().keys() ) - set(state_dict.keys() ) SCREAMING_SNAKE_CASE__ : Optional[int] = {k for k in missing_keys if not k.endswith('.attn.bias' )} if len(lowercase__ ) != 0: raise ValueError(f'''extra keys found: {extra_keys}''' ) if len(lowercase__ ) != 0: raise ValueError(f'''missing keys: {missing_keys}''' ) model.load_state_dict(lowercase__ , strict=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.num_parameters(exclude_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = checkpoint['best_val_loss'].item() logger.info(f'''model loaded: {round(n_params/1E6 , 1 )}M params, {round(lowercase__ , 3 )} loss''' ) model.eval() model.to(lowercase__ ) del checkpoint, state_dict return model def _a ( lowercase__ : Dict , lowercase__ : Tuple=False , lowercase__ : str="text" ): '''simple docstring''' if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() SCREAMING_SNAKE_CASE__ : Dict = 'cpu' # do conversion on cpu SCREAMING_SNAKE_CASE__ : str = _get_ckpt_path(lowercase__ , use_small=lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = _load_model(lowercase__ , lowercase__ , model_type=lowercase__ , use_small=lowercase__ ) # load bark initial model SCREAMING_SNAKE_CASE__ : List[str] = _bark_load_model(lowercase__ , 'cpu' , model_type=lowercase__ , use_small=lowercase__ ) if model_type == "text": SCREAMING_SNAKE_CASE__ : Any = bark_model['model'] if model.num_parameters(exclude_embeddings=lowercase__ ) != bark_model.get_num_params(): raise ValueError('initial and new models don\'t have the same number of parameters' ) # check if same output as the bark model SCREAMING_SNAKE_CASE__ : Union[str, Any] = 5 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 10 if model_type in ["text", "coarse"]: SCREAMING_SNAKE_CASE__ : List[Any] = torch.randint(2_56 , (batch_size, sequence_length) , dtype=torch.int ) SCREAMING_SNAKE_CASE__ : str = bark_model(lowercase__ )[0] SCREAMING_SNAKE_CASE__ : str = model(lowercase__ ) # take last logits SCREAMING_SNAKE_CASE__ : Optional[int] = output_new_model_total.logits[:, [-1], :] else: SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Dict = 8 SCREAMING_SNAKE_CASE__ : str = torch.randint(2_56 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) SCREAMING_SNAKE_CASE__ : Any = model(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = bark_model(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError('initial and new outputs don\'t have the same shape' ) if (output_new_model - output_old_model).abs().max().item() > 1E-3: raise ValueError('initial and new outputs are not equal' ) Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) model.save_pretrained(lowercase__ ) def _a ( lowercase__ : Dict , lowercase__ : Any , lowercase__ : int , lowercase__ : Optional[Any] , lowercase__ : Optional[int] , lowercase__ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = BarkSemanticConfig.from_pretrained(os.path.join(lowercase__ , 'config.json' ) ) SCREAMING_SNAKE_CASE__ : List[Any] = BarkCoarseConfig.from_pretrained(os.path.join(lowercase__ , 'config.json' ) ) SCREAMING_SNAKE_CASE__ : int = BarkFineConfig.from_pretrained(os.path.join(lowercase__ , 'config.json' ) ) SCREAMING_SNAKE_CASE__ : List[str] = EncodecConfig.from_pretrained('facebook/encodec_24khz' ) SCREAMING_SNAKE_CASE__ : Dict = BarkSemanticModel.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = BarkCoarseModel.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BarkFineModel.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = EncodecModel.from_pretrained('facebook/encodec_24khz' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = BarkConfig.from_sub_model_configs( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : int = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BarkModel(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = semantic SCREAMING_SNAKE_CASE__ : str = coarseAcoustic SCREAMING_SNAKE_CASE__ : int = fineAcoustic SCREAMING_SNAKE_CASE__ : Optional[Any] = codec SCREAMING_SNAKE_CASE__ : str = bark_generation_config Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) bark.save_pretrained(lowercase__ , repo_id=lowercase__ , push_to_hub=lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
85
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class snake_case ( unittest.TestCase ): @slow def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFXLMRobertaModel.from_pretrained('jplu/tf-xlm-roberta-base' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'input_ids': tf.convert_to_tensor([[0, 2646, 1_0269, 83, 9_9942, 2]] , dtype=tf.intaa ), # "My dog is cute" 'attention_mask': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : Dict = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , a_ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
85
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
1
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "susnato/ernie-m-base_pytorch": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json", "susnato/ernie-m-large_pytorch": "https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'ernie_m' lowercase_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self : Optional[Any] , a_ : int = 25_0002 , a_ : int = 768 , a_ : int = 12 , a_ : int = 12 , a_ : int = 3072 , a_ : str = "gelu" , a_ : float = 0.1 , a_ : float = 0.1 , a_ : int = 514 , a_ : float = 0.02 , a_ : int = 1 , a_ : float = 1e-0_5 , a_ : List[Any]=None , a_ : Dict=False , a_ : Union[str, Any]=0.0 , **a_ : List[Any] , )-> Tuple: """simple docstring""" super().__init__(pad_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : str = hidden_act SCREAMING_SNAKE_CASE__ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = classifier_dropout SCREAMING_SNAKE_CASE__ : List[Any] = is_decoder SCREAMING_SNAKE_CASE__ : Optional[Any] = act_dropout
85
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 snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
1
from ...processing_utils import ProcessorMixin class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'feature_extractor'] lowercase_ = 'TvltImageProcessor' lowercase_ = 'TvltFeatureExtractor' def __init__( self : int , a_ : List[str] , a_ : Dict )-> str: """simple docstring""" super().__init__(image_processor=a_ , feature_extractor=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor SCREAMING_SNAKE_CASE__ : Any = feature_extractor def __call__( self : Optional[Any] , a_ : int=None , a_ : str=None , a_ : int=None , a_ : Tuple=None , a_ : Tuple=False , a_ : Dict=False , *a_ : Tuple , **a_ : Union[str, Any] , )-> List[str]: """simple docstring""" if images is None and audio is None: raise ValueError('You need to specify either an `images` or `audio` input to process.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if images is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.image_processor(a_ , mask_pixel=a_ , *a_ , **a_ ) if images_mixed is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.image_processor(a_ , is_mixed=a_ , *a_ , **a_ ) if audio is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extractor( a_ , *a_ , sampling_rate=a_ , mask_audio=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {} if audio is not None: output_dict.update(a_ ) if images is not None: output_dict.update(a_ ) if images_mixed_dict is not None: output_dict.update(a_ ) return output_dict @property def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor.model_input_names SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
SCREAMING_SNAKE_CASE__ : int = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def _a ( lowercase__ : bytes ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ''.join(bin(lowercase__ )[2:].zfill(8 ) for byte in data ) SCREAMING_SNAKE_CASE__ : Any = len(lowercase__ ) % 6 != 0 if padding_needed: # The padding that will be added later SCREAMING_SNAKE_CASE__ : List[Any] = b'=' * ((6 - len(lowercase__ ) % 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(lowercase__ ) % 6) else: SCREAMING_SNAKE_CASE__ : Optional[int] = 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(lowercase__ ) , 6 ) ).encode() + padding ) def _a ( lowercase__ : str ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) and not isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = ( 'argument should be a bytes-like object or ASCII string, ' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowercase__ ) # 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(lowercase__ , lowercase__ ): try: SCREAMING_SNAKE_CASE__ : str = encoded_data.decode('utf-8' ) except UnicodeDecodeError: raise ValueError('base64 encoded data should only contain ASCII characters' ) SCREAMING_SNAKE_CASE__ : int = 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(lowercase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one SCREAMING_SNAKE_CASE__ : int = encoded_data[:-padding] SCREAMING_SNAKE_CASE__ : List[str] = ''.join( bin(B64_CHARSET.index(lowercase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: SCREAMING_SNAKE_CASE__ : List[str] = ''.join( bin(B64_CHARSET.index(lowercase__ ) )[2:].zfill(6 ) for char in encoded_data ) SCREAMING_SNAKE_CASE__ : Optional[int] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowercase__ ) , 8 ) ] return bytes(lowercase__ ) if __name__ == "__main__": import doctest doctest.testmod()
85
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
1
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = "T5Config" def _a ( lowercase__ : jnp.array , lowercase__ : int , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = jnp.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) SCREAMING_SNAKE_CASE__ : int = shifted_input_ids.at[:, 0].set(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = jnp.where(shifted_input_ids == -1_00 , lowercase__ , lowercase__ ) return shifted_input_ids class snake_case ( UpperCamelCase_ ): lowercase_ = 'mt5' lowercase_ = MTaConfig class snake_case ( UpperCamelCase_ ): lowercase_ = 'mt5' lowercase_ = MTaConfig class snake_case ( UpperCamelCase_ ): lowercase_ = 'mt5' lowercase_ = MTaConfig
85
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
1
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def _a ( lowercase__ : bytes , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ : Any = '1' SCREAMING_SNAKE_CASE__ : int = 'f32le' SCREAMING_SNAKE_CASE__ : Dict = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowercase__ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ffmpeg_process.communicate(lowercase__ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error SCREAMING_SNAKE_CASE__ : Any = output_stream[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.frombuffer(lowercase__ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def _a ( lowercase__ : int , lowercase__ : float , lowercase__ : str = "f32le" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ : Optional[int] = '1' if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ : Union[str, Any] = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) SCREAMING_SNAKE_CASE__ : Dict = platform.system() if system == "Linux": SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'alsa' SCREAMING_SNAKE_CASE__ : Any = 'default' elif system == "Darwin": SCREAMING_SNAKE_CASE__ : Optional[Any] = 'avfoundation' SCREAMING_SNAKE_CASE__ : Dict = ':0' elif system == "Windows": SCREAMING_SNAKE_CASE__ : int = 'dshow' SCREAMING_SNAKE_CASE__ : Dict = 'default' SCREAMING_SNAKE_CASE__ : int = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] SCREAMING_SNAKE_CASE__ : List[str] = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : int = _ffmpeg_stream(lowercase__ , lowercase__ ) for item in iterator: yield item def _a ( lowercase__ : int , lowercase__ : float , lowercase__ : Optional[int] = None , lowercase__ : Optional[Union[Tuple[float, float], float]] = None , lowercase__ : str = "f32le" , ): '''simple docstring''' if stream_chunk_s is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = stream_chunk_s else: SCREAMING_SNAKE_CASE__ : Optional[int] = chunk_length_s SCREAMING_SNAKE_CASE__ : Any = ffmpeg_microphone(lowercase__ , lowercase__ , format_for_conversion=lowercase__ ) if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ : int = np.intaa SCREAMING_SNAKE_CASE__ : Any = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ : int = np.floataa SCREAMING_SNAKE_CASE__ : Optional[int] = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) if stride_length_s is None: SCREAMING_SNAKE_CASE__ : str = chunk_length_s / 6 SCREAMING_SNAKE_CASE__ : List[Any] = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowercase__ , (int, float) ): SCREAMING_SNAKE_CASE__ : List[str] = [stride_length_s, stride_length_s] SCREAMING_SNAKE_CASE__ : Any = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : Tuple = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : List[Any] = datetime.datetime.now() SCREAMING_SNAKE_CASE__ : Union[str, Any] = datetime.timedelta(seconds=lowercase__ ) for item in chunk_bytes_iter(lowercase__ , lowercase__ , stride=(stride_left, stride_right) , stream=lowercase__ ): # Put everything back in numpy scale SCREAMING_SNAKE_CASE__ : Tuple = np.frombuffer(item['raw'] , dtype=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def _a ( lowercase__ : Optional[int] , lowercase__ : int , lowercase__ : Tuple[int, int] , lowercase__ : bool = False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = b'' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = stride if stride_left + stride_right >= chunk_len: raise ValueError( f'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}''' ) SCREAMING_SNAKE_CASE__ : int = 0 for raw in iterator: acc += raw if stream and len(lowercase__ ) < chunk_len: SCREAMING_SNAKE_CASE__ : int = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowercase__ ) >= chunk_len: # We are flushing the accumulator SCREAMING_SNAKE_CASE__ : Union[str, Any] = (_stride_left, stride_right) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'raw': acc[:chunk_len], 'stride': stride} if stream: SCREAMING_SNAKE_CASE__ : Optional[int] = False yield item SCREAMING_SNAKE_CASE__ : Optional[Any] = stride_left SCREAMING_SNAKE_CASE__ : Tuple = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowercase__ ) > stride_left: SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'raw': acc, 'stride': (_stride_left, 0)} if stream: SCREAMING_SNAKE_CASE__ : Optional[int] = False yield item def _a ( lowercase__ : List[Any] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = 2**24 # 16Mo try: with subprocess.Popen(lowercase__ , stdout=subprocess.PIPE , bufsize=lowercase__ ) as ffmpeg_process: while True: SCREAMING_SNAKE_CASE__ : Optional[Any] = ffmpeg_process.stdout.read(lowercase__ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
85
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : Dict , a_ : Optional[int] )-> Dict: """simple docstring""" for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] , model_result['ss'] ): SCREAMING_SNAKE_CASE__ : Optional[int] = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = PyTorchBenchmark(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 'sgugger/tiny-distilbert-classification' SCREAMING_SNAKE_CASE__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , only_pretrain_model=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = PyTorchBenchmark(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , torchscript=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = PyTorchBenchmark(a_ ) SCREAMING_SNAKE_CASE__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' , 'Cant do half precision' ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , fpaa=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = PyTorchBenchmark(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : Tuple = AutoConfig.from_pretrained(a_ ) # set architectures equal to `None` SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = PyTorchBenchmark(a_ , configs=[config] ) SCREAMING_SNAKE_CASE__ : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : Optional[int] = PyTorchBenchmark(a_ ) SCREAMING_SNAKE_CASE__ : int = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' , 'Can\'t do half precision' ) def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : int = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=a_ , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = PyTorchBenchmark(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __lowercase( self : str )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : List[str] = AutoConfig.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = PyTorchBenchmark(a_ , configs=[config] ) SCREAMING_SNAKE_CASE__ : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowercase( self : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 'sshleifer/tinier_bart' SCREAMING_SNAKE_CASE__ : Tuple = AutoConfig.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = PyTorchBenchmark(a_ , configs=[config] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'sshleifer/tiny-gpt2' SCREAMING_SNAKE_CASE__ : Optional[int] = AutoConfig.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : List[str] = PyTorchBenchmark(a_ , configs=[config] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'sshleifer/tinier_bart' SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoConfig.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = PyTorchBenchmark(a_ , configs=[config] ) SCREAMING_SNAKE_CASE__ : int = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , save_to_csv=a_ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(a_ , 'inf_time.csv' ) , train_memory_csv_file=os.path.join(a_ , 'train_mem.csv' ) , inference_memory_csv_file=os.path.join(a_ , 'inf_mem.csv' ) , train_time_csv_file=os.path.join(a_ , 'train_time.csv' ) , env_info_csv_file=os.path.join(a_ , 'env.csv' ) , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : str = PyTorchBenchmark(a_ ) benchmark.run() self.assertTrue(Path(os.path.join(a_ , 'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(a_ , 'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(a_ , 'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(a_ , 'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(a_ , 'env.csv' ) ).exists() ) def __lowercase( self : List[str] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(a_ : Tuple ): self.assertTrue(hasattr(a_ , 'sequential' ) ) self.assertTrue(hasattr(a_ , 'cumulative' ) ) self.assertTrue(hasattr(a_ , 'current' ) ) self.assertTrue(hasattr(a_ , 'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=a_ , inference=a_ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(a_ , 'log.txt' ) , log_print=a_ , trace_memory_line_by_line=a_ , multi_process=a_ , ) SCREAMING_SNAKE_CASE__ : int = PyTorchBenchmark(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(a_ , 'log.txt' ) ).exists() )
85
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
1
from __future__ import annotations from fractions import Fraction def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Dict = 11 SCREAMING_SNAKE_CASE__ : Optional[int] = int('1' + '0' * digit_len ) for num in range(lowercase__ , lowercase__ ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(lowercase__ , lowercase__ ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 SCREAMING_SNAKE_CASE__ : Tuple = 10 return solutions def _a ( lowercase__ : int = 2 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 for fraction in fraction_list(lowercase__ ): SCREAMING_SNAKE_CASE__ : List[Any] = Fraction(lowercase__ ) result *= frac.denominator / frac.numerator return int(lowercase__ ) if __name__ == "__main__": print(solution())
85
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
1
import string import numpy def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return b if a == 0 else greatest_common_divisor(b % a , lowercase__ ) class snake_case : lowercase_ = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) lowercase_ = numpy.vectorize(lambda UpperCamelCase_ : x % 36 ) lowercase_ = numpy.vectorize(UpperCamelCase_ ) def __init__( self : Tuple , a_ : numpy.ndarray )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.modulus(a_ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key SCREAMING_SNAKE_CASE__ : int = encrypt_key.shape[0] def __lowercase( self : Any , a_ : str )-> int: """simple docstring""" return self.key_string.index(a_ ) def __lowercase( self : int , a_ : int )-> str: """simple docstring""" return self.key_string[round(a_ )] def __lowercase( self : Dict )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: SCREAMING_SNAKE_CASE__ : List[Any] = det % len(self.key_string ) SCREAMING_SNAKE_CASE__ : Tuple = len(self.key_string ) if greatest_common_divisor(a_ , len(self.key_string ) ) != 1: SCREAMING_SNAKE_CASE__ : Any = ( F'''determinant modular {req_l} of encryption key({det}) ''' F'''is not co prime w.r.t {req_l}.\nTry another key.''' ) raise ValueError(a_ ) def __lowercase( self : int , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [char for char in text.upper() if char in self.key_string] SCREAMING_SNAKE_CASE__ : str = chars[-1] while len(a_ ) % self.break_key != 0: chars.append(a_ ) return "".join(a_ ) def __lowercase( self : Any , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.process_text(text.upper() ) SCREAMING_SNAKE_CASE__ : int = '' for i in range(0 , len(a_ ) - self.break_key + 1 , self.break_key ): SCREAMING_SNAKE_CASE__ : Any = text[i : i + self.break_key] SCREAMING_SNAKE_CASE__ : int = [self.replace_letters(a_ ) for char in batch] SCREAMING_SNAKE_CASE__ : int = numpy.array([vec] ).T SCREAMING_SNAKE_CASE__ : Tuple = self.modulus(self.encrypt_key.dot(a_ ) ).T.tolist()[ 0 ] SCREAMING_SNAKE_CASE__ : List[str] = ''.join( self.replace_digits(a_ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def __lowercase( self : List[str] )-> numpy.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: SCREAMING_SNAKE_CASE__ : Any = det % len(self.key_string ) SCREAMING_SNAKE_CASE__ : Dict = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: SCREAMING_SNAKE_CASE__ : Any = i break SCREAMING_SNAKE_CASE__ : Optional[int] = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(a_ ) ) def __lowercase( self : Dict , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.make_decrypt_key() SCREAMING_SNAKE_CASE__ : Optional[int] = self.process_text(text.upper() ) SCREAMING_SNAKE_CASE__ : List[str] = '' for i in range(0 , len(a_ ) - self.break_key + 1 , self.break_key ): SCREAMING_SNAKE_CASE__ : int = text[i : i + self.break_key] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.replace_letters(a_ ) for char in batch] SCREAMING_SNAKE_CASE__ : Any = numpy.array([vec] ).T SCREAMING_SNAKE_CASE__ : str = self.modulus(decrypt_key.dot(a_ ) ).T.tolist()[0] SCREAMING_SNAKE_CASE__ : int = ''.join( self.replace_digits(a_ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = int(input('Enter the order of the encryption key: ' ) ) SCREAMING_SNAKE_CASE__ : Dict = [] print('Enter each row of the encryption key with space separated integers' ) for _ in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = [int(lowercase__ ) for x in input().split()] hill_matrix.append(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = HillCipher(numpy.array(lowercase__ ) ) print('Would you like to encrypt or decrypt some text? (1 or 2)' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = input('\n1. Encrypt\n2. Decrypt\n' ) if option == "1": SCREAMING_SNAKE_CASE__ : Any = input('What text would you like to encrypt?: ' ) print('Your encrypted text is:' ) print(hc.encrypt(lowercase__ ) ) elif option == "2": SCREAMING_SNAKE_CASE__ : int = input('What text would you like to decrypt?: ' ) print('Your decrypted text is:' ) print(hc.decrypt(lowercase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
85
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
1
def _a ( lowercase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = len(lowercase__ ) for i in range(lowercase__ ): for j in range(i + 1 , lowercase__ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = numbers[j], numbers[i] return numbers if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = input("Enter numbers separated by a comma:\n").strip() SCREAMING_SNAKE_CASE__ : Dict = [int(item) for item in user_input.split(",")] print(exchange_sort(unsorted))
85
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
1
from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class snake_case ( yaml.SafeLoader ): def __lowercase( self : Any , a_ : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE__ : List[Any] = [tuple(a_ ) if isinstance(a_ , a_ ) else key for key in keys] SCREAMING_SNAKE_CASE__ : Union[str, Any] = Counter(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F'''Got duplicate yaml keys: {duplicate_keys}''' ) def __lowercase( self : Any , a_ : Union[str, Any] , a_ : Optional[Any]=False )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = super().construct_mapping(a_ , deep=a_ ) self._check_no_duplicates_on_constructed_node(a_ ) return mapping def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE__ : int = full_content[1:].index('---' ) + 1 SCREAMING_SNAKE_CASE__ : List[Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowercase__ ) class snake_case ( UpperCamelCase_ ): # class attributes lowercase_ = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def __lowercase( cls : Tuple , a_ : Path )-> "DatasetMetadata": """simple docstring""" with open(a_ , encoding='utf-8' ) as readme_file: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(a_ ) else: return cls() def __lowercase( self : Union[str, Any] , a_ : Path )-> Union[str, Any]: """simple docstring""" if path.exists(): with open(a_ , encoding='utf-8' ) as readme_file: SCREAMING_SNAKE_CASE__ : Dict = readme_file.read() else: SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : int = self._to_readme(a_ ) with open(a_ , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(a_ ) def __lowercase( self : str , a_ : Optional[str] = None )-> str: """simple docstring""" if readme_content is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = _split_yaml_from_readme(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = '---\n' + self.to_yaml_string() + '---\n' + content else: SCREAMING_SNAKE_CASE__ : List[str] = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def __lowercase( cls : List[str] , a_ : str )-> "DatasetMetadata": """simple docstring""" SCREAMING_SNAKE_CASE__ : str = yaml.load(a_ , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE__ : Tuple = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**a_ ) def __lowercase( self : List[str] )-> str: """simple docstring""" return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=a_ , allow_unicode=a_ , encoding='utf-8' , ).decode('utf-8' ) SCREAMING_SNAKE_CASE__ : Optional[int] = { "image-classification": [], "translation": [], "image-segmentation": [], "fill-mask": [], "automatic-speech-recognition": [], "token-classification": [], "sentence-similarity": [], "audio-classification": [], "question-answering": [], "summarization": [], "zero-shot-classification": [], "table-to-text": [], "feature-extraction": [], "other": [], "multiple-choice": [], "text-classification": [], "text-to-image": [], "text2text-generation": [], "zero-shot-image-classification": [], "tabular-classification": [], "tabular-regression": [], "image-to-image": [], "tabular-to-text": [], "unconditional-image-generation": [], "text-retrieval": [], "text-to-speech": [], "object-detection": [], "audio-to-audio": [], "text-generation": [], "conversational": [], "table-question-answering": [], "visual-question-answering": [], "image-to-text": [], "reinforcement-learning": [], "voice-activity-detection": [], "time-series-forecasting": [], "document-question-answering": [], } if __name__ == "__main__": from argparse import ArgumentParser SCREAMING_SNAKE_CASE__ : str = ArgumentParser(usage="Validate the yaml metadata block of a README.md file.") ap.add_argument("readme_filepath") SCREAMING_SNAKE_CASE__ : Union[str, Any] = ap.parse_args() SCREAMING_SNAKE_CASE__ : Union[str, Any] = Path(args.readme_filepath) SCREAMING_SNAKE_CASE__ : List[str] = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
85
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "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 SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case ( UpperCamelCase_ ): lowercase_ = 42 lowercase_ = 42 def __init__( self : str , a_ : UNetaDModel , a_ : ScoreSdeVeScheduler )-> List[Any]: """simple docstring""" super().__init__() self.register_modules(unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self : Optional[int] , a_ : int = 1 , a_ : int = 2000 , a_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a_ : Optional[str] = "pil" , a_ : bool = True , **a_ : int , )-> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.unet.config.sample_size SCREAMING_SNAKE_CASE__ : Tuple = (batch_size, 3, img_size, img_size) SCREAMING_SNAKE_CASE__ : Tuple = self.unet SCREAMING_SNAKE_CASE__ : Union[str, Any] = randn_tensor(a_ , generator=a_ ) * self.scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : int = sample.to(self.device ) self.scheduler.set_timesteps(a_ ) self.scheduler.set_sigmas(a_ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): SCREAMING_SNAKE_CASE__ : Optional[int] = self.unet(a_ , a_ ).sample SCREAMING_SNAKE_CASE__ : List[str] = self.scheduler.step_correct(a_ , a_ , generator=a_ ).prev_sample # prediction step SCREAMING_SNAKE_CASE__ : Any = model(a_ , a_ ).sample SCREAMING_SNAKE_CASE__ : str = self.scheduler.step_pred(a_ , a_ , a_ , generator=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = output.prev_sample, output.prev_sample_mean SCREAMING_SNAKE_CASE__ : Dict = sample_mean.clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : int = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : str = self.numpy_to_pil(a_ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=a_ )
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
1
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' while b: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = b, a % b return a def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(lowercase__ , a % b ) def _a ( ): '''simple docstring''' print(f'''euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}''' ) print(f'''euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}''' ) print(f'''euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}''' ) print(f'''euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}''' ) print(f'''euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}''' ) print(f'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}''' ) print(f'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}''' ) print(f'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}''' ) print(f'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}''' ) print(f'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}''' ) if __name__ == "__main__": main()
85
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
1
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PhobertTokenizer lowercase_ = False def __lowercase( self : int )-> Optional[int]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : Tuple = ['T@@', 'i', 'I', 'R@@', 'r', 'e@@'] SCREAMING_SNAKE_CASE__ : str = dict(zip(a_ , range(len(a_ ) ) ) ) SCREAMING_SNAKE_CASE__ : Any = ['#version: 0.2', 'l à</w>'] SCREAMING_SNAKE_CASE__ : Optional[int] = {'unk_token': '<unk>'} SCREAMING_SNAKE_CASE__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: for token in vocab_tokens: fp.write(F'''{token} {vocab_tokens[token]}\n''' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a_ ) ) def __lowercase( self : Any , **a_ : Any )-> str: """simple docstring""" kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Any , a_ : Optional[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 'Tôi là VinAI Research' SCREAMING_SNAKE_CASE__ : List[str] = 'T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>' return input_text, output_text def __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Tuple = 'Tôi là VinAI Research' SCREAMING_SNAKE_CASE__ : Tuple = 'T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h'.split() SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize(a_ ) print(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : List[Any] = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , a_ )
85
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
1
def _a ( lowercase__ : int = 1_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : str = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
85
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = 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 : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
1
SCREAMING_SNAKE_CASE__ : Dict = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] SCREAMING_SNAKE_CASE__ : List[Any] = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] SCREAMING_SNAKE_CASE__ : str = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] SCREAMING_SNAKE_CASE__ : Optional[int] = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] SCREAMING_SNAKE_CASE__ : Dict = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] SCREAMING_SNAKE_CASE__ : str = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] SCREAMING_SNAKE_CASE__ : Tuple = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] SCREAMING_SNAKE_CASE__ : List[str] = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
85
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): SCREAMING_SNAKE_CASE__ : Dict = """pt""" elif is_tf_available(): SCREAMING_SNAKE_CASE__ : List[str] = """tf""" else: SCREAMING_SNAKE_CASE__ : List[Any] = """jax""" class lowerCamelCase_ ( lowerCamelCase , unittest.TestCase ): a__ = PerceiverTokenizer a__ = False def A ( self ): """simple docstring""" super().setUp() __magic_name__ :str = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A ( self ): """simple docstring""" return PerceiverTokenizer.from_pretrained('''deepmind/language-perceiver''' ) def A ( self , **__lowerCAmelCase ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def A ( self , __lowerCAmelCase , __lowerCAmelCase=False , __lowerCAmelCase=2_0 , __lowerCAmelCase=5 ): """simple docstring""" # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. __magic_name__ :List[str] = [] for i in range(len(__lowerCAmelCase ) ): try: __magic_name__ :Optional[int] = tokenizer.decode([i] , clean_up_tokenization_spaces=__lowerCAmelCase ) except UnicodeDecodeError: pass toks.append((i, tok) ) __magic_name__ :Dict = list(filter(lambda __lowerCAmelCase : re.match(R'''^[ a-zA-Z]+$''' , t[1] ) , __lowerCAmelCase ) ) __magic_name__ :Union[str, Any] = list(filter(lambda __lowerCAmelCase : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=__lowerCAmelCase ) , __lowerCAmelCase ) ) if max_length is not None and len(__lowerCAmelCase ) > max_length: __magic_name__ :int = toks[:max_length] if min_length is not None and len(__lowerCAmelCase ) < min_length and len(__lowerCAmelCase ) > 0: while len(__lowerCAmelCase ) < min_length: __magic_name__ :str = toks + toks # toks_str = [t[1] for t in toks] __magic_name__ :Dict = [t[0] for t in toks] # Ensure consistency __magic_name__ :List[str] = tokenizer.decode(__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) if " " not in output_txt and len(__lowerCAmelCase ) > 1: __magic_name__ :Tuple = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__lowerCAmelCase ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__lowerCAmelCase ) ) if with_prefix_space: __magic_name__ :Union[str, Any] = ''' ''' + output_txt __magic_name__ :str = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) return output_txt, output_ids def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = self.perceiver_tokenizer __magic_name__ :List[Any] = '''Unicode €.''' __magic_name__ :Tuple = tokenizer(__lowerCAmelCase ) __magic_name__ :Optional[int] = [4, 9_1, 1_1_6, 1_1_1, 1_0_5, 1_1_7, 1_0_6, 1_0_7, 3_8, 2_3_2, 1_3_6, 1_7_8, 5_2, 5] self.assertEqual(encoded['''input_ids'''] , __lowerCAmelCase ) # decoding __magic_name__ :List[str] = tokenizer.decode(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , '''[CLS]Unicode €.[SEP]''' ) __magic_name__ :int = tokenizer('''e è é ê ë''' ) __magic_name__ :List[Any] = [4, 1_0_7, 3_8, 2_0_1, 1_7_4, 3_8, 2_0_1, 1_7_5, 3_8, 2_0_1, 1_7_6, 3_8, 2_0_1, 1_7_7, 5] self.assertEqual(encoded['''input_ids'''] , __lowerCAmelCase ) # decoding __magic_name__ :Tuple = tokenizer.decode(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , '''[CLS]e è é ê ë[SEP]''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''[CLS]e è é ê ë[SEP]''' ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = self.perceiver_tokenizer __magic_name__ :Tuple = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off __magic_name__ :Union[str, Any] = [4, 7_1, 3_8, 1_1_4, 1_1_7, 1_1_6, 1_0_9, 3_8, 1_1_8, 1_0_3, 1_2_0, 1_0_3, 1_0_9, 1_2_0, 1_0_3, 1_1_8, 1_1_0, 3_8, 1_0_8, 1_1_7, 1_2_0, 3_8, 1_2_1, 1_2_3, 1_1_5, 1_1_5, 1_0_3, 1_2_0, 1_1_1, 1_2_8, 1_0_3, 1_2_2, 1_1_1, 1_1_7, 1_1_6, 5_2, 5, 0] # fmt: on __magic_name__ :List[str] = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) if FRAMEWORK != "jax": __magic_name__ :List[Any] = list(batch.input_ids.numpy()[0] ) else: __magic_name__ :Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual((2, 3_8) , batch.input_ids.shape ) self.assertEqual((2, 3_8) , batch.attention_mask.shape ) def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.perceiver_tokenizer __magic_name__ :Dict = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] __magic_name__ :Any = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , __lowerCAmelCase ) self.assertIn('''attention_mask''' , __lowerCAmelCase ) self.assertNotIn('''decoder_input_ids''' , __lowerCAmelCase ) self.assertNotIn('''decoder_attention_mask''' , __lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :str = self.perceiver_tokenizer __magic_name__ :Optional[Any] = [ '''Summary of the text.''', '''Another summary.''', ] __magic_name__ :int = tokenizer( text_target=__lowerCAmelCase , max_length=3_2 , padding='''max_length''' , truncation=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) self.assertEqual(3_2 , targets['''input_ids'''].shape[1] ) def A ( self ): """simple docstring""" # safety check on max_len default value so we are sure the test works __magic_name__ :List[str] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test __magic_name__ :Dict = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __magic_name__ :Union[str, Any] = tempfile.mkdtemp() __magic_name__ :Union[str, Any] = ''' He is very happy, UNwant\u00E9d,running''' __magic_name__ :Optional[Any] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) tokenizer.save_pretrained(__lowerCAmelCase ) __magic_name__ :int = tokenizer.__class__.from_pretrained(__lowerCAmelCase ) __magic_name__ :Union[str, Any] = after_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) shutil.rmtree(__lowerCAmelCase ) __magic_name__ :int = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __magic_name__ :Union[str, Any] = tempfile.mkdtemp() __magic_name__ :Tuple = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) __magic_name__ :Optional[Any] = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) __magic_name__ :List[Any] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) tokenizer.save_pretrained(__lowerCAmelCase ) __magic_name__ :int = tokenizer.__class__.from_pretrained(__lowerCAmelCase ) __magic_name__ :Union[str, Any] = after_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) __magic_name__ :Optional[Any] = tokenizer.__class__.from_pretrained(__lowerCAmelCase , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :str = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__lowerCAmelCase ) with open(os.path.join(__lowerCAmelCase , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: __magic_name__ :Union[str, Any] = json.load(__lowerCAmelCase ) with open(os.path.join(__lowerCAmelCase , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: __magic_name__ :Tuple = json.load(__lowerCAmelCase ) __magic_name__ :str = [F'''<extra_id_{i}>''' for i in range(1_2_5 )] __magic_name__ :List[str] = added_tokens_extra_ids + [ '''an_additional_special_token''' ] __magic_name__ :Tuple = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(__lowerCAmelCase , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(__lowerCAmelCase , __lowerCAmelCase ) with open(os.path.join(__lowerCAmelCase , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(__lowerCAmelCase , __lowerCAmelCase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __magic_name__ :Optional[int] = tokenizer_class.from_pretrained( __lowerCAmelCase , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __magic_name__ :Optional[Any] = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=__lowerCAmelCase )] __magic_name__ :Any = tokenizer_class.from_pretrained( __lowerCAmelCase , additional_special_tokens=__lowerCAmelCase , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def A ( self ): """simple docstring""" __magic_name__ :List[str] = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([1_7_8] ) , '''�''' ) def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens __magic_name__ :List[Any] = self.get_tokenizers(fast=__lowerCAmelCase , do_lower_case=__lowerCAmelCase ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): __magic_name__ :Any = ['''[CLS]''', '''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''s''', '''t''', '''[SEP]'''] __magic_name__ :Union[str, Any] = tokenizer.convert_tokens_to_string(__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase )
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint __snake_case = { '''169M''': 1_2, '''430M''': 2_4, '''1B5''': 2_4, '''3B''': 3_2, '''7B''': 3_2, '''14B''': 4_0, } __snake_case = { '''169M''': 7_6_8, '''430M''': 1_0_2_4, '''1B5''': 2_0_4_8, '''3B''': 2_5_6_0, '''7B''': 4_0_9_6, '''14B''': 5_1_2_0, } def _A ( _lowercase ) -> List[str]: """simple docstring""" __UpperCamelCase = list(state_dict.keys() ) for name in state_dict_keys: __UpperCamelCase = state_dict.pop(_lowercase ) # emb -> embedding if name.startswith('emb.' ): __UpperCamelCase = name.replace('emb.' , 'embeddings.' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0' ): __UpperCamelCase = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln' ) # att -> attention __UpperCamelCase = re.sub(r'blocks\.(\d+)\.att' , r'blocks.\1.attention' , _lowercase ) # ffn -> feed_forward __UpperCamelCase = re.sub(r'blocks\.(\d+)\.ffn' , r'blocks.\1.feed_forward' , _lowercase ) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k' ): __UpperCamelCase = name.replace('.time_mix_k' , '.time_mix_key' ) # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v' ): __UpperCamelCase = name.replace('.time_mix_v' , '.time_mix_value' ) # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r' ): __UpperCamelCase = name.replace('.time_mix_r' , '.time_mix_receptance' ) if name != "head.weight": __UpperCamelCase = 'rwkv.' + name __UpperCamelCase = weight return state_dict def _A ( _lowercase , _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase=False , _lowercase=None ) -> Any: """simple docstring""" if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.' ) __UpperCamelCase = 5_02_77 __UpperCamelCase = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b' ) else: __UpperCamelCase = PreTrainedTokenizerFast(tokenizer_file=_lowercase ) __UpperCamelCase = len(_lowercase ) tokenizer.save_pretrained(_lowercase ) # 2. Build the config __UpperCamelCase = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: __UpperCamelCase = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.' ) if size not in possible_sizes: raise ValueError(f'''`size` should be one of {possible_sizes}, got {size}.''' ) __UpperCamelCase = RwkvConfig( vocab_size=_lowercase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_lowercase ) # 3. Download model file then convert state_dict __UpperCamelCase = hf_hub_download(_lowercase , _lowercase ) __UpperCamelCase = torch.load(_lowercase , map_location='cpu' ) __UpperCamelCase = convert_state_dict(_lowercase ) # 4. Split in shards and save __UpperCamelCase, __UpperCamelCase = shard_checkpoint(_lowercase ) for shard_file, shard in shards.items(): torch.save(_lowercase , os.path.join(_lowercase , _lowercase ) ) if index is not None: __UpperCamelCase = os.path.join(_lowercase , _lowercase ) # Save the index as well with open(_lowercase , 'w' , encoding='utf-8' ) as f: __UpperCamelCase = json.dumps(_lowercase , indent=2 , sort_keys=_lowercase ) + '\n' f.write(_lowercase ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.' ) __UpperCamelCase = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: __UpperCamelCase = torch.load(os.path.join(_lowercase , _lowercase ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_lowercase , _lowercase ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.' ) __UpperCamelCase = AutoModelForCausalLM.from_pretrained(_lowercase ) model.push_to_hub(_lowercase , max_shard_size='2GB' ) tokenizer.push_to_hub(_lowercase ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--repo_id''', default=None, type=str, required=True, help='''Repo ID from which to pull the checkpoint.''' ) parser.add_argument( '''--checkpoint_file''', default=None, type=str, required=True, help='''Name of the checkpoint file in the repo.''' ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''Where to save the converted model.''' ) parser.add_argument( '''--tokenizer_file''', default=None, type=str, help='''Path to the tokenizer file to use (if not provided, only the model is converted).''', ) parser.add_argument( '''--size''', default=None, type=str, help='''Size of the model. Will be inferred from the `checkpoint_file` if not passed.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Push to the Hub the converted model.''', ) parser.add_argument( '''--model_name''', default=None, type=str, help='''Name of the pushed model on the Hub, including the username / organization.''', ) __snake_case = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
1
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
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 DeformableDetrImageProcessor class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" def __init__( self : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict=7 , __lowerCAmelCase : Tuple=3 , __lowerCAmelCase : int=30 , __lowerCAmelCase : Dict=4_00 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Optional[Any]=[0.5, 0.5, 0.5] , __lowerCAmelCase : Dict=[0.5, 0.5, 0.5] , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : List[str]=1 / 2_55 , __lowerCAmelCase : int=True , ) -> List[str]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p _A = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 13_33} _A = parent _A = batch_size _A = num_channels _A = min_resolution _A = max_resolution _A = do_resize _A = size _A = do_normalize _A = image_mean _A = image_std _A = do_rescale _A = rescale_factor _A = do_pad def snake_case_ ( self : Optional[int] ) -> Any: 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 snake_case_ ( self : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : str=False ) -> Dict: if not batched: _A = image_inputs[0] if isinstance(__lowerCAmelCase , Image.Image ): _A , _A = image.size else: _A , _A = image.shape[1], image.shape[2] if w < h: _A = int(self.size['''shortest_edge'''] * h / w ) _A = self.size['''shortest_edge'''] elif w > h: _A = self.size['''shortest_edge'''] _A = int(self.size['''shortest_edge'''] * w / h ) else: _A = self.size['''shortest_edge'''] _A = self.size['''shortest_edge'''] else: _A = [] for image in image_inputs: _A , _A = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _A = max(__lowerCAmelCase , key=lambda __lowerCAmelCase : item[0] )[0] _A = max(__lowerCAmelCase , key=lambda __lowerCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCamelCase__ ( _A , unittest.TestCase): """simple docstring""" a__ : Any = DeformableDetrImageProcessor if is_vision_available() else None def snake_case_ ( self : Optional[int] ) -> Any: _A = DeformableDetrImageProcessingTester(self ) @property def snake_case_ ( self : Union[str, Any] ) -> Dict: return self.image_processor_tester.prepare_image_processor_dict() def snake_case_ ( self : Optional[int] ) -> List[str]: _A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase , '''image_mean''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''image_std''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_rescale''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_pad''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''size''' ) ) def snake_case_ ( self : List[str] ) -> int: _A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 13_33} ) self.assertEqual(image_processor.do_pad , __lowerCAmelCase ) _A = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__lowerCAmelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , __lowerCAmelCase ) def snake_case_ ( self : Any ) -> Union[str, Any]: pass def snake_case_ ( self : List[str] ) -> Optional[int]: # Initialize image_processing _A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , Image.Image ) # Test not batched input _A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _A , _A = self.image_processor_tester.get_expected_values(__lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _A , _A = self.image_processor_tester.get_expected_values(__lowerCAmelCase , batched=__lowerCAmelCase ) _A = image_processing(__lowerCAmelCase , 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 snake_case_ ( self : Tuple ) -> int: # Initialize image_processing _A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , numpify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , np.ndarray ) # Test not batched input _A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _A , _A = self.image_processor_tester.get_expected_values(__lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _A = image_processing(__lowerCAmelCase , return_tensors='''pt''' ).pixel_values _A , _A = self.image_processor_tester.get_expected_values(__lowerCAmelCase , batched=__lowerCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def snake_case_ ( self : Optional[Any] ) -> int: # Initialize image_processing _A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , torchify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , torch.Tensor ) # Test not batched input _A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _A , _A = self.image_processor_tester.get_expected_values(__lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _A = image_processing(__lowerCAmelCase , return_tensors='''pt''' ).pixel_values _A , _A = self.image_processor_tester.get_expected_values(__lowerCAmelCase , batched=__lowerCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def snake_case_ ( self : Optional[Any] ) -> Optional[int]: # prepare image and target _A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: _A = json.loads(f.read() ) _A = {'''image_id''': 3_97_69, '''annotations''': target} # encode them _A = DeformableDetrImageProcessor() _A = image_processing(images=__lowerCAmelCase , annotations=__lowerCAmelCase , return_tensors='''pt''' ) # verify pixel values _A = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['''pixel_values'''].shape , __lowerCAmelCase ) _A = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __lowerCAmelCase , atol=1E-4 ) ) # verify area _A = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __lowerCAmelCase ) ) # verify boxes _A = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __lowerCAmelCase ) _A = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __lowerCAmelCase , atol=1E-3 ) ) # verify image_id _A = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __lowerCAmelCase ) ) # verify is_crowd _A = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __lowerCAmelCase ) ) # verify class_labels _A = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __lowerCAmelCase ) ) # verify orig_size _A = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __lowerCAmelCase ) ) # verify size _A = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __lowerCAmelCase ) ) @slow def snake_case_ ( self : List[str] ) -> List[str]: # prepare image, target and masks_path _A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: _A = json.loads(f.read() ) _A = {'''file_name''': '''000000039769.png''', '''image_id''': 3_97_69, '''segments_info''': target} _A = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them _A = DeformableDetrImageProcessor(format='''coco_panoptic''' ) _A = image_processing(images=__lowerCAmelCase , annotations=__lowerCAmelCase , masks_path=__lowerCAmelCase , return_tensors='''pt''' ) # verify pixel values _A = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['''pixel_values'''].shape , __lowerCAmelCase ) _A = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __lowerCAmelCase , atol=1E-4 ) ) # verify area _A = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __lowerCAmelCase ) ) # verify boxes _A = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __lowerCAmelCase ) _A = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __lowerCAmelCase , atol=1E-3 ) ) # verify image_id _A = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __lowerCAmelCase ) ) # verify is_crowd _A = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __lowerCAmelCase ) ) # verify class_labels _A = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __lowerCAmelCase ) ) # verify masks _A = 82_28_73 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , __lowerCAmelCase ) # verify orig_size _A = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __lowerCAmelCase ) ) # verify size _A = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __lowerCAmelCase ) )
2
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
0
'''simple docstring''' import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params lowerCAmelCase : Union[str, Any] = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def A_( A : Dict): for pegasus_name, hf_name in PATTERNS: UpperCamelCase = k.replace(A , A) return k def A_( A : dict , A : dict): UpperCamelCase = DEFAULTS.copy() cfg_kwargs.update(A) UpperCamelCase = PegasusConfig(**A) UpperCamelCase = PegasusForConditionalGeneration(A) UpperCamelCase = torch_model.model.state_dict() UpperCamelCase = {} for k, v in tf_weights.items(): UpperCamelCase = rename_state_dict_key(A) if new_k not in sd: raise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})''') if "dense" in k or "proj" in new_k: UpperCamelCase = v.T UpperCamelCase = torch.tensor(A , dtype=sd[new_k].dtype) assert v.shape == sd[new_k].shape, f'''{new_k}, {k}, {v.shape}, {sd[new_k].shape}''' # make sure embedding.padding_idx is respected UpperCamelCase = torch.zeros_like(mapping['shared.weight'][cfg.pad_token_id + 1]) UpperCamelCase = mapping['shared.weight'] UpperCamelCase = mapping['shared.weight'] UpperCamelCase = {k: torch.zeros_like(A) for k, v in sd.items() if k.endswith('bias') and k not in mapping} mapping.update(**A) UpperCamelCase , UpperCamelCase = torch_model.model.load_state_dict(A , strict=A) UpperCamelCase = [ k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.weight'] ] assert unexpected_missing == [], f'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], f'''no matches found for the following tf keys {extra}''' return torch_model def A_( A : Tuple="./ckpt/aeslc/model.ckpt-32000"): UpperCamelCase = tf.train.list_variables(A) UpperCamelCase = {} UpperCamelCase = ['Adafactor', 'global_step'] for name, shape in tqdm(A , desc='converting tf checkpoint to dict'): UpperCamelCase = any(pat in name for pat in ignore_name) if skip_key: continue UpperCamelCase = tf.train.load_variable(A , A) UpperCamelCase = array return tf_weights def A_( A : str , A : str): # save tokenizer first UpperCamelCase = Path(A).parent.name UpperCamelCase = task_specific_params[f'''summarization_{dataset}''']['max_position_embeddings'] UpperCamelCase = PegasusTokenizer.from_pretrained('sshleifer/pegasus' , model_max_length=A) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(A) # convert model UpperCamelCase = get_tf_weights_as_numpy(A) UpperCamelCase = task_specific_params[f'''summarization_{dataset}'''] if dataset == "large": UpperCamelCase = task_specific_params UpperCamelCase = convert_pegasus(A , A) torch_model.save_pretrained(A) UpperCamelCase = torch_model.state_dict() sd.pop('model.decoder.embed_positions.weight') sd.pop('model.encoder.embed_positions.weight') torch.save(A , Path(A) / 'pytorch_model.bin') if __name__ == "__main__": lowerCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase : Any = parser.parse_args() if args.save_dir is None: lowerCAmelCase : Optional[int] = Path(args.tf_ckpt_path).parent.name lowerCAmelCase : List[Any] = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
3
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Optional[int] = logging.get_logger(__name__) __UpperCamelCase : Dict = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class a ( a__ ): snake_case__ = '''gpt_bigcode''' snake_case__ = ['''past_key_values'''] snake_case__ = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _snake_case=5_02_57 , _snake_case=10_24 , _snake_case=7_68 , _snake_case=12 , _snake_case=12 , _snake_case=None , _snake_case="gelu_pytorch_tanh" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=0.1 , _snake_case=1E-5 , _snake_case=0.02 , _snake_case=True , _snake_case=True , _snake_case=5_02_56 , _snake_case=5_02_56 , _snake_case=True , _snake_case=True , _snake_case=True , **_snake_case , ): """simple docstring""" lowerCAmelCase = vocab_size lowerCAmelCase = n_positions lowerCAmelCase = n_embd lowerCAmelCase = n_layer lowerCAmelCase = n_head lowerCAmelCase = n_inner lowerCAmelCase = activation_function lowerCAmelCase = resid_pdrop lowerCAmelCase = embd_pdrop lowerCAmelCase = attn_pdrop lowerCAmelCase = layer_norm_epsilon lowerCAmelCase = initializer_range lowerCAmelCase = scale_attn_weights lowerCAmelCase = use_cache lowerCAmelCase = attention_softmax_in_fpaa lowerCAmelCase = scale_attention_softmax_in_fpaa lowerCAmelCase = multi_query lowerCAmelCase = bos_token_id lowerCAmelCase = eos_token_id super().__init__(bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case )
4
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
0
'''simple docstring''' import pytest _lowercase = """__dummy_dataset1__""" _lowercase = """ import json import os import datasets REPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\" URLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \"validation\": REPO_URL + \"wikiann-bn-validation.jsonl\"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { \"tokens\": datasets.Sequence(datasets.Value(\"string\")), \"ner_tags\": datasets.Sequence( datasets.features.ClassLabel( names=[ \"O\", \"B-PER\", \"I-PER\", \"B-ORG\", \"I-ORG\", \"B-LOC\", \"I-LOC\", ] ) ), \"langs\": datasets.Sequence(datasets.Value(\"string\")), \"spans\": datasets.Sequence(datasets.Value(\"string\")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={\"filepath\": dl_path[\"train\"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={\"filepath\": dl_path[\"validation\"]}), ] def _generate_examples(self, filepath): with open(filepath, \"r\", encoding=\"utf-8\") as f: for i, line in enumerate(f): yield i, json.loads(line) """ @pytest.fixture def A (): return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def A (): return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def A (__lowerCamelCase :Dict , __lowerCamelCase :List[Any] , __lowerCamelCase :Union[str, Any] ): _lowerCAmelCase = dataset_loading_script_name _lowerCAmelCase = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=__lowerCamelCase ) _lowerCAmelCase = script_dir / f'{script_name}.py' with open(__lowerCamelCase , """w""" ) as f: f.write(__lowerCamelCase ) return str(__lowerCamelCase )
5
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
0
import os import numpy import onnx def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = a.name SCREAMING_SNAKE_CASE__ = b.name SCREAMING_SNAKE_CASE__ = """""" SCREAMING_SNAKE_CASE__ = """""" SCREAMING_SNAKE_CASE__ = a == b SCREAMING_SNAKE_CASE__ = name_a SCREAMING_SNAKE_CASE__ = name_b return res def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] ): for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(UpperCamelCase__ , UpperCamelCase__ ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , UpperCamelCase__ , UpperCamelCase__ ) _graph_replace_input_with(node_proto.attribute[1].g , UpperCamelCase__ , UpperCamelCase__ ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): for n in graph_proto.node: _node_replace_input_with(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = list(model.graph.initializer ) SCREAMING_SNAKE_CASE__ = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i SCREAMING_SNAKE_CASE__ = inits[i].name SCREAMING_SNAKE_CASE__ = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = os.path.dirname(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.basename(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = onnx.load(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = list(model.graph.initializer ) SCREAMING_SNAKE_CASE__ = set() SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 for i in range(len(UpperCamelCase__ ) ): if i in dup_set: continue for j in range(i + 1 , len(UpperCamelCase__ ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(UpperCamelCase__ ) dup_set.add(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = inits[j].data_type SCREAMING_SNAKE_CASE__ = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print("""unexpected data type: """ , UpperCamelCase__ ) total_reduced_size += mem_size SCREAMING_SNAKE_CASE__ = inits[i].name SCREAMING_SNAKE_CASE__ = inits[j].name if name_i in dup_map: dup_map[name_i].append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = [name_j] ind_to_replace.append((j, i) ) print("""total reduced size: """ , total_reduced_size / 1_024 / 1_024 / 1_024 , """GB""" ) SCREAMING_SNAKE_CASE__ = sorted(UpperCamelCase__ ) _remove_dup_initializers_from_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """optimized_""" + model_file_name SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) onnx.save(UpperCamelCase__ , UpperCamelCase__ ) return new_model
6
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 snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
0
"""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 ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() a = logging.get_logger(__name__) def _snake_case ( _snake_case : List[Any] , _snake_case : Dict=False , _snake_case : Optional[int]=False , _snake_case : str=False ) -> Optional[Any]: '''simple docstring''' _A = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''transformer.blocks.{i}.norm1.weight''', F'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.norm1.bias''', F'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (F'''transformer.blocks.{i}.attn.proj.weight''', F'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (F'''transformer.blocks.{i}.attn.proj.bias''', F'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''transformer.blocks.{i}.norm2.weight''', F'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.norm2.bias''', F'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (F'''transformer.blocks.{i}.mlp.fc1.weight''', F'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc1.bias''', F'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc2.weight''', F'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc2.bias''', F'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _snake_case ( _snake_case : int , _snake_case : int ) -> Any: '''simple docstring''' for i in range(config.num_hidden_layers ): _A = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _A = state_dict.pop(F'''transformer.blocks.{i}.attn.qkv.weight''' ) _A = state_dict.pop(F'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _A = in_proj_weight[ : config.hidden_size, : ] _A = in_proj_bias[: config.hidden_size] _A = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _A = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _A = in_proj_weight[ -config.hidden_size :, : ] _A = in_proj_bias[-config.hidden_size :] def _snake_case ( _snake_case : Tuple ) -> str: '''simple docstring''' _A = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(_snake_case , _snake_case ) def _snake_case ( _snake_case : Dict , _snake_case : str , _snake_case : Tuple ) -> str: '''simple docstring''' _A = dct.pop(_snake_case ) _A = val @torch.no_grad() def _snake_case ( _snake_case : List[str] , _snake_case : Dict ) -> List[str]: '''simple docstring''' _A = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=_snake_case ) _A = False _A = False _A = False _A = False if "vqa" in checkpoint_url: _A = True _A = 31_29 _A = 'huggingface/label-files' _A = 'vqa2-id2label.json' _A = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type='dataset' ) , 'r' ) ) _A = {int(_snake_case ): v for k, v in idalabel.items()} _A = idalabel _A = {v: k for k, v in idalabel.items()} _A = ViltForQuestionAnswering(_snake_case ) elif "nlvr" in checkpoint_url: _A = True _A = 2 _A = {0: 'False', 1: 'True'} _A = {v: k for k, v in config.idalabel.items()} _A = 3 _A = ViltForImagesAndTextClassification(_snake_case ) elif "irtr" in checkpoint_url: _A = True _A = ViltForImageAndTextRetrieval(_snake_case ) elif "mlm_itm" in checkpoint_url: _A = True _A = ViltForMaskedLM(_snake_case ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys _A = torch.hub.load_state_dict_from_url(_snake_case , map_location='cpu' )['state_dict'] _A = create_rename_keys(_snake_case , _snake_case , _snake_case , _snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) read_in_q_k_v(_snake_case , _snake_case ) if mlm_model or irtr_model: _A = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(_snake_case , _snake_case ) # load state dict into HuggingFace model model.eval() if mlm_model: _A , _A = model.load_state_dict(_snake_case , strict=_snake_case ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(_snake_case ) # Define processor _A = ViltImageProcessor(size=3_84 ) _A = BertTokenizer.from_pretrained('bert-base-uncased' ) _A = ViltProcessor(_snake_case , _snake_case ) # Forward pass on example inputs (image + text) if nlvr_model: _A = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=_snake_case ).raw ) _A = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=_snake_case ).raw ) _A = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) _A = processor(_snake_case , _snake_case , return_tensors='pt' ) _A = processor(_snake_case , _snake_case , return_tensors='pt' ) _A = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: _A = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=_snake_case ).raw ) if mlm_model: _A = 'a bunch of [MASK] laying on a [MASK].' else: _A = 'How many cats are there?' _A = processor(_snake_case , _snake_case , return_tensors='pt' ) _A = model(**_snake_case ) # Verify outputs if mlm_model: _A = torch.Size([1, 11, 3_05_22] ) _A = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , _snake_case , atol=1E-4 ) # verify masked token prediction equals "cats" _A = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: _A = torch.Size([1, 31_29] ) _A = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , _snake_case , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , _snake_case , atol=1E-4 ) # verify vqa prediction equals "2" _A = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: _A = torch.Size([1, 2] ) _A = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , _snake_case , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(_snake_case ).mkdir(exist_ok=_snake_case ) print(F'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) processor.save_pretrained(_snake_case ) if __name__ == "__main__": a = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) a = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
7
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class SCREAMING_SNAKE_CASE (a__ , a__ , a__ , unittest.TestCase ): lowerCAmelCase = StableUnCLIPImgaImgPipeline lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase = frozenset([] ) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = 32 __A : List[str] = embedder_hidden_size # image encoding components __A : List[Any] = CLIPImageProcessor(crop_size=32 , size=32) torch.manual_seed(0) __A : Optional[int] = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=_UpperCAmelCase , projection_dim=_UpperCAmelCase , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , )) # regular denoising components torch.manual_seed(0) __A : Union[str, Any] = StableUnCLIPImageNormalizer(embedding_dim=_UpperCAmelCase) __A : Dict = DDPMScheduler(beta_schedule='squaredcos_cap_v2') torch.manual_seed(0) __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') torch.manual_seed(0) __A : Union[str, Any] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_UpperCAmelCase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )) torch.manual_seed(0) __A : Dict = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_UpperCAmelCase , layers_per_block=1 , upcast_attention=_UpperCAmelCase , use_linear_projection=_UpperCAmelCase , ) torch.manual_seed(0) __A : Union[str, Any] = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=_UpperCAmelCase , steps_offset=1 , ) torch.manual_seed(0) __A : Any = AutoencoderKL() __A : List[str] = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase=0 , _UpperCAmelCase=True): '''simple docstring''' if str(_UpperCAmelCase).startswith('mps'): __A : Tuple = torch.manual_seed(_UpperCAmelCase) else: __A : Any = torch.Generator(device=_UpperCAmelCase).manual_seed(_UpperCAmelCase) __A : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(_UpperCAmelCase)).to(_UpperCAmelCase) if pil_image: __A : List[Any] = input_image * 0.5 + 0.5 __A : Dict = input_image.clamp(0 , 1) __A : Optional[int] = input_image.cpu().permute(0 , 2 , 3 , 1).float().numpy() __A : Tuple = DiffusionPipeline.numpy_to_pil(_UpperCAmelCase)[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : Union[str, Any] = self.get_dummy_components() __A : Dict = StableUnCLIPImgaImgPipeline(**_UpperCAmelCase) __A : Dict = sd_pipe.to(_UpperCAmelCase) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase) __A : Dict = self.get_dummy_inputs(_UpperCAmelCase) inputs.update({'image_embeds': None}) __A : Any = sd_pipe(**_UpperCAmelCase).images __A : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __A : List[Any] = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[Any] = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[str] = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=_UpperCAmelCase) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_max_difference=_UpperCAmelCase) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png') __A : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy') __A : Any = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa) pipe.to(_UpperCAmelCase) pipe.set_progress_bar_config(disable=_UpperCAmelCase) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __A : Optional[Any] = torch.Generator(device='cpu').manual_seed(0) __A : Dict = pipe(_UpperCAmelCase , 'anime turle' , generator=_UpperCAmelCase , output_type='np') __A : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_UpperCAmelCase , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png') __A : List[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy') __A : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa) pipe.to(_UpperCAmelCase) pipe.set_progress_bar_config(disable=_UpperCAmelCase) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __A : str = torch.Generator(device='cpu').manual_seed(0) __A : Any = pipe(_UpperCAmelCase , 'anime turle' , generator=_UpperCAmelCase , output_type='np') __A : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_UpperCAmelCase , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png') torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __A : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa) __A : int = pipe.to(_UpperCAmelCase) pipe.set_progress_bar_config(disable=_UpperCAmelCase) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __A : Optional[int] = pipe( _UpperCAmelCase , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) __A : Optional[int] = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
8
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
0
import argparse from collections import defaultdict def A ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Any: A__ = f'''{file}_{class_name}_{test_name}''' done_test[_id] += 1 with open(__UpperCamelCase , 'r' ) as f: A__ = f.readlines() A__ = f'''class {class_name}(''' A__ = f'''{4 * " "}def {test_name}(''' A__ = f'''{8 * " "}{correct_line.split()[0]}''' A__ = f'''{16 * " "}{correct_line.split()[0]}''' A__ = False A__ = False A__ = False A__ = False A__ = 0 A__ = 0 A__ = [] for line in lines: if line.startswith(__UpperCamelCase ): A__ = True elif in_class and line.startswith(__UpperCamelCase ): A__ = True elif in_class and in_func and (line.startswith(__UpperCamelCase ) or line.startswith(__UpperCamelCase )): A__ = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: A__ = True if in_class and in_func and in_line: if ")" not in line: continue else: A__ = True if in_class and in_func and in_line and insert_line: new_lines.append(f'''{spaces * " "}{correct_line}''' ) A__ = A__ = A__ = A__ = False else: new_lines.append(__UpperCamelCase ) with open(__UpperCamelCase , 'w' ) as f: for line in new_lines: f.write(__UpperCamelCase ) def A ( __UpperCamelCase , __UpperCamelCase=None ) -> str: if fail is not None: with open(__UpperCamelCase , 'r' ) as f: A__ = {l.strip() for l in f.readlines()} else: A__ = None with open(__UpperCamelCase , 'r' ) as f: A__ = f.readlines() A__ = defaultdict(__UpperCamelCase ) for line in correct_lines: A__ , A__ , A__ , A__ = line.split(';' ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''') parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None) SCREAMING_SNAKE_CASE__ = parser.parse_args() main(args.correct_filename, args.fail_filename)
9
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
0
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class lowerCAmelCase_ ( __lowercase, unittest.TestCase ): UpperCAmelCase = CpmAntTokenizer UpperCAmelCase = False def UpperCamelCase_ ( self : List[str] ): super().setUp() _UpperCamelCase = [ '''<d>''', '''</d>''', '''<s>''', '''</s>''', '''</_>''', '''<unk>''', '''<pad>''', '''</n>''', '''我''', '''是''', '''C''', '''P''', '''M''', '''A''', '''n''', '''t''', ] _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] ) ) @tooslow def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = CpmAntTokenizer.from_pretrained('''openbmb/cpm-ant-10b''' ) _UpperCamelCase = '''今天天气真好!''' _UpperCamelCase = ['''今天''', '''天气''', '''真''', '''好''', '''!'''] _UpperCamelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) _UpperCamelCase = '''今天天气真好!''' _UpperCamelCase = [tokenizer.bos_token] + tokens _UpperCamelCase = [6, 9802, 1_4962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , _A ) _UpperCamelCase = tokenizer.decode(_A ) self.assertEqual(_A , _A )
10
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
'''simple docstring''' import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "vocab_file": "vocab.txt", "merges_file": "bpe.codes", } lowercase_ = { "vocab_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt", }, "merges_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes", }, } lowercase_ = { "vinai/phobert-base": 256, "vinai/phobert-large": 256, } def lowerCAmelCase (__A): """simple docstring""" _a = set() _a = word[0] for char in word[1:]: pairs.add((prev_char, char)) _a = char _a = set(__A) return pairs class __A ( A ): '''simple docstring''' __lowerCamelCase : Optional[Any] = VOCAB_FILES_NAMES __lowerCamelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self , A , A , A="<s>" , A="</s>" , A="</s>" , A="<s>" , A="<unk>" , A="<pad>" , A="<mask>" , **A , ) -> Optional[Any]: """simple docstring""" super().__init__( bos_token=A , eos_token=A , unk_token=A , sep_token=A , cls_token=A , pad_token=A , mask_token=A , **A , ) _a = vocab_file _a = merges_file _a = {} _a = 0 _a = 1 _a = 2 _a = 3 self.add_from_file(A ) _a = {v: k for k, v in self.encoder.items()} with open(A , encoding='''utf-8''' ) as merges_handle: _a = merges_handle.read().split('''\n''' )[:-1] _a = [tuple(merge.split()[:-1] ) for merge in merges] _a = dict(zip(A , range(len(A ) ) ) ) _a = {} def a__ (self , A , A = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a = [self.cls_token_id] _a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def a__ (self , A , A = None , A = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A , token_ids_a=A , already_has_special_tokens=A ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def a__ (self , A , A = None ) -> List[int]: """simple docstring""" _a = [self.sep_token_id] _a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def a__ (self ) -> Union[str, Any]: """simple docstring""" return len(self.encoder ) def a__ (self ) -> Union[str, Any]: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def a__ (self , A ) -> Tuple: """simple docstring""" if token in self.cache: return self.cache[token] _a = tuple(A ) _a = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _a = get_pairs(A ) if not pairs: return token while True: _a = min(A , key=lambda A : self.bpe_ranks.get(A , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _a , _a = bigram _a = [] _a = 0 while i < len(A ): try: _a = word.index(A , A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _a = j if word[i] == first and i < len(A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _a = tuple(A ) _a = new_word if len(A ) == 1: break else: _a = get_pairs(A ) _a = '''@@ '''.join(A ) _a = word[:-4] _a = word return word def a__ (self , A ) -> str: """simple docstring""" _a = [] _a = re.findall(R'''\S+\n?''' , A ) for token in words: split_tokens.extend(list(self.bpe(A ).split(''' ''' ) ) ) return split_tokens def a__ (self , A ) -> Dict: """simple docstring""" return self.encoder.get(A , self.encoder.get(self.unk_token ) ) def a__ (self , A ) -> Any: """simple docstring""" return self.decoder.get(A , self.unk_token ) def a__ (self , A ) -> int: """simple docstring""" _a = ''' '''.join(A ).replace('''@@ ''' , '''''' ).strip() return out_string def a__ (self , A , A = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return _a = os.path.join( A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _a = os.path.join( A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ): copyfile(self.vocab_file , A ) if os.path.abspath(self.merges_file ) != os.path.abspath(A ): copyfile(self.merges_file , A ) return out_vocab_file, out_merge_file def a__ (self , A ) -> List[Any]: """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(f'''Incorrect encoding detected in {f}, please rebuild the dataset''' ) return _a = f.readlines() for lineTmp in lines: _a = lineTmp.strip() _a = line.rfind(''' ''' ) if idx == -1: raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt>\'''' ) _a = line[:idx] _a = len(self.encoder )
11
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase__ : Optional[Any] = { """s-JoL/Open-Llama-V1""": """https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json""", } class _snake_case ( UpperCAmelCase_ ): __lowerCAmelCase : int = 'open-llama' def __init__( self , SCREAMING_SNAKE_CASE_=10_00_00 , SCREAMING_SNAKE_CASE_=40_96 , SCREAMING_SNAKE_CASE_=1_10_08 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_="silu" , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=0.0_2 , SCREAMING_SNAKE_CASE_=1E-6 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): '''simple docstring''' lowercase__ : str = vocab_size lowercase__ : Tuple = max_position_embeddings lowercase__ : Tuple = hidden_size lowercase__ : Tuple = intermediate_size lowercase__ : Any = num_hidden_layers lowercase__ : Tuple = num_attention_heads lowercase__ : Any = hidden_act lowercase__ : Optional[int] = initializer_range lowercase__ : Union[str, Any] = rms_norm_eps lowercase__ : Optional[Any] = use_cache lowercase__ : Dict = kwargs.pop( """use_memorry_efficient_attention""" , SCREAMING_SNAKE_CASE_) lowercase__ : Dict = hidden_dropout_prob lowercase__ : Optional[int] = attention_dropout_prob lowercase__ : Optional[int] = use_stable_embedding lowercase__ : Dict = shared_input_output_embedding lowercase__ : str = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def lowercase__ ( self): '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE_) or len(self.rope_scaling) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ f'got {self.rope_scaling}') lowercase__ : int = self.rope_scaling.get("""type""" , SCREAMING_SNAKE_CASE_) lowercase__ : Optional[int] = self.rope_scaling.get("""factor""" , SCREAMING_SNAKE_CASE_) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}') if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}')
12
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
0
'''simple docstring''' def UpperCAmelCase__ ( UpperCAmelCase_ : str ) -> str: return "".join(chr(ord(UpperCAmelCase_ ) - 32 ) if 'a' <= char <= 'z' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
13
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
0
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : str = FunnelTokenizer UpperCAmelCase__ : List[str] = FunnelTokenizerFast UpperCAmelCase__ : List[str] = True UpperCAmelCase__ : Union[str, Any] = True def __lowercase ( self ) -> Tuple: super().setUp() _a : str = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] _a : str = 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 , **_a ) -> Union[str, Any]: return FunnelTokenizer.from_pretrained(self.tmpdirname , **_a ) def __lowercase ( self , **_a ) -> Dict: return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def __lowercase ( self , _a ) -> Any: _a : Dict = '''UNwant\u00E9d,running''' _a : Tuple = '''unwanted, running''' return input_text, output_text def __lowercase ( self ) -> int: _a : Any = self.tokenizer_class(self.vocab_file ) _a : Optional[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_a , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 1_0, 8, 9] ) def __lowercase ( self ) -> Tuple: _a : int = self.get_tokenizers(do_lower_case=_a ) for tokenizer in tokenizers: _a : Any = tokenizer('''UNwant\u00E9d,running''' ) _a : Optional[int] = len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) _a : Tuple = tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
14
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class A ( unittest.TestCase ): '''simple docstring''' @slow def lowerCamelCase__ (self : Any ) -> int: """simple docstring""" lowercase__ = XLMRobertaModel.from_pretrained("""xlm-roberta-base""" ) lowercase__ = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]] ) # The dog is cute and lives in the garden house lowercase__ = torch.Size((1, 12, 768) ) # batch_size, sequence_length, embedding_vector_dim lowercase__ = torch.tensor( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): lowercase__ = model(_UpperCAmelCase )["""last_hidden_state"""].detach() self.assertEqual(output.shape , _UpperCAmelCase ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , _UpperCAmelCase , atol=1E-3 ) ) @slow def lowerCamelCase__ (self : Tuple ) -> Any: """simple docstring""" lowercase__ = XLMRobertaModel.from_pretrained("""xlm-roberta-large""" ) lowercase__ = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]] ) # The dog is cute and lives in the garden house lowercase__ = torch.Size((1, 12, 1024) ) # batch_size, sequence_length, embedding_vector_dim lowercase__ = torch.tensor( [[-0.0_699, -0.0_318, 0.0_705, -0.1_241, 0.0_999, -0.0_520, 0.1_004, -0.1_838, -0.4_704, 0.1_437, 0.0_821, 0.0_126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): lowercase__ = model(_UpperCAmelCase )["""last_hidden_state"""].detach() self.assertEqual(output.shape , _UpperCAmelCase ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , _UpperCAmelCase , atol=1E-3 ) )
15
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "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 SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
from __future__ import annotations __A : str = list[tuple[int, int]] __A : Optional[int] = [ [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], ] __A : List[str] = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : float , __lowerCamelCase : Node | None , ): SCREAMING_SNAKE_CASE = pos_x SCREAMING_SNAKE_CASE = pos_y SCREAMING_SNAKE_CASE = (pos_y, pos_x) SCREAMING_SNAKE_CASE = goal_x SCREAMING_SNAKE_CASE = goal_y SCREAMING_SNAKE_CASE = g_cost SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = self.calculate_heuristic() def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = abs(self.pos_x - self.goal_x ) SCREAMING_SNAKE_CASE = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self : Union[str, Any] , __lowerCamelCase : List[Any] ): return self.f_cost < other.f_cost class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[int] , __lowerCamelCase : tuple[int, int] , __lowerCamelCase : tuple[int, int] ): SCREAMING_SNAKE_CASE = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __lowerCamelCase ) SCREAMING_SNAKE_CASE = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , __lowerCamelCase ) SCREAMING_SNAKE_CASE = [self.start] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = False def _snake_case ( self : Optional[Any] ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() SCREAMING_SNAKE_CASE = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: SCREAMING_SNAKE_CASE = True return self.retrace_path(__lowerCamelCase ) self.closed_nodes.append(__lowerCamelCase ) SCREAMING_SNAKE_CASE = self.get_successors(__lowerCamelCase ) 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(__lowerCamelCase ) else: # retrieve the best current path SCREAMING_SNAKE_CASE = self.open_nodes.pop(self.open_nodes.index(__lowerCamelCase ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(__lowerCamelCase ) else: self.open_nodes.append(__lowerCamelCase ) if not self.reached: return [self.start.pos] return None def _snake_case ( self : List[Any] , __lowerCamelCase : Node ): SCREAMING_SNAKE_CASE = [] for action in delta: SCREAMING_SNAKE_CASE = parent.pos_x + action[1] SCREAMING_SNAKE_CASE = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__lowerCamelCase ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( __lowerCamelCase , __lowerCamelCase , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __lowerCamelCase , ) ) return successors def _snake_case ( self : str , __lowerCamelCase : Node | None ): SCREAMING_SNAKE_CASE = node SCREAMING_SNAKE_CASE = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) SCREAMING_SNAKE_CASE = current_node.parent path.reverse() return path if __name__ == "__main__": __A : Optional[Any] = (0, 0) __A : Optional[int] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') __A : List[str] = GreedyBestFirst(init, goal) __A : Tuple = greedy_bf.search() if path: for pos_x, pos_y in path: __A : Optional[Any] = 2 for elem in grid: print(elem)
16
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
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 __SCREAMING_SNAKE_CASE ( a__ : Dataset ,a__ : Dict[str, str] ) -> Union[str, Any]: __A : Union[str, Any] = args.log_outputs __A : List[Any] = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric __A : List[Any] = load_metric("""wer""" ) __A : List[str] = load_metric("""cer""" ) # compute metrics __A : int = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) __A : Any = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results __A : List[Any] = f"""WER: {wer_result}\nCER: {cer_result}""" print(a__ ) with open(f"""{dataset_id}_eval_results.txt""" ,"""w""" ) as f: f.write(a__ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: __A : int = f"""log_{dataset_id}_predictions.txt""" __A : Union[str, Any] = f"""log_{dataset_id}_targets.txt""" with open(a__ ,"""w""" ) as p, open(a__ ,"""w""" ) as t: # mapping function to write output def write_to_file(a__ : Dict ,a__ : str ): p.write(f"""{i}""" + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f"""{i}""" + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(a__ ,with_indices=a__ ) def __SCREAMING_SNAKE_CASE ( a__ : str ) -> str: __A : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training __A : List[Any] = re.sub(a__ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! __A : int = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: __A : str = """ """.join(text.split(a__ ) ) return text def __SCREAMING_SNAKE_CASE ( a__ : Dict ) -> Optional[Any]: # load dataset __A : Optional[Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=a__ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor __A : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) __A : Any = feature_extractor.sampling_rate # resample audio __A : Optional[int] = dataset.cast_column("""audio""" ,Audio(sampling_rate=a__ ) ) # load eval pipeline if args.device is None: __A : List[str] = 0 if torch.cuda.is_available() else -1 __A : str = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(a__ : Tuple ): __A : int = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) __A : Optional[int] = prediction["""text"""] __A : int = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples __A : List[str] = dataset.map(a__ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(a__ ,a__ ) if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = 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.''', ) UpperCAmelCase_ : int = parser.parse_args() main(args)
17
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class lowerCAmelCase_ ( __magic_name__ ,__magic_name__ ): __lowerCamelCase : Optional[int] = "maskformer-swin" __lowerCamelCase : Optional[Any] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , _lowerCAmelCase=224 , _lowerCAmelCase=4 , _lowerCAmelCase=3 , _lowerCAmelCase=96 , _lowerCAmelCase=[2, 2, 6, 2] , _lowerCAmelCase=[3, 6, 12, 24] , _lowerCAmelCase=7 , _lowerCAmelCase=4.0 , _lowerCAmelCase=True , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.1 , _lowerCAmelCase="gelu" , _lowerCAmelCase=False , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-5 , _lowerCAmelCase=None , _lowerCAmelCase=None , **_lowerCAmelCase , ) -> Any: super().__init__(**_lowerCAmelCase ) _lowerCAmelCase = image_size _lowerCAmelCase = patch_size _lowerCAmelCase = num_channels _lowerCAmelCase = embed_dim _lowerCAmelCase = depths _lowerCAmelCase = len(_lowerCAmelCase ) _lowerCAmelCase = num_heads _lowerCAmelCase = window_size _lowerCAmelCase = mlp_ratio _lowerCAmelCase = qkv_bias _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = drop_path_rate _lowerCAmelCase = hidden_act _lowerCAmelCase = use_absolute_embeddings _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase = int(embed_dim * 2 ** (len(_lowerCAmelCase ) - 1) ) _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 )
18
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
0
"""simple docstring""" _a = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ _a = [{"""type""": """code""", """content""": INSTALL_CONTENT}] _a = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
19
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
0
from __future__ import annotations import string from itertools import cycle, product from pathlib import Path _lowerCAmelCase: str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) _lowerCAmelCase: list[int] = [ord(letter) for letter in string.ascii_lowercase] _lowerCAmelCase: set[int] = {ord(char) for char in VALID_CHARS} _lowerCAmelCase: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def _lowercase( __a : list[int] , __a : tuple[int, ...] ): a__ ="" a__ =42 a__ =42 a__ =42 for keychar, cipherchar in zip(cycle(__a ) , __a ): a__ =cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(__a ) return decoded def _lowercase( __a : list[int] ): a__ =[] for key in product(__a , repeat=3 ): a__ =try_key(__a , __a ) if encoded is not None: possibles.append(__a ) return possibles def _lowercase( __a : list[str] , __a : str ): return [possible for possible in possibles if common_word in possible.lower()] def _lowercase( __a : str = "p059_cipher.txt" ): a__ =42 a__ =42 a__ =42 a__ =42 a__ =Path(__a ).parent.joinpath(__a ).read_text(encoding='utf-8' ) a__ =[int(__a ) for number in data.strip().split(',' )] a__ =filter_valid_chars(__a ) for common_word in COMMON_WORDS: a__ =filter_common_word(__a , __a ) if len(__a ) == 1: break a__ =possibles[0] return sum(ord(__a ) for char in decoded_text ) if __name__ == "__main__": print(F"""{solution() = }""")
20
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = 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 : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
0
def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase ): if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) __magic_name__ : str =str(bin(lowerCamelCase ) )[2:] # remove the leading "0b" __magic_name__ : str =str(bin(lowerCamelCase ) )[2:] # remove the leading "0b" __magic_name__ : Optional[int] =max(len(lowerCamelCase ) , len(lowerCamelCase ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase ) , b_binary.zfill(lowerCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
21
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _snake_case : Any = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class A ( _a ): lowercase_ = 'albert' def __init__( self : List[str] , lowerCAmelCase_ : Tuple=3_00_00 , lowerCAmelCase_ : Dict=1_28 , lowerCAmelCase_ : str=40_96 , lowerCAmelCase_ : int=12 , lowerCAmelCase_ : Dict=1 , lowerCAmelCase_ : Tuple=64 , lowerCAmelCase_ : Union[str, Any]=1_63_84 , lowerCAmelCase_ : Dict=1 , lowerCAmelCase_ : Union[str, Any]="gelu_new" , lowerCAmelCase_ : List[str]=0 , lowerCAmelCase_ : int=0 , lowerCAmelCase_ : Dict=5_12 , lowerCAmelCase_ : Any=2 , lowerCAmelCase_ : Any=0.0_2 , lowerCAmelCase_ : Tuple=1e-12 , lowerCAmelCase_ : Union[str, Any]=0.1 , lowerCAmelCase_ : Union[str, Any]="absolute" , lowerCAmelCase_ : Any=0 , lowerCAmelCase_ : List[str]=2 , lowerCAmelCase_ : Dict=3 , **lowerCAmelCase_ : Any , ) -> Optional[Any]: """simple docstring""" super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) _a = vocab_size _a = embedding_size _a = hidden_size _a = num_hidden_layers _a = num_hidden_groups _a = num_attention_heads _a = inner_group_num _a = hidden_act _a = intermediate_size _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = initializer_range _a = layer_norm_eps _a = classifier_dropout_prob _a = position_embedding_type class A ( _a ): @property def __lowerCAmelCase ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": _a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
22
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
0
import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") snake_case__ : List[str] = logging.getLogger(__name__) @dataclass class _a : """simple docstring""" A_ = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) A_ = field( default=UpperCAmelCase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) A_ = field( default=UpperCAmelCase__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) A_ = field( default=UpperCAmelCase__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) A_ = field( default=UpperCAmelCase__ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) A_ = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) A_ = field( default=UpperCAmelCase__ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) @dataclass class _a : """simple docstring""" A_ = field(default=UpperCAmelCase__ , metadata={"""help""": """The input training data file (a text file)."""} ) A_ = field( default=UpperCAmelCase__ , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , ) A_ = field( default=UpperCAmelCase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) A_ = field( default=UpperCAmelCase__ , metadata={"""help""": """The number of processes to use for the preprocessing."""} , ) A_ = field( default=UpperCAmelCase__ , metadata={ """help""": ( """The maximum total input sequence length after tokenization. If passed, sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) A_ = field( default=UpperCAmelCase__ , metadata={ """help""": ( """Whether to pad all samples to the maximum sentence length. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch. More """ """efficient on GPU but very bad for TPU.""" ) } , ) A_ = field( default=UpperCAmelCase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) A_ = field( default=UpperCAmelCase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def _UpperCAmelCase ( self ) -> Union[str, Any]: if self.train_file is not None: UpperCamelCase_ = self.train_file.split('.' )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: UpperCamelCase_ = self.validation_file.split('.' )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class _a : """simple docstring""" A_ = 42 A_ = True A_ = None A_ = None def __call__( self , _UpperCAmelCase ) -> List[Any]: UpperCamelCase_ = 'label' if 'label' in features[0].keys() else 'labels' UpperCamelCase_ = [feature.pop(_UpperCAmelCase ) for feature in features] UpperCamelCase_ = len(_UpperCAmelCase ) UpperCamelCase_ = len(features[0]['input_ids'] ) UpperCamelCase_ = [ [{k: v[i] for k, v in feature.items()} for i in range(_UpperCAmelCase )] for feature in features ] UpperCamelCase_ = list(chain(*_UpperCAmelCase ) ) UpperCamelCase_ = self.tokenizer.pad( _UpperCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , ) # Un-flatten UpperCamelCase_ = {k: v.view(_UpperCAmelCase , _UpperCAmelCase , -1 ) for k, v in batch.items()} # Add back labels UpperCamelCase_ = torch.tensor(_UpperCAmelCase , dtype=torch.intaa ) return batch def _snake_case (): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCamelCase_ = 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_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_swag' , __lowercase , __lowercase) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout)] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCamelCase_ = training_args.get_process_log_level() logger.setLevel(__lowercase) datasets.utils.logging.set_verbosity(__lowercase) transformers.utils.logging.set_verbosity(__lowercase) 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_ = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: UpperCamelCase_ = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.') elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.') # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: UpperCamelCase_ = {} if data_args.train_file is not None: UpperCamelCase_ = data_args.train_file if data_args.validation_file is not None: UpperCamelCase_ = data_args.validation_file UpperCamelCase_ = data_args.train_file.split('.')[-1] UpperCamelCase_ = load_dataset( __lowercase , data_files=__lowercase , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. UpperCamelCase_ = load_dataset( 'swag' , 'regular' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) UpperCamelCase_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) UpperCamelCase_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path) , config=__lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. UpperCamelCase_ = [f"""ending{i}""" for i in range(4)] UpperCamelCase_ = 'sent1' UpperCamelCase_ = 'sent2' if data_args.max_seq_length is None: UpperCamelCase_ = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( 'The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value' ' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can' ' override this default with `--block_size xxx`.') UpperCamelCase_ = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""") UpperCamelCase_ = min(data_args.max_seq_length , tokenizer.model_max_length) # Preprocessing the datasets. def preprocess_function(__lowercase): UpperCamelCase_ = [[context] * 4 for context in examples[context_name]] UpperCamelCase_ = examples[question_header_name] UpperCamelCase_ = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(__lowercase) ] # Flatten out UpperCamelCase_ = list(chain(*__lowercase)) UpperCamelCase_ = list(chain(*__lowercase)) # Tokenize UpperCamelCase_ = tokenizer( __lowercase , __lowercase , truncation=__lowercase , max_length=__lowercase , padding='max_length' if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(__lowercase) , 4)] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError('--do_train requires a train dataset') UpperCamelCase_ = raw_datasets['train'] if data_args.max_train_samples is not None: UpperCamelCase_ = min(len(__lowercase) , data_args.max_train_samples) UpperCamelCase_ = train_dataset.select(range(__lowercase)) with training_args.main_process_first(desc='train dataset map pre-processing'): UpperCamelCase_ = train_dataset.map( __lowercase , batched=__lowercase , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError('--do_eval requires a validation dataset') UpperCamelCase_ = raw_datasets['validation'] if data_args.max_eval_samples is not None: UpperCamelCase_ = min(len(__lowercase) , data_args.max_eval_samples) UpperCamelCase_ = eval_dataset.select(range(__lowercase)) with training_args.main_process_first(desc='validation dataset map pre-processing'): UpperCamelCase_ = eval_dataset.map( __lowercase , batched=__lowercase , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator UpperCamelCase_ = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=__lowercase , pad_to_multiple_of=8 if training_args.fpaa else None) ) # Metric def compute_metrics(__lowercase): UpperCamelCase_ , UpperCamelCase_ = eval_predictions UpperCamelCase_ = np.argmax(__lowercase , axis=1) return {"accuracy": (preds == label_ids).astype(np.floataa).mean().item()} # Initialize our Trainer UpperCamelCase_ = Trainer( model=__lowercase , args=__lowercase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=__lowercase , data_collator=__lowercase , compute_metrics=__lowercase , ) # Training if training_args.do_train: UpperCamelCase_ = None if training_args.resume_from_checkpoint is not None: UpperCamelCase_ = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCamelCase_ = last_checkpoint UpperCamelCase_ = trainer.train(resume_from_checkpoint=__lowercase) trainer.save_model() # Saves the tokenizer too for easy upload UpperCamelCase_ = train_result.metrics UpperCamelCase_ = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowercase) ) UpperCamelCase_ = min(__lowercase , len(__lowercase)) trainer.log_metrics('train' , __lowercase) trainer.save_metrics('train' , __lowercase) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***') UpperCamelCase_ = trainer.evaluate() UpperCamelCase_ = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowercase) UpperCamelCase_ = min(__lowercase , len(__lowercase)) trainer.log_metrics('eval' , __lowercase) trainer.save_metrics('eval' , __lowercase) UpperCamelCase_ = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'multiple-choice', 'dataset_tags': 'swag', 'dataset_args': 'regular', 'dataset': 'SWAG', 'language': 'en', } if training_args.push_to_hub: trainer.push_to_hub(**__lowercase) else: trainer.create_model_card(**__lowercase) def _snake_case (__lowercase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
23
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase_ : Tuple = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _UpperCamelCase (_lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : Optional[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] )-> Optional[int]: '''simple docstring''' for attribute in key.split('''.''' ): __snake_case = getattr(_lowerCamelCase , _lowerCamelCase ) if weight_type is not None: __snake_case = getattr(_lowerCamelCase , _lowerCamelCase ).shape else: __snake_case = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": __snake_case = value elif weight_type == "weight_g": __snake_case = value elif weight_type == "weight_v": __snake_case = value elif weight_type == "bias": __snake_case = value elif weight_type == "running_mean": __snake_case = value elif weight_type == "running_var": __snake_case = value elif weight_type == "num_batches_tracked": __snake_case = value elif weight_type == "inv_freq": __snake_case = value else: __snake_case = value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _UpperCamelCase (_lowerCamelCase : Any , _lowerCamelCase : Tuple , _lowerCamelCase : str )-> int: '''simple docstring''' __snake_case = [] __snake_case = fairseq_model.state_dict() __snake_case = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __snake_case = False if "conv_layers" in name: load_conv_layer( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , hf_model.config.feat_extract_norm == '''group''' , ) __snake_case = True else: for key, mapped_key in MAPPING.items(): __snake_case = '''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __snake_case = True if "*" in mapped_key: __snake_case = name.split(_lowerCamelCase )[0].split('''.''' )[-2] __snake_case = mapped_key.replace('''*''' , _lowerCamelCase ) if "pos_bias_u" in name: __snake_case = None elif "pos_bias_v" in name: __snake_case = None elif "weight_g" in name: __snake_case = '''weight_g''' elif "weight_v" in name: __snake_case = '''weight_v''' elif "bias" in name: __snake_case = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __snake_case = '''weight''' elif "running_mean" in name: __snake_case = '''running_mean''' elif "inv_freq" in name: __snake_case = '''inv_freq''' elif "running_var" in name: __snake_case = '''running_var''' elif "num_batches_tracked" in name: __snake_case = '''num_batches_tracked''' else: __snake_case = None set_recursively(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) continue if not is_used: unused_weights.append(_lowerCamelCase ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _UpperCamelCase (_lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : List[str] )-> Optional[Any]: '''simple docstring''' __snake_case = full_name.split('''conv_layers.''' )[-1] __snake_case = name.split('''.''' ) __snake_case = int(items[0] ) __snake_case = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) __snake_case = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) __snake_case = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) __snake_case = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) __snake_case = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(_lowerCamelCase ) @torch.no_grad() def _UpperCamelCase (_lowerCamelCase : List[Any] , _lowerCamelCase : int , _lowerCamelCase : int=None , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : str=True )-> Optional[Any]: '''simple docstring''' if config_path is not None: __snake_case = WavaVecaConformerConfig.from_pretrained(_lowerCamelCase , hidden_act='''swish''' ) else: __snake_case = WavaVecaConformerConfig() if "rope" in checkpoint_path: __snake_case = '''rotary''' if is_finetuned: if dict_path: __snake_case = Dictionary.load(_lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __snake_case = target_dict.pad_index __snake_case = target_dict.bos_index __snake_case = target_dict.eos_index __snake_case = len(target_dict.symbols ) __snake_case = os.path.join(_lowerCamelCase , '''vocab.json''' ) if not os.path.isdir(_lowerCamelCase ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(_lowerCamelCase ) ) return os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) __snake_case = target_dict.indices # fairseq has the <pad> and <s> switched __snake_case = 0 __snake_case = 1 with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(_lowerCamelCase , _lowerCamelCase ) __snake_case = WavaVecaCTCTokenizer( _lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=_lowerCamelCase , ) __snake_case = True if config.feat_extract_norm == '''layer''' else False __snake_case = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=_lowerCamelCase , return_attention_mask=_lowerCamelCase , ) __snake_case = WavaVecaProcessor(feature_extractor=_lowerCamelCase , tokenizer=_lowerCamelCase ) processor.save_pretrained(_lowerCamelCase ) __snake_case = WavaVecaConformerForCTC(_lowerCamelCase ) else: __snake_case = WavaVecaConformerForPreTraining(_lowerCamelCase ) if is_finetuned: __snake_case , __snake_case , __snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __snake_case = argparse.Namespace(task='''audio_pretraining''' ) __snake_case = fairseq.tasks.setup_task(_lowerCamelCase ) __snake_case , __snake_case , __snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_lowerCamelCase ) __snake_case = model[0].eval() recursively_load_weights(_lowerCamelCase , _lowerCamelCase , not is_finetuned ) hf_wavavec.save_pretrained(_lowerCamelCase ) if __name__ == "__main__": UpperCAmelCase_ : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase_ : int = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
24
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
0
def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Optional[int] = [0] * len(_a) for i in range(1 , len(_a)): # use last results for better performance - dynamic programming SCREAMING_SNAKE_CASE : Dict = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: SCREAMING_SNAKE_CASE : List[str] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 SCREAMING_SNAKE_CASE : List[Any] = j return prefix_result def lowerCamelCase__ ( _a): return max(prefix_function(_a)) if __name__ == "__main__": import doctest doctest.testmod()
25
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) class _A ( __lowercase ): lowercase__: Any = '''encoder-decoder''' lowercase__: str = True def __init__( self : str , **__magic_name__ : int ) -> str: """simple docstring""" super().__init__(**__magic_name__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" __snake_case : Any = kwargs.pop("""encoder""" ) __snake_case : Union[str, Any] = encoder_config.pop("""model_type""" ) __snake_case : Optional[int] = kwargs.pop("""decoder""" ) __snake_case : Dict = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig __snake_case : Optional[Any] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) __snake_case : Optional[Any] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) __snake_case : List[str] = True @classmethod def lowercase__ ( cls : Optional[Any] , __magic_name__ : PretrainedConfig , __magic_name__ : PretrainedConfig , **__magic_name__ : Dict ) -> PretrainedConfig: """simple docstring""" logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) __snake_case : List[Any] = True __snake_case : Any = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__magic_name__ ) def lowercase__ ( self : Optional[int] ) -> str: """simple docstring""" __snake_case : Union[str, Any] = copy.deepcopy(self.__dict__ ) __snake_case : int = self.encoder.to_dict() __snake_case : List[str] = self.decoder.to_dict() __snake_case : Tuple = self.__class__.model_type return output
26
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
0
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __A : List[Any] = "." if __name__ == "__main__": __A : Tuple = os.path.join(REPO_PATH, "utils/documentation_tests.txt") __A : Union[str, Any] = [] __A : Optional[int] = [] with open(doctest_file_path) as fp: for line in fp: __A : Dict = line.strip() __A : int = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: __A : List[Any] = "\n".join(non_existent_paths) raise ValueError(f"`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}") if all_paths != sorted(all_paths): raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")
27
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
0
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def lowercase__( __UpperCamelCase: Optional[int] ,__UpperCamelCase: List[Any] ,__UpperCamelCase: Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 0 if start < end: SCREAMING_SNAKE_CASE : Dict = randint(__UpperCamelCase ,__UpperCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = a[end] SCREAMING_SNAKE_CASE : Dict = a[pivot] SCREAMING_SNAKE_CASE : str = temp SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = _in_place_partition(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) count += _in_place_quick_sort(__UpperCamelCase ,__UpperCamelCase ,p - 1 ) count += _in_place_quick_sort(__UpperCamelCase ,p + 1 ,__UpperCamelCase ) return count def lowercase__( __UpperCamelCase: Optional[Any] ,__UpperCamelCase: Tuple ,__UpperCamelCase: Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Optional[int] = randint(__UpperCamelCase ,__UpperCamelCase ) SCREAMING_SNAKE_CASE : str = a[end] SCREAMING_SNAKE_CASE : int = a[pivot] SCREAMING_SNAKE_CASE : int = temp SCREAMING_SNAKE_CASE : str = start - 1 for index in range(__UpperCamelCase ,__UpperCamelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value SCREAMING_SNAKE_CASE : Any = new_pivot_index + 1 SCREAMING_SNAKE_CASE : Tuple = a[new_pivot_index] SCREAMING_SNAKE_CASE : Tuple = a[index] SCREAMING_SNAKE_CASE : str = temp SCREAMING_SNAKE_CASE : List[Any] = a[new_pivot_index + 1] SCREAMING_SNAKE_CASE : Tuple = a[end] SCREAMING_SNAKE_CASE : Optional[int] = temp return new_pivot_index + 1, count UpperCamelCase_ = TemporaryFile() UpperCamelCase_ = 1_0_0 # 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)
28
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 snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
0
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig A_ = logging.get_logger(__name__) # General docstring A_ = """ResNetConfig""" # Base docstring A_ = """microsoft/resnet-50""" A_ = [1, 2048, 7, 7] # Image classification docstring A_ = """microsoft/resnet-50""" A_ = """tiger cat""" A_ = [ """microsoft/resnet-50""", # See all resnet models at https://huggingface.co/models?filter=resnet ] class __lowerCamelCase ( nn.Module ): def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 3 , UpperCAmelCase = 1 , UpperCAmelCase = "relu" ): super().__init__() lowerCamelCase_ = nn.Convad( UpperCAmelCase , UpperCAmelCase , kernel_size=UpperCAmelCase , stride=UpperCAmelCase , padding=kernel_size // 2 , bias=UpperCAmelCase ) lowerCamelCase_ = nn.BatchNormad(UpperCAmelCase ) lowerCamelCase_ = ACTaFN[activation] if activation is not None else nn.Identity() def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = self.convolution(UpperCAmelCase ) lowerCamelCase_ = self.normalization(UpperCAmelCase ) lowerCamelCase_ = self.activation(UpperCAmelCase ) return hidden_state class __lowerCamelCase ( nn.Module ): def __init__( self , UpperCAmelCase ): super().__init__() lowerCamelCase_ = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) lowerCamelCase_ = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) lowerCamelCase_ = config.num_channels def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) lowerCamelCase_ = self.embedder(UpperCAmelCase ) lowerCamelCase_ = self.pooler(UpperCAmelCase ) return embedding class __lowerCamelCase ( nn.Module ): def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 2 ): super().__init__() lowerCamelCase_ = nn.Convad(UpperCAmelCase , UpperCAmelCase , kernel_size=1 , stride=UpperCAmelCase , bias=UpperCAmelCase ) lowerCamelCase_ = nn.BatchNormad(UpperCAmelCase ) def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = self.convolution(UpperCAmelCase ) lowerCamelCase_ = self.normalization(UpperCAmelCase ) return hidden_state class __lowerCamelCase ( nn.Module ): def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 1 , UpperCAmelCase = "relu" ): super().__init__() lowerCamelCase_ = in_channels != out_channels or stride != 1 lowerCamelCase_ = ( ResNetShortCut(UpperCAmelCase , UpperCAmelCase , stride=UpperCAmelCase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase_ = nn.Sequential( ResNetConvLayer(UpperCAmelCase , UpperCAmelCase , stride=UpperCAmelCase ) , ResNetConvLayer(UpperCAmelCase , UpperCAmelCase , activation=UpperCAmelCase ) , ) lowerCamelCase_ = ACTaFN[activation] def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = hidden_state lowerCamelCase_ = self.layer(UpperCAmelCase ) lowerCamelCase_ = self.shortcut(UpperCAmelCase ) hidden_state += residual lowerCamelCase_ = self.activation(UpperCAmelCase ) return hidden_state class __lowerCamelCase ( nn.Module ): def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 1 , UpperCAmelCase = "relu" , UpperCAmelCase = 4 ): super().__init__() lowerCamelCase_ = in_channels != out_channels or stride != 1 lowerCamelCase_ = out_channels // reduction lowerCamelCase_ = ( ResNetShortCut(UpperCAmelCase , UpperCAmelCase , stride=UpperCAmelCase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase_ = nn.Sequential( ResNetConvLayer(UpperCAmelCase , UpperCAmelCase , kernel_size=1 ) , ResNetConvLayer(UpperCAmelCase , UpperCAmelCase , stride=UpperCAmelCase ) , ResNetConvLayer(UpperCAmelCase , UpperCAmelCase , kernel_size=1 , activation=UpperCAmelCase ) , ) lowerCamelCase_ = ACTaFN[activation] def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = hidden_state lowerCamelCase_ = self.layer(UpperCAmelCase ) lowerCamelCase_ = self.shortcut(UpperCAmelCase ) hidden_state += residual lowerCamelCase_ = self.activation(UpperCAmelCase ) return hidden_state class __lowerCamelCase ( nn.Module ): def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 2 , UpperCAmelCase = 2 , ): super().__init__() lowerCamelCase_ = ResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else ResNetBasicLayer lowerCamelCase_ = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase , UpperCAmelCase , stride=UpperCAmelCase , activation=config.hidden_act ) , *[layer(UpperCAmelCase , UpperCAmelCase , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = input for layer in self.layers: lowerCamelCase_ = layer(UpperCAmelCase ) return hidden_state class __lowerCamelCase ( nn.Module ): def __init__( self , UpperCAmelCase ): super().__init__() lowerCamelCase_ = nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( UpperCAmelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) lowerCamelCase_ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(UpperCAmelCase , config.depths[1:] ): self.stages.append(ResNetStage(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , depth=UpperCAmelCase ) ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase = False , UpperCAmelCase = True ): lowerCamelCase_ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCamelCase_ = hidden_states + (hidden_state,) lowerCamelCase_ = stage_module(UpperCAmelCase ) if output_hidden_states: lowerCamelCase_ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=UpperCAmelCase , hidden_states=UpperCAmelCase , ) class __lowerCamelCase ( lowerCAmelCase ): a__: Tuple = ResNetConfig a__: Tuple = 'resnet' a__: List[Any] = 'pixel_values' a__: Union[str, Any] = True def UpperCAmelCase__ ( self , UpperCAmelCase ): if isinstance(UpperCAmelCase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode='''fan_out''' , nonlinearity='''relu''' ) elif isinstance(UpperCAmelCase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase=False ): if isinstance(UpperCAmelCase , UpperCAmelCase ): lowerCamelCase_ = value A_ = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ResNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ A_ = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare ResNet model outputting raw features without any specific head on top.' , lowerCAmelCase , ) class __lowerCamelCase ( lowerCAmelCase ): def __init__( self , UpperCAmelCase ): super().__init__(UpperCAmelCase ) lowerCamelCase_ = config lowerCamelCase_ = ResNetEmbeddings(UpperCAmelCase ) lowerCamelCase_ = ResNetEncoder(UpperCAmelCase ) lowerCamelCase_ = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None ): lowerCamelCase_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = self.embedder(UpperCAmelCase ) lowerCamelCase_ = self.encoder( UpperCAmelCase , output_hidden_states=UpperCAmelCase , return_dict=UpperCAmelCase ) lowerCamelCase_ = encoder_outputs[0] lowerCamelCase_ = self.pooler(UpperCAmelCase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase , pooler_output=UpperCAmelCase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , lowerCAmelCase , ) class __lowerCamelCase ( lowerCAmelCase ): def __init__( self , UpperCAmelCase ): super().__init__(UpperCAmelCase ) lowerCamelCase_ = config.num_labels lowerCamelCase_ = ResNetModel(UpperCAmelCase ) # classification head lowerCamelCase_ = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase__ ( self , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , ): lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = self.resnet(UpperCAmelCase , output_hidden_states=UpperCAmelCase , return_dict=UpperCAmelCase ) lowerCamelCase_ = outputs.pooler_output if return_dict else outputs[1] lowerCamelCase_ = self.classifier(UpperCAmelCase ) lowerCamelCase_ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowerCamelCase_ = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowerCamelCase_ = '''single_label_classification''' else: lowerCamelCase_ = '''multi_label_classification''' if self.config.problem_type == "regression": lowerCamelCase_ = MSELoss() if self.num_labels == 1: lowerCamelCase_ = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowerCamelCase_ = loss_fct(UpperCAmelCase , UpperCAmelCase ) elif self.config.problem_type == "single_label_classification": lowerCamelCase_ = CrossEntropyLoss() lowerCamelCase_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowerCamelCase_ = BCEWithLogitsLoss() lowerCamelCase_ = loss_fct(UpperCAmelCase , UpperCAmelCase ) if not return_dict: lowerCamelCase_ = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=UpperCAmelCase , logits=UpperCAmelCase , hidden_states=outputs.hidden_states ) @add_start_docstrings( '\n ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n ' , lowerCAmelCase , ) class __lowerCamelCase ( lowerCAmelCase , lowerCAmelCase ): def __init__( self , UpperCAmelCase ): super().__init__(UpperCAmelCase ) super()._init_backbone(UpperCAmelCase ) lowerCamelCase_ = [config.embedding_size] + config.hidden_sizes lowerCamelCase_ = ResNetEmbeddings(UpperCAmelCase ) lowerCamelCase_ = ResNetEncoder(UpperCAmelCase ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase ) @replace_return_docstrings(output_type=UpperCAmelCase , config_class=_CONFIG_FOR_DOC ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None ): lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCamelCase_ = self.embedder(UpperCAmelCase ) lowerCamelCase_ = self.encoder(UpperCAmelCase , output_hidden_states=UpperCAmelCase , return_dict=UpperCAmelCase ) lowerCamelCase_ = outputs.hidden_states lowerCamelCase_ = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: lowerCamelCase_ = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=UpperCAmelCase , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=UpperCAmelCase , )
29
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' if not len(_lowercase ) == len(_lowercase ) == 3: raise ValueError('''Please enter a valid equation.''' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('''Both a & b of two equations can\'t be zero.''' ) # Extract the coefficients UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : int = equationa UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : str = equationa # Calculate the determinants of the matrices UpperCAmelCase_ : Union[str, Any] = aa * ba - aa * ba UpperCAmelCase_ : Tuple = ca * ba - ca * ba UpperCAmelCase_ : Tuple = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('''Infinite solutions. (Consistent system)''' ) else: raise ValueError('''No solution. (Inconsistent system)''' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: UpperCAmelCase_ : Optional[int] = determinant_x / determinant UpperCAmelCase_ : Tuple = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
30
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
0
import colorsys from PIL import Image # type: ignore def UpperCAmelCase_ ( __UpperCAmelCase : float , __UpperCAmelCase : float , __UpperCAmelCase : int ) -> float: SCREAMING_SNAKE_CASE_ = x SCREAMING_SNAKE_CASE_ = y for step in range(__UpperCAmelCase ): # noqa: B007 SCREAMING_SNAKE_CASE_ = a * a - b * b + x SCREAMING_SNAKE_CASE_ = 2 * a * b + y SCREAMING_SNAKE_CASE_ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def UpperCAmelCase_ ( __UpperCAmelCase : float ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def UpperCAmelCase_ ( __UpperCAmelCase : float ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__UpperCAmelCase , 1 , 1 ) ) def UpperCAmelCase_ ( __UpperCAmelCase : int = 8_00 , __UpperCAmelCase : int = 6_00 , __UpperCAmelCase : float = -0.6 , __UpperCAmelCase : float = 0 , __UpperCAmelCase : float = 3.2 , __UpperCAmelCase : int = 50 , __UpperCAmelCase : bool = True , ) -> Image.Image: SCREAMING_SNAKE_CASE_ = Image.new('RGB' , (image_width, image_height) ) SCREAMING_SNAKE_CASE_ = img.load() # loop through the image-coordinates for image_x in range(__UpperCAmelCase ): for image_y in range(__UpperCAmelCase ): # determine the figure-coordinates based on the image-coordinates SCREAMING_SNAKE_CASE_ = figure_width / image_width * image_height SCREAMING_SNAKE_CASE_ = figure_center_x + (image_x / image_width - 0.5) * figure_width SCREAMING_SNAKE_CASE_ = figure_center_y + (image_y / image_height - 0.5) * figure_height SCREAMING_SNAKE_CASE_ = get_distance(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: SCREAMING_SNAKE_CASE_ = get_color_coded_rgb(__UpperCAmelCase ) else: SCREAMING_SNAKE_CASE_ = get_black_and_white_rgb(__UpperCAmelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCamelCase__ : Optional[int] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
31
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
0
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def A__ ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple ) -> Dict: """simple docstring""" _UpperCAmelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg''' _UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ).convert('''RGB''' ) _UpperCAmelCase = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3) , (0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1) ), ] ) _UpperCAmelCase = transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ).to(SCREAMING_SNAKE_CASE_ ) return image def A__ ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" if "visual_encoder" in key: _UpperCAmelCase = re.sub('''visual_encoder*''' , '''vision_model.encoder''' , SCREAMING_SNAKE_CASE_ ) if "blocks" in key: _UpperCAmelCase = re.sub(R'''blocks''' , '''layers''' , SCREAMING_SNAKE_CASE_ ) if "attn" in key: _UpperCAmelCase = re.sub(R'''attn''' , '''self_attn''' , SCREAMING_SNAKE_CASE_ ) if "norm1" in key: _UpperCAmelCase = re.sub(R'''norm1''' , '''layer_norm1''' , SCREAMING_SNAKE_CASE_ ) if "norm2" in key: _UpperCAmelCase = re.sub(R'''norm2''' , '''layer_norm2''' , SCREAMING_SNAKE_CASE_ ) if "encoder.norm" in key: _UpperCAmelCase = re.sub(R'''encoder.norm''' , '''post_layernorm''' , SCREAMING_SNAKE_CASE_ ) if "encoder.patch_embed.proj" in key: _UpperCAmelCase = re.sub(R'''encoder.patch_embed.proj''' , '''embeddings.patch_embedding''' , SCREAMING_SNAKE_CASE_ ) if "encoder.pos_embed" in key: _UpperCAmelCase = re.sub(R'''encoder.pos_embed''' , '''embeddings.position_embedding''' , SCREAMING_SNAKE_CASE_ ) if "encoder.cls_token" in key: _UpperCAmelCase = re.sub(R'''encoder.cls_token''' , '''embeddings.class_embedding''' , SCREAMING_SNAKE_CASE_ ) if "self_attn" in key: _UpperCAmelCase = re.sub(R'''self_attn.proj''' , '''self_attn.projection''' , SCREAMING_SNAKE_CASE_ ) return key @torch.no_grad() def A__ ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int=None ) -> Dict: """simple docstring""" if config_path is not None: _UpperCAmelCase = BlipConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) else: _UpperCAmelCase = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) _UpperCAmelCase = BlipForConditionalGeneration(SCREAMING_SNAKE_CASE_ ).eval() _UpperCAmelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth''' _UpperCAmelCase = blip_decoder(pretrained=SCREAMING_SNAKE_CASE_ , image_size=3_84 , vit='''base''' ) _UpperCAmelCase = pt_model.eval() _UpperCAmelCase = pt_model.state_dict() for key in modified_state_dict.copy(): _UpperCAmelCase = modified_state_dict.pop(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = rename_key(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = value hf_model.load_state_dict(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = 3_84 _UpperCAmelCase = load_demo_image(image_size=SCREAMING_SNAKE_CASE_ , device='''cpu''' ) _UpperCAmelCase = BertTokenizer.from_pretrained('''bert-base-uncased''' ) _UpperCAmelCase = tokenizer(['''a picture of'''] ).input_ids _UpperCAmelCase = hf_model.generate(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] _UpperCAmelCase = hf_model.generate(SCREAMING_SNAKE_CASE_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' _UpperCAmelCase = ( '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth''' ) _UpperCAmelCase = blip_vqa(pretrained=SCREAMING_SNAKE_CASE_ , image_size=SCREAMING_SNAKE_CASE_ , vit='''base''' ) vqa_model.eval() _UpperCAmelCase = vqa_model.state_dict() for key in modified_state_dict.copy(): _UpperCAmelCase = modified_state_dict.pop(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = rename_key(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = value _UpperCAmelCase = BlipForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) hf_vqa_model.load_state_dict(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = ['''How many dogs are in this image?'''] _UpperCAmelCase = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).input_ids _UpperCAmelCase = hf_vqa_model.generate(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' ) _UpperCAmelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth''' _UpperCAmelCase = blip_itm(pretrained=SCREAMING_SNAKE_CASE_ , image_size=SCREAMING_SNAKE_CASE_ , vit='''base''' ) itm_model.eval() _UpperCAmelCase = itm_model.state_dict() for key in modified_state_dict.copy(): _UpperCAmelCase = modified_state_dict.pop(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = rename_key(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = value _UpperCAmelCase = BlipForImageTextRetrieval(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = ['''A picture of a woman with a dog sitting in a beach'''] _UpperCAmelCase = tokenizer( SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , padding='''max_length''' , truncation=SCREAMING_SNAKE_CASE_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(SCREAMING_SNAKE_CASE_ ) hf_itm_model.eval() _UpperCAmelCase = hf_itm_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , use_itm_head=SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = hf_itm_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , use_itm_head=SCREAMING_SNAKE_CASE_ ) assert out[0].item() == 0.2_1_1_0_6_8_7_4_9_4_2_7_7_9_5_4 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5_6_9_8_8_4_5_3_8_6_5_0_5_1_2_7 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' ) if __name__ == "__main__": UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") UpperCAmelCase_ = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
32
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: if height >= 1: move_tower(height - 1 , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) move_disk(__lowerCAmelCase , __lowerCAmelCase ) move_tower(height - 1 , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> Any: print('''moving disk from''' , __lowerCAmelCase , '''to''' , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( ) -> List[str]: snake_case__ = int(input('''Height of hanoi: ''' ).strip() ) move_tower(__lowerCAmelCase , '''A''' , '''B''' , '''C''' ) if __name__ == "__main__": main()
33
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
0
"""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 # ######################################################################## SCREAMING_SNAKE_CASE_ = 16 SCREAMING_SNAKE_CASE_ = 32 def __snake_case ( _lowercase ,_lowercase ,_lowercase ,_lowercase ,_lowercase = 16 ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained('''bert-base-cased''' ) UpperCamelCase = DatasetDict( { '''train''': dataset['''train'''].select(_lowercase ), '''validation''': dataset['''train'''].select(_lowercase ), '''test''': dataset['''validation'''], } ) def tokenize_function(_lowercase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase = tokenizer(examples['''sentence1'''] ,examples['''sentence2'''] ,truncation=_lowercase ,max_length=_lowercase ) 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( _lowercase ,batched=_lowercase ,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(_lowercase ): # 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( _lowercase ,padding='''longest''' ,max_length=_lowercase ,pad_to_multiple_of=_lowercase ,return_tensors='''pt''' ,) # Instantiate dataloaders. UpperCamelCase = DataLoader( tokenized_datasets['''train'''] ,shuffle=_lowercase ,collate_fn=_lowercase ,batch_size=_lowercase ) UpperCamelCase = DataLoader( tokenized_datasets['''validation'''] ,shuffle=_lowercase ,collate_fn=_lowercase ,batch_size=_lowercase ) UpperCamelCase = DataLoader( tokenized_datasets['''test'''] ,shuffle=_lowercase ,collate_fn=_lowercase ,batch_size=_lowercase ) return train_dataloader, eval_dataloader, test_dataloader def __snake_case ( _lowercase ,_lowercase ): """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(_lowercase ) # 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(_lowercase ): UpperCamelCase , UpperCamelCase , UpperCamelCase = get_fold_dataloaders( _lowercase ,_lowercase ,_lowercase ,_lowercase ,) # 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=_lowercase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase = AdamW(params=model.parameters() ,lr=_lowercase ) # Instantiate scheduler UpperCamelCase = get_linear_schedule_with_warmup( optimizer=_lowercase ,num_warmup_steps=100 ,num_training_steps=(len(_lowercase ) * 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( _lowercase ,_lowercase ,_lowercase ,_lowercase ,_lowercase ) # Now we train the model for epoch in range(_lowercase ): model.train() for step, batch in enumerate(_lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) UpperCamelCase = model(**_lowercase ) UpperCamelCase = outputs.loss UpperCamelCase = loss / gradient_accumulation_steps accelerator.backward(_lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**_lowercase ) UpperCamelCase = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=_lowercase ,references=_lowercase ,) UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,_lowercase ) # New Code # # We also run predictions on the test set at the very end UpperCamelCase = [] for step, batch in enumerate(_lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**_lowercase ) 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(_lowercase ,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(_lowercase ,dim=0 ) UpperCamelCase = torch.stack(_lowercase ,dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) UpperCamelCase = metric.compute(predictions=_lowercase ,references=_lowercase ) accelerator.print('''Average test metrics from all folds:''' ,_lowercase ) def __snake_case ( ): """simple docstring""" UpperCamelCase = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' ,type=_lowercase ,default=_lowercase ,choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] ,help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' ,) parser.add_argument('''--cpu''' ,action='''store_true''' ,help='''If passed, will train on the CPU.''' ) # New Code # parser.add_argument('''--num_folds''' ,type=_lowercase ,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(_lowercase ,_lowercase ) if __name__ == "__main__": main()
34
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
0
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class lowercase ( _UpperCAmelCase ): lowerCamelCase : Any = CustomTokenizer pass
35
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
0
from math import sqrt def lowercase ( __A : int = 100_0000 ) -> int: '''simple docstring''' snake_case : int = 0 snake_case : int = 0 snake_case : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(__A , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
36
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
0
def UpperCamelCase_ ( __a ) -> list[int]: a__ : str = len(__a ) for i in range(__a ): for j in range(i + 1 , __a ): if numbers[j] < numbers[i]: a__, a__ : List[Any] = numbers[j], numbers[i] return numbers if __name__ == "__main__": UpperCamelCase : Dict = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase : Any = [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
37
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "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 SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
'''simple docstring''' import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING A_ : Dict = logging.get_logger(__name__) A_ : Any = { "facebook/detr-resnet-50": "https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json", # See all DETR models at https://huggingface.co/models?filter=detr } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''detr''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=1_0_0 , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=2_0_4_8 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=2_0_4_8 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE="sine" , __SCREAMING_SNAKE_CASE="resnet50" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.1 , **__SCREAMING_SNAKE_CASE , ): if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) snake_case__ : Optional[int] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = backbone_config.get("""model_type""" ) snake_case__ : List[Any] = CONFIG_MAPPING[backbone_model_type] snake_case__ : Dict = config_class.from_dict(__SCREAMING_SNAKE_CASE ) # set timm attributes to None snake_case__ , snake_case__ , snake_case__ : int = None, None, None snake_case__ : List[Any] = use_timm_backbone snake_case__ : Optional[int] = backbone_config snake_case__ : Tuple = num_channels snake_case__ : str = num_queries snake_case__ : Optional[int] = d_model snake_case__ : Tuple = encoder_ffn_dim snake_case__ : Union[str, Any] = encoder_layers snake_case__ : List[str] = encoder_attention_heads snake_case__ : Dict = decoder_ffn_dim snake_case__ : Any = decoder_layers snake_case__ : Optional[int] = decoder_attention_heads snake_case__ : List[Any] = dropout snake_case__ : List[str] = attention_dropout snake_case__ : Tuple = activation_dropout snake_case__ : List[str] = activation_function snake_case__ : List[str] = init_std snake_case__ : Optional[Any] = init_xavier_std snake_case__ : int = encoder_layerdrop snake_case__ : Any = decoder_layerdrop snake_case__ : int = encoder_layers snake_case__ : Dict = auxiliary_loss snake_case__ : Dict = position_embedding_type snake_case__ : Tuple = backbone snake_case__ : str = use_pretrained_backbone snake_case__ : Union[str, Any] = dilation # Hungarian matcher snake_case__ : int = class_cost snake_case__ : Optional[int] = bbox_cost snake_case__ : Dict = giou_cost # Loss coefficients snake_case__ : List[str] = mask_loss_coefficient snake_case__ : Optional[Any] = dice_loss_coefficient snake_case__ : Optional[Any] = bbox_loss_coefficient snake_case__ : List[Any] = giou_loss_coefficient snake_case__ : Optional[int] = eos_coefficient super().__init__(is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def __UpperCamelCase ( self ): return self.encoder_attention_heads @property def __UpperCamelCase ( self ): return self.d_model @classmethod def __UpperCamelCase ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return cls(backbone_config=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: snake_case__ : Union[str, Any] = self.backbone_config.to_dict() snake_case__ : Tuple = self.__class__.model_type return output class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-5 @property def __UpperCamelCase ( self ): return 1_2
38
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Initialise PyTorch model snake_case_ = RemBertConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print('''Building PyTorch model from configuration: {}'''.format(str(SCREAMING_SNAKE_CASE__ ) ) ) snake_case_ = RemBertModel(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tf_weights_in_rembert(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print('''Save PyTorch model to {}'''.format(SCREAMING_SNAKE_CASE__ ) ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--rembert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained RemBERT 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.''' ) lowerCAmelCase_ = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
39
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=7, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=18, SCREAMING_SNAKE_CASE_=30, SCREAMING_SNAKE_CASE_=400, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=True, ) -> Optional[int]: UpperCamelCase : Union[str, Any] = size if size is not None else {'height': 18, 'width': 18} UpperCamelCase : Dict = parent UpperCamelCase : Tuple = batch_size UpperCamelCase : str = num_channels UpperCamelCase : int = image_size UpperCamelCase : Tuple = min_resolution UpperCamelCase : Optional[Any] = max_resolution UpperCamelCase : Union[str, Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = apply_ocr def snake_case_ ( self ) -> Optional[int]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowerCAmelCase_ ( a__ , unittest.TestCase ): UpperCAmelCase__ : Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def snake_case_ ( self ) -> Optional[Any]: UpperCamelCase : Tuple = LayoutLMvaImageProcessingTester(self ) @property def snake_case_ ( self ) -> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def snake_case_ ( self ) -> Tuple: UpperCamelCase : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'size' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'apply_ocr' ) ) def snake_case_ ( self ) -> List[str]: UpperCamelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'height': 18, 'width': 18} ) UpperCamelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict, size=42 ) self.assertEqual(image_processor.size, {'height': 42, 'width': 42} ) def snake_case_ ( self ) -> int: pass def snake_case_ ( self ) -> int: # Initialize image_processing UpperCamelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : Dict = prepare_image_inputs(self.image_processor_tester, equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_, Image.Image ) # Test not batched input UpperCamelCase : Optional[Any] = image_processing(image_inputs[0], return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ), ) self.assertIsInstance(encoding.words, SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(encoding.boxes, SCREAMING_SNAKE_CASE_ ) # Test batched UpperCamelCase : List[str] = image_processing(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ), ) def snake_case_ ( self ) -> Union[str, Any]: # Initialize image_processing UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase : str = prepare_image_inputs(self.image_processor_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 : str = image_processing(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ), ) # Test batched UpperCamelCase : Tuple = image_processing(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ), ) def snake_case_ ( self ) -> Tuple: # Initialize image_processing UpperCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase : List[str] = prepare_image_inputs(self.image_processor_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 : Optional[Any] = image_processing(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ), ) # Test batched UpperCamelCase : List[str] = image_processing(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ), ) def snake_case_ ( self ) -> Union[str, Any]: # with apply_OCR = True UpperCamelCase : Union[str, Any] = LayoutLMvaImageProcessor() from datasets import load_dataset UpperCamelCase : Dict = load_dataset('hf-internal-testing/fixtures_docvqa', split='test' ) UpperCamelCase : Dict = Image.open(ds[0]['file'] ).convert('RGB' ) UpperCamelCase : Union[str, Any] = image_processing(SCREAMING_SNAKE_CASE_, return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 UpperCamelCase : str = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 UpperCamelCase : int = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, SCREAMING_SNAKE_CASE_ ) self.assertListEqual(encoding.boxes, SCREAMING_SNAKE_CASE_ ) # with apply_OCR = False UpperCamelCase : Any = LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = image_processing(SCREAMING_SNAKE_CASE_, return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 224, 224) )
40
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCAmelCase__ = {'''tokenization_byt5''': ['''ByT5Tokenizer''']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
41
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
0
'''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 ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _UpperCamelCase ( __UpperCamelCase ) -> int: lowerCamelCase_ = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: lowerCamelCase_ = [1_44, 1_92, 2_40] lowerCamelCase_ = [16, 32, 64, 96, 1_28, 1_60, 6_40] elif "mobilevit_xs" in mobilevit_name: lowerCamelCase_ = [96, 1_20, 1_44] lowerCamelCase_ = [16, 32, 48, 64, 80, 96, 3_84] elif "mobilevit_xxs" in mobilevit_name: lowerCamelCase_ = [64, 80, 96] lowerCamelCase_ = [16, 16, 24, 48, 64, 80, 3_20] lowerCamelCase_ = 0.05 lowerCamelCase_ = 2.0 if mobilevit_name.startswith('deeplabv3_' ): lowerCamelCase_ = 5_12 lowerCamelCase_ = 16 lowerCamelCase_ = 21 lowerCamelCase_ = 'pascal-voc-id2label.json' else: lowerCamelCase_ = 10_00 lowerCamelCase_ = 'imagenet-1k-id2label.json' lowerCamelCase_ = 'huggingface/label-files' lowerCamelCase_ = json.load(open(hf_hub_download(__UpperCamelCase ,__UpperCamelCase ,repo_type='dataset' ) ,'r' ) ) lowerCamelCase_ = {int(__UpperCamelCase ): v for k, v in idalabel.items()} lowerCamelCase_ = idalabel lowerCamelCase_ = {v: k for k, v in idalabel.items()} return config def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase=False ) -> Optional[Any]: for i in range(1 ,6 ): if f'''layer_{i}.''' in name: lowerCamelCase_ = name.replace(f'''layer_{i}.''' ,f'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: lowerCamelCase_ = name.replace('conv_1.' ,'conv_stem.' ) if ".block." in name: lowerCamelCase_ = name.replace('.block.' ,'.' ) if "exp_1x1" in name: lowerCamelCase_ = name.replace('exp_1x1' ,'expand_1x1' ) if "red_1x1" in name: lowerCamelCase_ = name.replace('red_1x1' ,'reduce_1x1' ) if ".local_rep.conv_3x3." in name: lowerCamelCase_ = name.replace('.local_rep.conv_3x3.' ,'.conv_kxk.' ) if ".local_rep.conv_1x1." in name: lowerCamelCase_ = name.replace('.local_rep.conv_1x1.' ,'.conv_1x1.' ) if ".norm." in name: lowerCamelCase_ = name.replace('.norm.' ,'.normalization.' ) if ".conv." in name: lowerCamelCase_ = name.replace('.conv.' ,'.convolution.' ) if ".conv_proj." in name: lowerCamelCase_ = name.replace('.conv_proj.' ,'.conv_projection.' ) for i in range(0 ,2 ): for j in range(0 ,4 ): if f'''.{i}.{j}.''' in name: lowerCamelCase_ = name.replace(f'''.{i}.{j}.''' ,f'''.{i}.layer.{j}.''' ) for i in range(2 ,6 ): for j in range(0 ,4 ): if f'''.{i}.{j}.''' in name: lowerCamelCase_ = name.replace(f'''.{i}.{j}.''' ,f'''.{i}.''' ) if "expand_1x1" in name: lowerCamelCase_ = name.replace('expand_1x1' ,'downsampling_layer.expand_1x1' ) if "conv_3x3" in name: lowerCamelCase_ = name.replace('conv_3x3' ,'downsampling_layer.conv_3x3' ) if "reduce_1x1" in name: lowerCamelCase_ = name.replace('reduce_1x1' ,'downsampling_layer.reduce_1x1' ) for i in range(2 ,5 ): if f'''.global_rep.{i}.weight''' in name: lowerCamelCase_ = name.replace(f'''.global_rep.{i}.weight''' ,'.layernorm.weight' ) if f'''.global_rep.{i}.bias''' in name: lowerCamelCase_ = name.replace(f'''.global_rep.{i}.bias''' ,'.layernorm.bias' ) if ".global_rep." in name: lowerCamelCase_ = name.replace('.global_rep.' ,'.transformer.' ) if ".pre_norm_mha.0." in name: lowerCamelCase_ = name.replace('.pre_norm_mha.0.' ,'.layernorm_before.' ) if ".pre_norm_mha.1.out_proj." in name: lowerCamelCase_ = name.replace('.pre_norm_mha.1.out_proj.' ,'.attention.output.dense.' ) if ".pre_norm_ffn.0." in name: lowerCamelCase_ = name.replace('.pre_norm_ffn.0.' ,'.layernorm_after.' ) if ".pre_norm_ffn.1." in name: lowerCamelCase_ = name.replace('.pre_norm_ffn.1.' ,'.intermediate.dense.' ) if ".pre_norm_ffn.4." in name: lowerCamelCase_ = name.replace('.pre_norm_ffn.4.' ,'.output.dense.' ) if ".transformer." in name: lowerCamelCase_ = name.replace('.transformer.' ,'.transformer.layer.' ) if ".aspp_layer." in name: lowerCamelCase_ = name.replace('.aspp_layer.' ,'.' ) if ".aspp_pool." in name: lowerCamelCase_ = name.replace('.aspp_pool.' ,'.' ) if "seg_head." in name: lowerCamelCase_ = name.replace('seg_head.' ,'segmentation_head.' ) if "segmentation_head.classifier.classifier." in name: lowerCamelCase_ = name.replace('segmentation_head.classifier.classifier.' ,'segmentation_head.classifier.' ) if "classifier.fc." in name: lowerCamelCase_ = name.replace('classifier.fc.' ,'classifier.' ) elif (not base_model) and ("segmentation_head." not in name): lowerCamelCase_ = 'mobilevit.' + name return name def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=False ) -> List[str]: if base_model: lowerCamelCase_ = '' else: lowerCamelCase_ = 'mobilevit.' for key in orig_state_dict.copy().keys(): lowerCamelCase_ = orig_state_dict.pop(__UpperCamelCase ) if key[:8] == "encoder.": lowerCamelCase_ = key[8:] if "qkv" in key: lowerCamelCase_ = key.split('.' ) lowerCamelCase_ = int(key_split[0][6:] ) - 1 lowerCamelCase_ = int(key_split[3] ) lowerCamelCase_ = model.get_submodule(f'''{model_prefix}encoder.layer.{layer_num}''' ) lowerCamelCase_ = layer.transformer.layer[transformer_num].attention.attention.all_head_size lowerCamelCase_ = ( f'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: lowerCamelCase_ = val[:dim, :] lowerCamelCase_ = val[dim : dim * 2, :] lowerCamelCase_ = val[-dim:, :] else: lowerCamelCase_ = val[:dim] lowerCamelCase_ = val[dim : dim * 2] lowerCamelCase_ = val[-dim:] else: lowerCamelCase_ = val return orig_state_dict def _UpperCamelCase ( ) -> List[Any]: lowerCamelCase_ = 'http://images.cocodataset.org/val2017/000000039769.jpg' lowerCamelCase_ = Image.open(requests.get(__UpperCamelCase ,stream=__UpperCamelCase ).raw ) return im @torch.no_grad() def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=False ) -> Any: lowerCamelCase_ = get_mobilevit_config(__UpperCamelCase ) # load original state_dict lowerCamelCase_ = torch.load(__UpperCamelCase ,map_location='cpu' ) # load 🤗 model if mobilevit_name.startswith('deeplabv3_' ): lowerCamelCase_ = MobileViTForSemanticSegmentation(__UpperCamelCase ).eval() else: lowerCamelCase_ = MobileViTForImageClassification(__UpperCamelCase ).eval() lowerCamelCase_ = convert_state_dict(__UpperCamelCase ,__UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor lowerCamelCase_ = MobileViTImageProcessor(crop_size=config.image_size ,size=config.image_size + 32 ) lowerCamelCase_ = image_processor(images=prepare_img() ,return_tensors='pt' ) lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.logits if mobilevit_name.startswith('deeplabv3_' ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": lowerCamelCase_ = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": lowerCamelCase_ = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": lowerCamelCase_ = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(f'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] ,__UpperCamelCase ,atol=1e-4 ) else: assert logits.shape == (1, 10_00) if mobilevit_name == "mobilevit_s": lowerCamelCase_ = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": lowerCamelCase_ = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": lowerCamelCase_ = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(f'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] ,__UpperCamelCase ,atol=1e-4 ) Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) print(f'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__UpperCamelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(__UpperCamelCase ) if push_to_hub: lowerCamelCase_ = { 'mobilevit_s': 'mobilevit-small', 'mobilevit_xs': 'mobilevit-x-small', 'mobilevit_xxs': 'mobilevit-xx-small', 'deeplabv3_mobilevit_s': 'deeplabv3-mobilevit-small', 'deeplabv3_mobilevit_xs': 'deeplabv3-mobilevit-x-small', 'deeplabv3_mobilevit_xxs': 'deeplabv3-mobilevit-xx-small', } print('Pushing to the hub...' ) lowerCamelCase_ = model_mapping[mobilevit_name] image_processor.push_to_hub(__UpperCamelCase ,organization='apple' ) model.push_to_hub(__UpperCamelCase ,organization='apple' ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--mobilevit_name", default="mobilevit_s", type=str, help=( "Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs'," " 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'." ), ) parser.add_argument( "--checkpoint_path", required=True, type=str, help="Path to the original state dict (.pt file)." ) parser.add_argument( "--pytorch_dump_folder_path", required=True, 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." ) A_ = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
42
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = 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 : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
0
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) lowerCAmelCase = logging.getLogger(__name__) @dataclass class _a : _lowercase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _lowercase : bool = field(default=UpperCamelCase__ , metadata={'''help''': '''Whether tp freeze the encoder.'''} ) _lowercase : bool = field(default=UpperCamelCase__ , metadata={'''help''': '''Whether to freeze the embeddings.'''} ) @dataclass class _a : _lowercase : str = field( metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} ) _lowercase : Optional[str] = field( default='''summarization''' , metadata={'''help''': '''Task name, summarization (or summarization_{dataset} for pegasus) or translation'''} , ) _lowercase : Optional[int] = field( default=1024 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _lowercase : Optional[int] = field( default=128 , metadata={ '''help''': ( '''The maximum total sequence length for target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _lowercase : Optional[int] = field( default=142 , metadata={ '''help''': ( '''The maximum total sequence length for validation target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded. ''' '''This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ''' '''during ``evaluate`` and ``predict``.''' ) } , ) _lowercase : Optional[int] = field( default=142 , metadata={ '''help''': ( '''The maximum total sequence length for test target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _lowercase : Optional[int] = field(default=-1 , metadata={'''help''': '''# training examples. -1 means use all.'''} ) _lowercase : Optional[int] = field(default=-1 , metadata={'''help''': '''# validation examples. -1 means use all.'''} ) _lowercase : Optional[int] = field(default=-1 , metadata={'''help''': '''# test examples. -1 means use all.'''} ) _lowercase : Optional[str] = field(default=UpperCamelCase__ , metadata={'''help''': '''Source language id for translation.'''} ) _lowercase : Optional[str] = field(default=UpperCamelCase__ , metadata={'''help''': '''Target language id for translation.'''} ) _lowercase : Optional[int] = field(default=UpperCamelCase__ , metadata={'''help''': '''# num_beams to use for evaluation.'''} ) _lowercase : bool = field( default=UpperCamelCase__ , metadata={'''help''': '''If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'''} , ) def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" logger.info(f'***** {split} metrics *****' ) for key in sorted(metrics.keys() ): logger.info(f' {key} = {metrics[key]}' ) save_json(SCREAMING_SNAKE_CASE , os.path.join(SCREAMING_SNAKE_CASE , f'{split}_results.json' ) ) def _a ( ): """simple docstring""" lowercase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowercase__ , lowercase__ , lowercase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowercase__ , lowercase__ , lowercase__ = parser.parse_args_into_dataclasses() check_output_dir(SCREAMING_SNAKE_CASE ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , SCREAMING_SNAKE_CASE ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) lowercase__ = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): assert hasattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), f'({config.__class__.__name__}) doesn\'t have a `{p}` attribute' setattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) lowercase__ = 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 , ) lowercase__ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(SCREAMING_SNAKE_CASE , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: lowercase__ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(SCREAMING_SNAKE_CASE , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowercase__ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: lowercase__ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(SCREAMING_SNAKE_CASE ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) lowercase__ = SeqaSeqDataset # Get datasets lowercase__ = ( dataset_class( SCREAMING_SNAKE_CASE , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) lowercase__ = ( dataset_class( SCREAMING_SNAKE_CASE , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) lowercase__ = ( dataset_class( SCREAMING_SNAKE_CASE , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer lowercase__ = ( build_compute_metrics_fn(data_args.task , SCREAMING_SNAKE_CASE ) if training_args.predict_with_generate else None ) lowercase__ = SeqaSeqTrainer( model=SCREAMING_SNAKE_CASE , args=SCREAMING_SNAKE_CASE , data_args=SCREAMING_SNAKE_CASE , train_dataset=SCREAMING_SNAKE_CASE , eval_dataset=SCREAMING_SNAKE_CASE , data_collator=SeqaSeqDataCollator( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , ) lowercase__ = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) lowercase__ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) lowercase__ = train_result.metrics lowercase__ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , SCREAMING_SNAKE_CASE , training_args.output_dir ) all_metrics.update(SCREAMING_SNAKE_CASE ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowercase__ = trainer.evaluate(metric_key_prefix='''val''' ) lowercase__ = data_args.n_val lowercase__ = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , SCREAMING_SNAKE_CASE , training_args.output_dir ) all_metrics.update(SCREAMING_SNAKE_CASE ) if training_args.do_predict: logger.info('''*** Predict ***''' ) lowercase__ = trainer.predict(test_dataset=SCREAMING_SNAKE_CASE , metric_key_prefix='''test''' ) lowercase__ = test_output.metrics lowercase__ = data_args.n_test if trainer.is_world_process_zero(): lowercase__ = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , SCREAMING_SNAKE_CASE , training_args.output_dir ) all_metrics.update(SCREAMING_SNAKE_CASE ) if training_args.predict_with_generate: lowercase__ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE ) lowercase__ = lmap(str.strip , SCREAMING_SNAKE_CASE ) write_txt_file(SCREAMING_SNAKE_CASE , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(SCREAMING_SNAKE_CASE , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" main() if __name__ == "__main__": main()
43
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
0
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase_ : List[str] = random.Random() def A_ ( _lowerCAmelCase : str , _lowerCAmelCase : Optional[Any]=1.0 , _lowerCAmelCase : Tuple=None , _lowerCAmelCase : Optional[Any]=None ): """simple docstring""" if rng is None: _lowerCamelCase : List[Any] = global_rng _lowerCamelCase : Dict = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class UpperCAmelCase__ ( unittest.TestCase ): def __init__( self : Dict,__A : List[Any],__A : Any=7,__A : Dict=4_0_0,__A : Union[str, Any]=2_0_0_0,__A : Any=1_0,__A : Dict=1_6_0,__A : List[Any]=8,__A : Optional[int]=0.0,__A : int=4_0_0_0,__A : Dict=False,__A : List[Any]=True,): _lowerCamelCase : int = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : List[Any] = min_seq_length _lowerCamelCase : Optional[Any] = max_seq_length _lowerCamelCase : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _lowerCamelCase : Optional[int] = padding_value _lowerCamelCase : str = sampling_rate _lowerCamelCase : int = return_attention_mask _lowerCamelCase : List[Any] = do_normalize _lowerCamelCase : str = feature_size _lowerCamelCase : Tuple = chunk_length _lowerCamelCase : List[Any] = hop_length def lowerCamelCase_ ( self : str ): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCamelCase_ ( self : int,__A : str=False,__A : Union[str, Any]=False ): def _flatten(__A : Tuple ): return list(itertools.chain(*__A ) ) if equal_length: _lowerCamelCase : Optional[int] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _lowerCamelCase : Optional[int] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length,self.max_seq_length,self.seq_length_diff ) ] if numpify: _lowerCamelCase : Dict = [np.asarray(__A ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCAmelCase__ ( A , unittest.TestCase ): lowerCAmelCase_ = WhisperFeatureExtractor if is_speech_available() else None def lowerCamelCase_ ( self : Union[str, Any] ): _lowerCamelCase : Tuple = WhisperFeatureExtractionTester(self ) def lowerCamelCase_ ( self : Optional[int] ): _lowerCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : Optional[int] = feat_extract_first.save_pretrained(__A )[0] check_json_file_has_correct_format(__A ) _lowerCamelCase : Union[str, Any] = self.feature_extraction_class.from_pretrained(__A ) _lowerCamelCase : Optional[int] = feat_extract_first.to_dict() _lowerCamelCase : Dict = feat_extract_second.to_dict() _lowerCamelCase : str = feat_extract_first.mel_filters _lowerCamelCase : str = feat_extract_second.mel_filters self.assertTrue(np.allclose(__A,__A ) ) self.assertEqual(__A,__A ) def lowerCamelCase_ ( self : int ): _lowerCamelCase : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : Any = os.path.join(__A,"feat_extract.json" ) feat_extract_first.to_json_file(__A ) _lowerCamelCase : int = self.feature_extraction_class.from_json_file(__A ) _lowerCamelCase : Tuple = feat_extract_first.to_dict() _lowerCamelCase : Any = feat_extract_second.to_dict() _lowerCamelCase : Dict = feat_extract_first.mel_filters _lowerCamelCase : Union[str, Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(__A,__A ) ) self.assertEqual(__A,__A ) def lowerCamelCase_ ( self : Optional[Any] ): # Tests that all call wrap to encode_plus and batch_encode_plus _lowerCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _lowerCamelCase : Union[str, Any] = [floats_list((1, x) )[0] for x in range(8_0_0,1_4_0_0,2_0_0 )] _lowerCamelCase : Union[str, Any] = [np.asarray(__A ) for speech_input in speech_inputs] # Test feature size _lowerCamelCase : Optional[Any] = feature_extractor(__A,padding="max_length",return_tensors="np" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input _lowerCamelCase : Union[str, Any] = feature_extractor(speech_inputs[0],return_tensors="np" ).input_features _lowerCamelCase : Dict = feature_extractor(np_speech_inputs[0],return_tensors="np" ).input_features self.assertTrue(np.allclose(__A,__A,atol=1e-3 ) ) # Test batched _lowerCamelCase : str = feature_extractor(__A,return_tensors="np" ).input_features _lowerCamelCase : List[Any] = feature_extractor(__A,return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(__A,__A ): self.assertTrue(np.allclose(__A,__A,atol=1e-3 ) ) # Test 2-D numpy arrays are batched. _lowerCamelCase : Optional[int] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _lowerCamelCase : Dict = np.asarray(__A ) _lowerCamelCase : int = feature_extractor(__A,return_tensors="np" ).input_features _lowerCamelCase : Any = feature_extractor(__A,return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(__A,__A ): self.assertTrue(np.allclose(__A,__A,atol=1e-3 ) ) # Test truncation required _lowerCamelCase : str = [floats_list((1, x) )[0] for x in range(2_0_0,(feature_extractor.n_samples + 5_0_0),2_0_0 )] _lowerCamelCase : Dict = [np.asarray(__A ) for speech_input in speech_inputs] _lowerCamelCase : Union[str, Any] = [x[: feature_extractor.n_samples] for x in speech_inputs] _lowerCamelCase : Union[str, Any] = [np.asarray(__A ) for speech_input in speech_inputs_truncated] _lowerCamelCase : Tuple = feature_extractor(__A,return_tensors="np" ).input_features _lowerCamelCase : str = feature_extractor(__A,return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(__A,__A ): self.assertTrue(np.allclose(__A,__A,atol=1e-3 ) ) def lowerCamelCase_ ( self : Any ): import torch _lowerCamelCase : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _lowerCamelCase : str = np.random.rand(1_0_0,3_2 ).astype(np.floataa ) _lowerCamelCase : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _lowerCamelCase : List[Any] = feature_extractor.pad([{"input_features": inputs}],return_tensors="np" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) _lowerCamelCase : List[str] = feature_extractor.pad([{"input_features": inputs}],return_tensors="pt" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def lowerCamelCase_ ( self : Dict,__A : Optional[Any] ): _lowerCamelCase : List[Any] = load_dataset("hf-internal-testing/librispeech_asr_dummy","clean",split="validation" ) # automatic decoding with librispeech _lowerCamelCase : Dict = ds.sort("id" ).select(range(__A ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def lowerCamelCase_ ( self : Any ): # fmt: off _lowerCamelCase : Optional[int] = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on _lowerCamelCase : Optional[Any] = self._load_datasamples(1 ) _lowerCamelCase : Union[str, Any] = WhisperFeatureExtractor() _lowerCamelCase : str = feature_extractor(__A,return_tensors="pt" ).input_features self.assertEqual(input_features.shape,(1, 8_0, 3_0_0_0) ) self.assertTrue(torch.allclose(input_features[0, 0, :3_0],__A,atol=1e-4 ) ) def lowerCamelCase_ ( self : Any ): _lowerCamelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _lowerCamelCase : List[Any] = self._load_datasamples(1 )[0] _lowerCamelCase : List[str] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5 # Rescale to [0, 65535] to show issue _lowerCamelCase : Any = feat_extract.zero_mean_unit_var_norm([audio],attention_mask=__A )[0] self.assertTrue(np.all(np.mean(__A ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(__A ) - 1 ) < 1e-3 ) )
44
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
0
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { "nielsr/canine-s": 2_048, } # Unicode defines 1,114,112 total “codepoints” UpperCamelCase = 1_114_112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py UpperCamelCase = 0 UpperCamelCase = 0xe0_00 UpperCamelCase = 0xe0_01 UpperCamelCase = 0xe0_02 UpperCamelCase = 0xe0_03 UpperCamelCase = 0xe0_04 # Maps special codepoints to human-readable names. UpperCamelCase = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. UpperCamelCase = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class lowerCAmelCase_ ( lowercase ): """simple docstring""" _snake_case : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self :Tuple , lowerCamelCase__ :Optional[int]=chr(lowerCamelCase__ ) , lowerCamelCase__ :Optional[Any]=chr(lowerCamelCase__ ) , lowerCamelCase__ :Optional[Any]=chr(lowerCamelCase__ ) , lowerCamelCase__ :Dict=chr(lowerCamelCase__ ) , lowerCamelCase__ :List[Any]=chr(lowerCamelCase__ ) , lowerCamelCase__ :Dict=chr(lowerCamelCase__ ) , lowerCamelCase__ :Union[str, Any]=False , lowerCamelCase__ :int=20_48 , **lowerCamelCase__ :List[str] , ): UpperCamelCase__ :int = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else bos_token UpperCamelCase__ :List[Any] = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else eos_token UpperCamelCase__ :Any = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else sep_token UpperCamelCase__ :Any = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else cls_token UpperCamelCase__ :Optional[Any] = 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 UpperCamelCase__ :str = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else mask_token super().__init__( bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , add_prefix_space=lowerCamelCase__ , model_max_length=lowerCamelCase__ , **lowerCamelCase__ , ) # Creates a mapping for looking up the IDs of special symbols. UpperCamelCase__ :Dict[str, int] = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): UpperCamelCase__ :str = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. UpperCamelCase__ :Dict[int, str] = { codepoint: name for name, codepoint in self._special_codepoints.items() } UpperCamelCase__ :Any = UNICODE_VOCAB_SIZE UpperCamelCase__ :List[str] = len(self._special_codepoints ) @property def __a ( self :Any ): return self._unicode_vocab_size def __a ( self :Optional[int] , lowerCamelCase__ :str ): return list(lowerCamelCase__ ) def __a ( self :List[str] , lowerCamelCase__ :str ): try: return ord(lowerCamelCase__ ) except TypeError: raise ValueError(f"""invalid token: '{token}'""" ) def __a ( self :Any , lowerCamelCase__ :int ): try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(lowerCamelCase__ ) except TypeError: raise ValueError(f"""invalid id: {index}""" ) def __a ( self :Tuple , lowerCamelCase__ :Optional[int] ): return "".join(lowerCamelCase__ ) def __a ( self :Optional[int] , lowerCamelCase__ :List[int] , lowerCamelCase__ :Optional[List[int]] = None ): UpperCamelCase__ :Union[str, Any] = [self.sep_token_id] UpperCamelCase__ :Any = [self.cls_token_id] UpperCamelCase__ :Dict = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def __a ( self :Tuple , lowerCamelCase__ :List[int] , lowerCamelCase__ :Optional[List[int]] = None , lowerCamelCase__ :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase__ , token_ids_a=lowerCamelCase__ , already_has_special_tokens=lowerCamelCase__ ) UpperCamelCase__ :Tuple = [1] + ([0] * len(lowerCamelCase__ )) + [1] if token_ids_a is not None: result += ([0] * len(lowerCamelCase__ )) + [1] return result def __a ( self :int , lowerCamelCase__ :List[int] , lowerCamelCase__ :Optional[List[int]] = None ): UpperCamelCase__ :List[Any] = [self.sep_token_id] UpperCamelCase__ :Optional[Any] = [self.cls_token_id] UpperCamelCase__ :Tuple = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def __a ( self :Tuple , lowerCamelCase__ :str , lowerCamelCase__ :Optional[str] = None ): return ()
45
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
0
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Dict: '''simple docstring''' assert isinstance(_lowerCamelCase , _lowerCamelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> int: '''simple docstring''' _lowerCamelCase : Tuple = tmp_path / "cache" _lowerCamelCase : Optional[int] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _lowerCamelCase : Dict = ParquetDatasetReader(_lowerCamelCase , cache_dir=_lowerCamelCase , keep_in_memory=_lowerCamelCase ).read() _check_parquet_dataset(_lowerCamelCase , _lowerCamelCase ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Dict: '''simple docstring''' _lowerCamelCase : Optional[Any] = tmp_path / "cache" _lowerCamelCase : List[str] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} _lowerCamelCase : Optional[Any] = features.copy() if features else default_expected_features _lowerCamelCase : Optional[Any] = ( Features({feature: Value(_lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _lowerCamelCase : Any = ParquetDatasetReader(_lowerCamelCase , features=_lowerCamelCase , cache_dir=_lowerCamelCase ).read() _check_parquet_dataset(_lowerCamelCase , _lowerCamelCase ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> str: '''simple docstring''' _lowerCamelCase : Any = tmp_path / "cache" _lowerCamelCase : Dict = {"col_1": "string", "col_2": "int64", "col_3": "float64"} _lowerCamelCase : List[str] = ParquetDatasetReader(_lowerCamelCase , cache_dir=_lowerCamelCase , split=_lowerCamelCase ).read() _check_parquet_dataset(_lowerCamelCase , _lowerCamelCase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> List[str]: '''simple docstring''' if issubclass(_lowerCamelCase , _lowerCamelCase ): _lowerCamelCase : Tuple = parquet_path elif issubclass(_lowerCamelCase , _lowerCamelCase ): _lowerCamelCase : Any = [parquet_path] _lowerCamelCase : Any = tmp_path / "cache" _lowerCamelCase : Optional[int] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} _lowerCamelCase : Union[str, Any] = ParquetDatasetReader(_lowerCamelCase , cache_dir=_lowerCamelCase ).read() _check_parquet_dataset(_lowerCamelCase , _lowerCamelCase ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=("train",) ) -> Dict: '''simple docstring''' assert isinstance(_lowerCamelCase , _lowerCamelCase ) for split in splits: _lowerCamelCase : List[str] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> List[Any]: '''simple docstring''' _lowerCamelCase : Any = tmp_path / "cache" _lowerCamelCase : Tuple = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _lowerCamelCase : Any = ParquetDatasetReader( {"train": parquet_path} , cache_dir=_lowerCamelCase , keep_in_memory=_lowerCamelCase ).read() _check_parquet_datasetdict(_lowerCamelCase , _lowerCamelCase ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> List[Any]: '''simple docstring''' _lowerCamelCase : int = tmp_path / "cache" _lowerCamelCase : List[Any] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} _lowerCamelCase : Union[str, Any] = features.copy() if features else default_expected_features _lowerCamelCase : str = ( Features({feature: Value(_lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _lowerCamelCase : str = ParquetDatasetReader({"train": parquet_path} , features=_lowerCamelCase , cache_dir=_lowerCamelCase ).read() _check_parquet_datasetdict(_lowerCamelCase , _lowerCamelCase ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Dict: '''simple docstring''' if split: _lowerCamelCase : Union[str, Any] = {split: parquet_path} else: _lowerCamelCase : Optional[Any] = "train" _lowerCamelCase : Optional[Any] = {"train": parquet_path, "test": parquet_path} _lowerCamelCase : Optional[int] = tmp_path / "cache" _lowerCamelCase : List[str] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} _lowerCamelCase : Tuple = ParquetDatasetReader(_lowerCamelCase , cache_dir=_lowerCamelCase ).read() _check_parquet_datasetdict(_lowerCamelCase , _lowerCamelCase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Union[str, Any]: '''simple docstring''' _lowerCamelCase : Dict = ParquetDatasetWriter(_lowerCamelCase , tmp_path / "foo.parquet" ) assert writer.write() > 0 _lowerCamelCase : Tuple = pq.ParquetFile(tmp_path / "foo.parquet" ) _lowerCamelCase : List[Any] = pf.read() assert dataset.data.table == output_table def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Union[str, Any]: '''simple docstring''' _lowerCamelCase : Any = str(shared_datadir / "test_image_rgb.jpg" ) _lowerCamelCase : Optional[Any] = {"image": [image_path]} _lowerCamelCase : List[str] = Features({"image": Image()} ) _lowerCamelCase : List[str] = Dataset.from_dict(_lowerCamelCase , features=_lowerCamelCase ) _lowerCamelCase : List[Any] = ParquetDatasetWriter(_lowerCamelCase , tmp_path / "foo.parquet" ) assert writer.write() > 0 _lowerCamelCase : List[Any] = Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features _lowerCamelCase : List[str] = ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=_lowerCamelCase ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Any: '''simple docstring''' assert get_writer_batch_size(_lowerCamelCase ) == expected
46
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
0
def UpperCAmelCase__ ( lowerCamelCase_ : int , lowerCamelCase_ : int ): if b == 0: return 1 if (b % 2) == 0: return actual_power(lowerCamelCase_ , int(b / 2 ) ) * actual_power(lowerCamelCase_ , int(b / 2 ) ) else: return a * actual_power(lowerCamelCase_ , int(b / 2 ) ) * actual_power(lowerCamelCase_ , int(b / 2 ) ) def UpperCAmelCase__ ( lowerCamelCase_ : int , lowerCamelCase_ : int ): if b < 0: return 1 / actual_power(lowerCamelCase_ , lowerCamelCase_ ) return actual_power(lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": print(power(-2, -3))
47
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
0
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase__ : Optional[Any] = pytest.mark.integration UpperCAmelCase__ : str = {"comet"} UpperCAmelCase__ : Optional[Any] = importlib.util.find_spec("fairseq") is not None UpperCAmelCase__ : Optional[int] = {"code_eval"} UpperCAmelCase__ : List[Any] = os.name == "nt" UpperCAmelCase__ : Optional[int] = {"bertscore", "frugalscore", "perplexity"} UpperCAmelCase__ : int = importlib.util.find_spec("transformers") is not None def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[Any] , UpperCamelCase_ : List[str] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : List[Any] ) -> str: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : Any ) -> int: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @local class A ( parameterized.TestCase ): snake_case__ :Union[str, Any] = {} snake_case__ :Optional[Any] = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) lowerCAmelCase__ = datasets.load.import_main_class(metric_module.__name__ , dataset=__magic_name__ ) # check parameters lowerCAmelCase__ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__magic_name__ , metric_module.__name__ ): with self.use_local_metrics(): try: lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) # run doctest with self.use_local_metrics(): lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__magic_name__ ): yield else: yield @contextmanager def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" def load_local_metric(__magic_name__ : Union[str, Any] , *__magic_name__ : Any , **__magic_name__ : Any ): return load_metric(os.path.join("metrics" , __magic_name__ ) , *__magic_name__ , **__magic_name__ ) with patch("datasets.load_metric" ) as mock_load_metric: lowerCAmelCase__ = load_local_metric yield @classmethod def __SCREAMING_SNAKE_CASE ( cls : Any , __magic_name__ : Optional[int] ): """simple docstring""" def wrapper(__magic_name__ : Dict ): lowerCAmelCase__ = contextmanager(__magic_name__ ) lowerCAmelCase__ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def A ( UpperCamelCase_ : str ) -> Any: '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] ): """simple docstring""" assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: lowerCAmelCase__ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def A ( UpperCamelCase_ : List[Any] ) -> Optional[Any]: '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: lowerCAmelCase__ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def A ( UpperCamelCase_ : Optional[int] ) -> Any: '''simple docstring''' def load_from_checkpoint(UpperCamelCase_ : Tuple ): class A : def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : int , **__magic_name__ : Dict ): """simple docstring""" assert len(__magic_name__ ) == 2 lowerCAmelCase__ = [0.19, 0.92] return scores, sum(__magic_name__ ) / len(__magic_name__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: lowerCAmelCase__ = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: lowerCAmelCase__ = load_from_checkpoint yield def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = load_metric(os.path.join("metrics" , "seqeval" ) ) lowerCAmelCase__ = "ERROR" lowerCAmelCase__ = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase_ , match=re.escape(UpperCamelCase_ ) ): metric.compute(predictions=[] , references=[] , scheme=UpperCamelCase_ )
48
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
0
"""simple docstring""" import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": _lowercase : List[Any] = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) _lowercase : Any = parser.parse_args() _lowercase : int = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
49
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
0
'''simple docstring''' import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' @property def UpperCamelCase_ ( self ): torch.manual_seed(0 ) lowerCamelCase__ = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def UpperCamelCase_ ( self ): lowerCamelCase__ = self.dummy_uncond_unet lowerCamelCase__ = ScoreSdeVeScheduler() lowerCamelCase__ = ScoreSdeVePipeline(unet=_lowerCAmelCase ,scheduler=_lowerCAmelCase ) sde_ve.to(_lowerCAmelCase ) sde_ve.set_progress_bar_config(disable=_lowerCAmelCase ) lowerCamelCase__ = torch.manual_seed(0 ) lowerCamelCase__ = sde_ve(num_inference_steps=2 ,output_type="""numpy""" ,generator=_lowerCAmelCase ).images lowerCamelCase__ = torch.manual_seed(0 ) lowerCamelCase__ = sde_ve(num_inference_steps=2 ,output_type="""numpy""" ,generator=_lowerCAmelCase ,return_dict=_lowerCAmelCase )[ 0 ] lowerCamelCase__ = image[0, -3:, -3:, -1] lowerCamelCase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCamelCase__ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ): lowerCamelCase__ = """google/ncsnpp-church-256""" lowerCamelCase__ = UNetaDModel.from_pretrained(_lowerCAmelCase ) lowerCamelCase__ = ScoreSdeVeScheduler.from_pretrained(_lowerCAmelCase ) lowerCamelCase__ = ScoreSdeVePipeline(unet=_lowerCAmelCase ,scheduler=_lowerCAmelCase ) sde_ve.to(_lowerCAmelCase ) sde_ve.set_progress_bar_config(disable=_lowerCAmelCase ) lowerCamelCase__ = torch.manual_seed(0 ) lowerCamelCase__ = sde_ve(num_inference_steps=10 ,output_type="""numpy""" ,generator=_lowerCAmelCase ).images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) lowerCamelCase__ = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
50
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 snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
0
'''simple docstring''' a__ : int = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> list[str]: """simple docstring""" UpperCAmelCase = set() # keep track of all the paths to be checked UpperCAmelCase = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue UpperCAmelCase = queue.pop(0 ) # get the last node from the path UpperCAmelCase = path[-1] if node not in explored: UpperCAmelCase = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: UpperCAmelCase = list(SCREAMING_SNAKE_CASE_ ) new_path.append(SCREAMING_SNAKE_CASE_ ) queue.append(SCREAMING_SNAKE_CASE_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(SCREAMING_SNAKE_CASE_ ) # in case there's no path between the 2 nodes return [] def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> int: """simple docstring""" if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 UpperCAmelCase = [start] UpperCAmelCase = set(SCREAMING_SNAKE_CASE_ ) # Keep tab on distances from `start` node. UpperCAmelCase = {start: 0, target: -1} while queue: UpperCAmelCase = queue.pop(0 ) if node == target: UpperCAmelCase = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(SCREAMING_SNAKE_CASE_ ) queue.append(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
51
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
"""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 __lowercase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = IFInpaintingPipeline __lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} __lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __lowerCAmelCase = PipelineTesterMixin.required_optional_params - {'''latents'''} def _lowerCamelCase ( self ): return self._get_dummy_components() def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase=0 ): if str(_UpperCAmelCase ).startswith('''mps''' ): __a : str = torch.manual_seed(_UpperCAmelCase ) else: __a : List[Any] = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) __a : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) __a : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) __a : Optional[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def _lowerCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def _lowerCamelCase ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def _lowerCamelCase ( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def _lowerCamelCase ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def _lowerCamelCase ( self ): self._test_save_load_local() def _lowerCamelCase ( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
52
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
0
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel _snake_case : Optional[int] = False _snake_case : Any = True _snake_case : Optional[Any] = False if __name__ == "__main__": _snake_case : Dict = 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.') _snake_case : Tuple = parser.parse_args() _snake_case : 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', } _snake_case : int = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } _snake_case : Optional[int] = '' 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: _snake_case : Any = reader.read() _snake_case : Dict = 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'): _snake_case : str = UNetaDModel(**config) else: _snake_case : Any = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel _snake_case : Dict = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) _snake_case : int = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: _snake_case : Optional[Any] = config[key] del config[key] _snake_case : Optional[Any] = [k.replace('UNetRes', '') for k in config['down_block_types']] _snake_case : Tuple = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: _snake_case : int = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) _snake_case : Any = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue _snake_case : Optional[int] = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: _snake_case : List[Any] = param_value _snake_case : Optional[Any] = True if not has_changed: _snake_case : Union[str, Any] = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
53
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
0
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( "split_dict" , [ SplitDict(), SplitDict({"train": SplitInfo(name="train" , num_bytes=1_3_3_7 , num_examples=4_2 , dataset_name="my_dataset" )} ), SplitDict({"train": SplitInfo(name="train" , num_bytes=1_3_3_7 , num_examples=4_2 )} ), SplitDict({"train": SplitInfo()} ), ] , ) def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =split_dict._to_yaml_list() assert len(lowercase__ ) == len(lowercase__ ) UpperCAmelCase_ =SplitDict._from_yaml_list(lowercase__ ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump UpperCAmelCase_ =None # the split name of split_dict takes over the name of the split info object UpperCAmelCase_ =split_name assert split_dict == reloaded @pytest.mark.parametrize( "split_info" , [SplitInfo(), SplitInfo(dataset_name=lowercase__ ), SplitInfo(dataset_name="my_dataset" )] ) def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =asdict(SplitDict({"train": split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
54
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
def UpperCAmelCase ( a_ , a_ ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def UpperCAmelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
55
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
0
'''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 _a : Dict = 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 _a : Tuple = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class _lowercase : def __init__( self : List[Any] ) -> int: __snake_case = WATERMARK_BITS __snake_case = WatermarkEncoder() self.encoder.set_watermark('bits' , self.watermark ) def a ( self : Tuple , SCREAMING_SNAKE_CASE_ : torch.FloatTensor ) -> Dict: # can't encode images that are smaller than 256 if images.shape[-1] < 256: return images __snake_case = (255 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __snake_case = [self.encoder.encode(SCREAMING_SNAKE_CASE_ , 'dwtDct' ) for image in images] __snake_case = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE_ ) ).permute(0 , 3 , 1 , 2 ) __snake_case = torch.clamp(2 * (images / 255 - 0.5) , min=-1.0 , max=1.0 ) return images
56
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
0
from itertools import permutations def snake_case (UpperCAmelCase__ ) -> bool: if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False UpperCamelCase_: Optional[int] = [7, 1_1, 1_3, 1_7] for i, test in enumerate(UpperCAmelCase__ ): if (num[i + 4] * 1_0_0 + num[i + 5] * 1_0 + num[i + 6]) % test != 0: return False return True def snake_case (UpperCAmelCase__ = 1_0 ) -> int: return sum( int(''.join(map(UpperCAmelCase__ , UpperCAmelCase__ ) ) ) for num in permutations(range(UpperCAmelCase__ ) ) if is_substring_divisible(UpperCAmelCase__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
57
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
0
"""simple docstring""" import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __lowerCAmelCase ( __UpperCamelCase : bytes , __UpperCamelCase : int ): '''simple docstring''' snake_case_ : Optional[Any] = F'{sampling_rate}' snake_case_ : Dict = """1""" snake_case_ : int = """f32le""" snake_case_ : Dict = [ """ffmpeg""", """-i""", """pipe:0""", """-ac""", ac, """-ar""", ar, """-f""", format_for_conversion, """-hide_banner""", """-loglevel""", """quiet""", """pipe:1""", ] try: with subprocess.Popen(__UpperCamelCase , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: snake_case_ : Tuple = ffmpeg_process.communicate(__UpperCamelCase ) except FileNotFoundError as error: raise ValueError("""ffmpeg was not found but is required to load audio files from filename""" ) from error snake_case_ : Optional[int] = output_stream[0] snake_case_ : Optional[Any] = np.frombuffer(__UpperCamelCase , np.floataa ) if audio.shape[0] == 0: raise ValueError("""Malformed soundfile""" ) return audio def __lowerCAmelCase ( __UpperCamelCase : int , __UpperCamelCase : float , __UpperCamelCase : str = "f32le" , ): '''simple docstring''' snake_case_ : Any = F'{sampling_rate}' snake_case_ : Tuple = """1""" if format_for_conversion == "s16le": snake_case_ : List[Any] = 2 elif format_for_conversion == "f32le": snake_case_ : List[Any] = 4 else: raise ValueError(F'Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`' ) snake_case_ : str = platform.system() if system == "Linux": snake_case_ : Any = """alsa""" snake_case_ : Dict = """default""" elif system == "Darwin": snake_case_ : List[Any] = """avfoundation""" snake_case_ : Optional[int] = """:0""" elif system == "Windows": snake_case_ : int = """dshow""" snake_case_ : int = """default""" snake_case_ : List[Any] = [ """ffmpeg""", """-f""", format_, """-i""", input_, """-ac""", ac, """-ar""", ar, """-f""", format_for_conversion, """-fflags""", """nobuffer""", """-hide_banner""", """-loglevel""", """quiet""", """pipe:1""", ] snake_case_ : str = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample snake_case_ : str = _ffmpeg_stream(__UpperCamelCase , __UpperCamelCase ) for item in iterator: yield item def __lowerCAmelCase ( __UpperCamelCase : int , __UpperCamelCase : float , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Optional[Union[Tuple[float, float], float]] = None , __UpperCamelCase : str = "f32le" , ): '''simple docstring''' if stream_chunk_s is not None: snake_case_ : Tuple = stream_chunk_s else: snake_case_ : Dict = chunk_length_s snake_case_ : Union[str, Any] = ffmpeg_microphone(__UpperCamelCase , __UpperCamelCase , format_for_conversion=__UpperCamelCase ) if format_for_conversion == "s16le": snake_case_ : Tuple = np.intaa snake_case_ : int = 2 elif format_for_conversion == "f32le": snake_case_ : Tuple = np.floataa snake_case_ : Optional[Any] = 4 else: raise ValueError(F'Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`' ) if stride_length_s is None: snake_case_ : List[Any] = chunk_length_s / 6 snake_case_ : Optional[int] = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(__UpperCamelCase , (int, float) ): snake_case_ : Union[str, Any] = [stride_length_s, stride_length_s] snake_case_ : Dict = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample snake_case_ : Union[str, Any] = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample snake_case_ : str = datetime.datetime.now() snake_case_ : int = datetime.timedelta(seconds=__UpperCamelCase ) for item in chunk_bytes_iter(__UpperCamelCase , __UpperCamelCase , stride=(stride_left, stride_right) , stream=__UpperCamelCase ): # Put everything back in numpy scale snake_case_ : Any = np.frombuffer(item["""raw"""] , dtype=__UpperCamelCase ) snake_case_ : Dict = ( item["""stride"""][0] // size_of_sample, item["""stride"""][1] // size_of_sample, ) snake_case_ : Optional[int] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 1_0 * delta: # We're late !! SKIP continue yield item def __lowerCAmelCase ( __UpperCamelCase : Optional[int] , __UpperCamelCase : int , __UpperCamelCase : Tuple[int, int] , __UpperCamelCase : bool = False ): '''simple docstring''' snake_case_ : Dict = B"""""" snake_case_ , snake_case_ : List[Any] = stride if stride_left + stride_right >= chunk_len: raise ValueError( F'Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}' ) snake_case_ : List[str] = 0 for raw in iterator: acc += raw if stream and len(__UpperCamelCase ) < chunk_len: snake_case_ : Any = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(__UpperCamelCase ) >= chunk_len: # We are flushing the accumulator snake_case_ : Any = (_stride_left, stride_right) snake_case_ : Optional[Any] = {"""raw""": acc[:chunk_len], """stride""": stride} if stream: snake_case_ : List[Any] = False yield item snake_case_ : Optional[int] = stride_left snake_case_ : Dict = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(__UpperCamelCase ) > stride_left: snake_case_ : str = {"""raw""": acc, """stride""": (_stride_left, 0)} if stream: snake_case_ : Dict = False yield item def __lowerCAmelCase ( __UpperCamelCase : Any , __UpperCamelCase : int ): '''simple docstring''' snake_case_ : List[str] = 2**2_4 # 16Mo try: with subprocess.Popen(__UpperCamelCase , stdout=subprocess.PIPE , bufsize=__UpperCamelCase ) as ffmpeg_process: while True: snake_case_ : List[str] = ffmpeg_process.stdout.read(__UpperCamelCase ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError("""ffmpeg was not found but is required to stream audio files from filename""" ) from error
58
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
0
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "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 SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=7 , __magic_name__=True , __magic_name__=True , __magic_name__=False , __magic_name__=True , __magic_name__=99 , __magic_name__=32 , __magic_name__=5 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=512 , __magic_name__=16 , __magic_name__=2 , __magic_name__=0.02 , __magic_name__=3 , __magic_name__=4 , __magic_name__=None , ) -> Dict: '''simple docstring''' snake_case_ : List[str] = parent snake_case_ : List[Any] = batch_size snake_case_ : List[Any] = seq_length snake_case_ : List[Any] = is_training snake_case_ : Optional[Any] = use_input_mask snake_case_ : str = use_token_type_ids snake_case_ : List[str] = use_labels snake_case_ : int = vocab_size snake_case_ : int = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Tuple = intermediate_size snake_case_ : int = hidden_act snake_case_ : Tuple = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : List[str] = max_position_embeddings snake_case_ : List[Any] = type_vocab_size snake_case_ : List[str] = type_sequence_label_size snake_case_ : Union[str, Any] = initializer_range snake_case_ : List[Any] = num_labels snake_case_ : Optional[int] = num_choices snake_case_ : Any = scope def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ : List[Any] = None if self.use_input_mask: snake_case_ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ : int = None snake_case_ : Optional[Any] = None snake_case_ : Tuple = None if self.use_labels: snake_case_ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ : Dict = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> Optional[Any]: '''simple docstring''' snake_case_ : str = DistilBertModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : List[Any] = model(__magic_name__ , __magic_name__ ) snake_case_ : List[Any] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' snake_case_ : str = DistilBertForMaskedLM(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : str = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : Optional[int] = DistilBertForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Union[str, Any] = model( __magic_name__ , attention_mask=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ ) 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 , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' snake_case_ : str = self.num_labels snake_case_ : str = DistilBertForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Optional[int] = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> str: '''simple docstring''' snake_case_ : Dict = self.num_labels snake_case_ : List[Any] = DistilBertForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Optional[Any] = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : Any = self.num_choices snake_case_ : List[Any] = DistilBertForMultipleChoice(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : Tuple = model( __magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = self.prepare_config_and_inputs() ((snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_)) : Union[str, Any] = config_and_inputs snake_case_ : Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : Optional[int] = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) lowerCamelCase_ : str = ( { '''feature-extraction''': DistilBertModel, '''fill-mask''': DistilBertForMaskedLM, '''question-answering''': DistilBertForQuestionAnswering, '''text-classification''': DistilBertForSequenceClassification, '''token-classification''': DistilBertForTokenClassification, '''zero-shot''': DistilBertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase_ : Optional[Any] = True lowerCamelCase_ : List[Any] = True lowerCamelCase_ : int = True lowerCamelCase_ : str = True def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : int = DistilBertModelTester(self ) snake_case_ : List[str] = ConfigTester(self , config_class=__magic_name__ , dim=37 ) def lowerCamelCase (self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*__magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*__magic_name__ ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*__magic_name__ ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*__magic_name__ ) @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : Tuple = DistilBertModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) @slow @require_torch_gpu def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ , snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return snake_case_ : List[str] = True snake_case_ : Tuple = model_class(config=__magic_name__ ) snake_case_ : Tuple = self._prepare_for_class(__magic_name__ , __magic_name__ ) snake_case_ : List[str] = torch.jit.trace( __magic_name__ , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__magic_name__ , os.path.join(__magic_name__ , '''traced_model.pt''' ) ) snake_case_ : Union[str, Any] = torch.jit.load(os.path.join(__magic_name__ , '''traced_model.pt''' ) , map_location=__magic_name__ ) loaded(inputs_dict['''input_ids'''].to(__magic_name__ ) , inputs_dict['''attention_mask'''].to(__magic_name__ ) ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = DistilBertModel.from_pretrained('''distilbert-base-uncased''' ) snake_case_ : List[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) snake_case_ : Union[str, Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case_ : int = model(__magic_name__ , attention_mask=__magic_name__ )[0] snake_case_ : int = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __magic_name__ ) snake_case_ : Union[str, Any] = torch.tensor( [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __magic_name__ , atol=1e-4 ) )
60
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["image_processor", "tokenizer"] snake_case__ = "LayoutLMv2ImageProcessor" snake_case__ = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = kwargs.pop("feature_extractor" ) lowerCAmelCase__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , SCREAMING_SNAKE_CASE__ : Union[List[List[int]], List[List[List[int]]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[List[int], List[List[int]]]] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> BatchEncoding: # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes " "if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("You cannot return overflowing tokens without returning the offsets mapping." ) # first, apply the image processor lowerCAmelCase__ = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [text] # add batch dimension (as the image processor always adds a batch dimension) lowerCAmelCase__ = features["words"] lowerCAmelCase__ = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # add pixel values lowerCAmelCase__ = features.pop("pixel_values" ) if return_overflowing_tokens is True: lowerCAmelCase__ = self.get_overflowing_images(SCREAMING_SNAKE_CASE__ , encoded_inputs["overflow_to_sample_mapping"] ) lowerCAmelCase__ = images return encoded_inputs def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image lowerCAmelCase__ = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(SCREAMING_SNAKE_CASE__ )} and {len(SCREAMING_SNAKE_CASE__ )}' ) return images_with_overflow def a ( self : int , *SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def a ( self : Any ) -> Optional[Any]: return ["input_ids", "bbox", "attention_mask", "image"] @property def a ( self : Union[str, Any] ) -> int: warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def a ( self : List[str] ) -> Tuple: warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
61
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
0
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy snake_case = logging.getLogger(__name__) def lowerCamelCase__ ( lowercase , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = False , ): """simple docstring""" SCREAMING_SNAKE_CASE : int = bnb_quantization_config.load_in_abit SCREAMING_SNAKE_CASE : List[Any] = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) SCREAMING_SNAKE_CASE : Tuple = [] # custom device map if isinstance(lowercase , lowercase ) and len(device_map.keys() ) > 1: SCREAMING_SNAKE_CASE : int = [key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: SCREAMING_SNAKE_CASE : Optional[Any] = get_keys_to_not_convert(lowercase ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(lowercase ) # compatibility with peft SCREAMING_SNAKE_CASE : int = load_in_abit SCREAMING_SNAKE_CASE : str = load_in_abit SCREAMING_SNAKE_CASE : List[str] = get_parameter_device(lowercase ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) SCREAMING_SNAKE_CASE : Any = replace_with_bnb_layers(lowercase , lowercase , modules_to_not_convert=lowercase ) # convert param to the right dtype SCREAMING_SNAKE_CASE : Optional[int] = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".weight" , "" ).replace(".bias" , "" ) SCREAMING_SNAKE_CASE : Optional[int] = getattr(lowercase , lowercase , lowercase ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(lowercase ): param.to(lowercase ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F'''The model device type is {model_device.type}. However, cuda is needed for quantization.''' "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F'''`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ''' ) else: with init_empty_weights(): SCREAMING_SNAKE_CASE : str = replace_with_bnb_layers( lowercase , lowercase , modules_to_not_convert=lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = get_quantized_model_device_map( lowercase , lowercase , lowercase , max_memory=lowercase , no_split_module_classes=lowercase , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Optional[Any] = any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( lowercase , lowercase , lowercase , dtype=bnb_quantization_config.torch_dtype , offload_folder=lowercase , offload_state_dict=lowercase , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(lowercase , device_map=lowercase , offload_dir=lowercase ) def lowerCamelCase__ ( lowercase , lowercase , lowercase=None , lowercase=None , lowercase=None ): """simple docstring""" if device_map is None: if torch.cuda.is_available(): SCREAMING_SNAKE_CASE : Optional[Any] = {"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(lowercase , lowercase ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) SCREAMING_SNAKE_CASE : Tuple = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) SCREAMING_SNAKE_CASE : Optional[Any] = {} SCREAMING_SNAKE_CASE : Optional[Any] = special_dtypes SCREAMING_SNAKE_CASE : List[str] = no_split_module_classes SCREAMING_SNAKE_CASE : str = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": SCREAMING_SNAKE_CASE : List[Any] = get_balanced_memory( lowercase , low_zero=(device_map == "balanced_low_0") , max_memory=lowercase , **lowercase , ) SCREAMING_SNAKE_CASE : int = max_memory SCREAMING_SNAKE_CASE : Tuple = infer_auto_device_map(lowercase , **lowercase ) if isinstance(lowercase , lowercase ): # check if don't have any quantized module on the cpu SCREAMING_SNAKE_CASE : List[str] = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules SCREAMING_SNAKE_CASE : List[Any] = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCamelCase__ ( lowercase , lowercase , lowercase=None , lowercase=None ): """simple docstring""" if modules_to_not_convert is None: SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = _replace_with_bnb_layers( lowercase , lowercase , lowercase , lowercase ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCamelCase__ ( lowercase , lowercase , lowercase=None , lowercase=None , ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = False for name, module in model.named_children(): if current_key_name is None: SCREAMING_SNAKE_CASE : Any = [] current_key_name.append(lowercase ) if isinstance(lowercase , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` SCREAMING_SNAKE_CASE : Dict = ".".join(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: SCREAMING_SNAKE_CASE : Union[str, Any] = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE : Optional[int] = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=lowercase , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE : int = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) SCREAMING_SNAKE_CASE : int = module.weight.data if module.bias is not None: SCREAMING_SNAKE_CASE : List[str] = module.bias.data bnb_module.requires_grad_(lowercase ) setattr(lowercase , lowercase , lowercase ) SCREAMING_SNAKE_CASE : Any = True if len(list(module.children() ) ) > 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = _replace_with_bnb_layers( lowercase , lowercase , lowercase , lowercase ) SCREAMING_SNAKE_CASE : Tuple = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCamelCase__ ( lowercase ): """simple docstring""" with init_empty_weights(): SCREAMING_SNAKE_CASE : List[str] = deepcopy(lowercase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` SCREAMING_SNAKE_CASE : Dict = find_tied_parameters(lowercase ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE : List[Any] = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: SCREAMING_SNAKE_CASE : Optional[Any] = sum(lowercase , [] ) SCREAMING_SNAKE_CASE : int = len(lowercase ) > 0 # Check if it is a base model SCREAMING_SNAKE_CASE : Any = False if hasattr(lowercase , "base_model_prefix" ): SCREAMING_SNAKE_CASE : str = not hasattr(lowercase , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head SCREAMING_SNAKE_CASE : Optional[int] = list(model.named_children() ) SCREAMING_SNAKE_CASE : Optional[int] = [list_modules[-1][0]] # add last module together with tied weights SCREAMING_SNAKE_CASE : str = set(lowercase ) - set(lowercase ) SCREAMING_SNAKE_CASE : List[str] = list(set(lowercase ) ) + list(lowercase ) # remove ".weight" from the keys SCREAMING_SNAKE_CASE : str = [".weight", ".bias"] SCREAMING_SNAKE_CASE : List[Any] = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(lowercase , "" ) filtered_module_names.append(lowercase ) return filtered_module_names def lowerCamelCase__ ( lowercase ): """simple docstring""" for m in model.modules(): if isinstance(lowercase , bnb.nn.Linearabit ): return True return False def lowerCamelCase__ ( lowercase ): """simple docstring""" return next(parameter.parameters() ).device def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(lowercase , lowercase , 0 , dtype=lowercase , value=lowercase ) SCREAMING_SNAKE_CASE : str = param_name SCREAMING_SNAKE_CASE : List[str] = model if "." in tensor_name: SCREAMING_SNAKE_CASE : Dict = tensor_name.split("." ) for split in splits[:-1]: SCREAMING_SNAKE_CASE : Tuple = getattr(lowercase , lowercase ) if new_module is None: raise ValueError(F'''{module} has no attribute {split}.''' ) SCREAMING_SNAKE_CASE : Dict = new_module SCREAMING_SNAKE_CASE : List[str] = splits[-1] # offload weights SCREAMING_SNAKE_CASE : Tuple = False offload_weight(module._parameters[tensor_name] , lowercase , lowercase , index=lowercase ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , lowercase , index=lowercase , ) else: offload_weight(lowercase , lowercase , lowercase , index=lowercase ) offload_weight(lowercase , param_name.replace("weight" , "SCB" ) , lowercase , index=lowercase ) set_module_tensor_to_device(lowercase , lowercase , "meta" , dtype=lowercase , value=torch.empty(*param.size() ) )
62
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
0
from math import pow def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , ): if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count __UpperCAmelCase : Tuple = int(pow(__lowerCamelCase , __lowerCamelCase ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = backtrack( __lowerCamelCase , __lowerCamelCase , current_number + 1 , __lowerCamelCase , __lowerCamelCase ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. __UpperCAmelCase , __UpperCAmelCase : int = backtrack( __lowerCamelCase , __lowerCamelCase , current_number + 1 , __lowerCamelCase , __lowerCamelCase ) return current_sum, solutions_count def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : int ): if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( """Invalid input\n""" """needed_sum must be between 1 and 1000, power between 2 and 10.""" ) return backtrack(__lowerCamelCase , __lowerCamelCase , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
63
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
0
import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def A__ ( snake_case_ : Optional[Any] , snake_case_ : List[Any]=False ): SCREAMING_SNAKE_CASE__: Optional[int]= OmegaConf.load(snake_case_ ) if display: print(yaml.dump(OmegaConf.to_container(snake_case_ ) ) ) return config def A__ ( snake_case_ : str , snake_case_ : str=None , snake_case_ : Optional[int]=None ): if conf_path is None: SCREAMING_SNAKE_CASE__: int= '''./model_checkpoints/vqgan_only.yaml''' SCREAMING_SNAKE_CASE__: Optional[Any]= load_config(snake_case_ , display=snake_case_ ) SCREAMING_SNAKE_CASE__: Union[str, Any]= VQModel(**config.model.params ) if ckpt_path is None: SCREAMING_SNAKE_CASE__: Any= '''./model_checkpoints/vqgan_only.pt''' SCREAMING_SNAKE_CASE__: str= torch.load(snake_case_ , map_location=snake_case_ ) if ".ckpt" in ckpt_path: SCREAMING_SNAKE_CASE__: Optional[Any]= sd['''state_dict'''] model.load_state_dict(snake_case_ , strict=snake_case_ ) model.to(snake_case_ ) del sd return model def A__ ( snake_case_ : Optional[int] , snake_case_ : Optional[Any] ): SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: List[Any]= model.encode(snake_case_ ) print(F'VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}' ) SCREAMING_SNAKE_CASE__: Any= model.decode(snake_case_ ) return xrec def A__ ( snake_case_ : List[Any] , snake_case_ : List[str]=False ): SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Optional[int]= string.rsplit('''.''' , 1 ) if reload: SCREAMING_SNAKE_CASE__: int= importlib.import_module(snake_case_ ) importlib.reload(snake_case_ ) return getattr(importlib.import_module(snake_case_ , package=snake_case_ ) , cls ) def A__ ( snake_case_ : Tuple ): if "target" not in config: raise KeyError('''Expected key `target` to instantiate.''' ) return get_obj_from_str(config['''target'''] )(**config.get('''params''' , {} ) ) def A__ ( snake_case_ : Tuple , snake_case_ : Optional[int] , snake_case_ : Optional[int]=True , snake_case_ : Dict=True ): SCREAMING_SNAKE_CASE__: Tuple= instantiate_from_config(snake_case_ ) if sd is not None: model.load_state_dict(snake_case_ ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def A__ ( snake_case_ : List[str] , snake_case_ : Union[str, Any] , snake_case_ : Union[str, Any] , snake_case_ : Dict ): # load the specified checkpoint if ckpt: SCREAMING_SNAKE_CASE__: Dict= torch.load(snake_case_ , map_location='''cpu''' ) SCREAMING_SNAKE_CASE__: Dict= pl_sd['''global_step'''] print(F'loaded model from global step {global_step}.' ) else: SCREAMING_SNAKE_CASE__: Optional[int]= {'''state_dict''': None} SCREAMING_SNAKE_CASE__: List[Any]= None SCREAMING_SNAKE_CASE__: List[str]= load_model_from_config(config.model , pl_sd['''state_dict'''] , gpu=snake_case_ , eval_mode=snake_case_ )['''model'''] return model, global_step
64
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = 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 : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
0
"""simple docstring""" from collections.abc import Sequence def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' return sum(c * (x**i) for i, c in enumerate(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' UpperCAmelCase__ : List[str] = 0.0 for coeff in reversed(__UpperCamelCase ): UpperCAmelCase__ : Optional[int] = result * x + coeff return result if __name__ == "__main__": __UpperCAmelCase = (0.0, 0.0, 5.0, 9.3, 7.0) __UpperCAmelCase = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
65
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
0
def __magic_name__ ( SCREAMING_SNAKE_CASE = 3 , SCREAMING_SNAKE_CASE = 7 , SCREAMING_SNAKE_CASE = 1_000_000 ) -> int: _lowercase : Union[str, Any] = 0 _lowercase : Optional[int] = 1 for current_denominator in range(1 , limit + 1 ): _lowercase : str = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: _lowercase : List[Any] = current_numerator _lowercase : Any = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_000_000))
66
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf snake_case = logging.get_logger(__name__) @dataclass class A_ ( UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : str ,**__A : List[str] ) -> int: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: _lowercase = deprecated_arg[3:] _lowercase = not kwargs.pop(__A ) logger.warning( F"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" F""" {positive_arg}={kwargs[positive_arg]}""" ) _lowercase = kwargs.pop('tpu_name' ,self.tpu_name ) _lowercase = kwargs.pop('device_idx' ,self.device_idx ) _lowercase = kwargs.pop('eager_mode' ,self.eager_mode ) _lowercase = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**__A ) SCREAMING_SNAKE_CASE_ : str = field( default=UpperCAmelCase , metadata={'''help''': '''Name of TPU'''} , ) SCREAMING_SNAKE_CASE_ : int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) SCREAMING_SNAKE_CASE_ : bool = field(default=UpperCAmelCase , metadata={'''help''': '''Benchmark models in eager model.'''} ) SCREAMING_SNAKE_CASE_ : bool = field( default=UpperCAmelCase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def __UpperCAmelCase ( self : Optional[int] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) _lowercase = None if self.tpu: try: if self.tpu_name: _lowercase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: _lowercase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: _lowercase = None return tpu @cached_property def __UpperCAmelCase ( self : str ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) _lowercase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) _lowercase = tf.distribute.OneDeviceStrategy(device=F"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU _lowercase = tf.distribute.OneDeviceStrategy(device=F"""/cpu:{self.device_idx}""" ) return strategy @property def __UpperCAmelCase ( self : Any ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def __UpperCAmelCase ( self : Any ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def __UpperCAmelCase ( self : Any ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def __UpperCAmelCase ( self : List[Any] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __UpperCAmelCase ( self : Optional[Any] ) -> bool: return self.n_gpu > 0
67
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
0
from __future__ import annotations def lowercase__ ( A_: int ) -> bool: """simple docstring""" __UpperCAmelCase =str(A_ ) return len(A_ ) == 9 and set(A_ ) == set("""123456789""" ) def lowercase__ ( ) -> int | None: """simple docstring""" for base_num in range(9999 , 4999 , -1 ): __UpperCAmelCase =100002 * base_num if is_9_pandigital(A_ ): return candidate for base_num in range(333 , 99 , -1 ): __UpperCAmelCase =1002003 * base_num if is_9_pandigital(A_ ): return candidate return None if __name__ == "__main__": print(F"""{solution() = }""")
68
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
0
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): __SCREAMING_SNAKE_CASE = ["""image_processor""", """tokenizer"""] __SCREAMING_SNAKE_CASE = """LayoutLMv3ImageProcessor""" __SCREAMING_SNAKE_CASE = ("""LayoutLMv3Tokenizer""", """LayoutLMv3TokenizerFast""") def __init__( self : str , a_ : Dict=None , a_ : Dict=None , **a_ : Optional[int] ): """simple docstring""" __snake_case = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , a_ , ) __snake_case = kwargs.pop("feature_extractor" ) __snake_case = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Union[str, Any] , a_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a_ : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , a_ : Union[List[List[int]], List[List[List[int]]]] = None , a_ : Optional[Union[List[int], List[List[int]]]] = None , a_ : bool = True , a_ : Union[bool, str, PaddingStrategy] = False , a_ : Union[bool, str, TruncationStrategy] = None , a_ : Optional[int] = None , a_ : int = 0 , a_ : Optional[int] = None , a_ : Optional[bool] = None , a_ : Optional[bool] = None , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = True , a_ : Optional[Union[str, TensorType]] = None , **a_ : Tuple , ): """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) # first, apply the image processor __snake_case = self.image_processor(images=a_ , return_tensors=a_ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(a_ , a_ ): __snake_case = [text] # add batch dimension (as the image processor always adds a batch dimension) __snake_case = features["words"] __snake_case = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_token_type_ids=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) # add pixel values __snake_case = features.pop("pixel_values" ) if return_overflowing_tokens is True: __snake_case = self.get_overflowing_images(a_ , encoded_inputs["overflow_to_sample_mapping"] ) __snake_case = images return encoded_inputs def A ( self : List[Any] , a_ : int , a_ : int ): """simple docstring""" __snake_case = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(a_ ) != len(a_ ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f''' {len(a_ )} and {len(a_ )}''' ) return images_with_overflow def A ( self : str , *a_ : str , **a_ : List[str] ): """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def A ( self : str , *a_ : int , **a_ : Tuple ): """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def A ( self : Dict ): """simple docstring""" return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def A ( self : int ): """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , a_ , ) return self.image_processor_class @property def A ( self : Dict ): """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , a_ , ) return self.image_processor
69
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase : Any = { "configuration_m2m_100": ["M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP", "M2M100Config", "M2M100OnnxConfig"], "tokenization_m2m_100": ["M2M100Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = [ "M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST", "M2M100ForConditionalGeneration", "M2M100Model", "M2M100PreTrainedModel", ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
70
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = {"""configuration_plbart""": ["""PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PLBartConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ["""PLBartTokenizer"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ """PLBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """PLBartForCausalLM""", """PLBartForConditionalGeneration""", """PLBartForSequenceClassification""", """PLBartModel""", """PLBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
71
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
0
'''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 __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = ['image_processor', 'tokenizer'] UpperCamelCase__ = 'BlipImageProcessor' UpperCamelCase__ = 'AutoTokenizer' def __init__( self , snake_case_ , snake_case_ ): lowercase =False super().__init__(snake_case_ , snake_case_ ) lowercase =self.image_processor def __call__( self , snake_case_ = None , snake_case_ = None , snake_case_ = True , snake_case_ = False , snake_case_ = None , snake_case_ = None , snake_case_ = 0 , snake_case_ = None , snake_case_ = None , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = True , snake_case_ = None , **snake_case_ , ): 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: lowercase =self.tokenizer lowercase =self.tokenizer( text=snake_case_ , add_special_tokens=snake_case_ , padding=snake_case_ , truncation=snake_case_ , max_length=snake_case_ , stride=snake_case_ , pad_to_multiple_of=snake_case_ , return_attention_mask=snake_case_ , return_overflowing_tokens=snake_case_ , return_special_tokens_mask=snake_case_ , return_offsets_mapping=snake_case_ , return_token_type_ids=snake_case_ , return_length=snake_case_ , verbose=snake_case_ , return_tensors=snake_case_ , **snake_case_ , ) return text_encoding # add pixel_values lowercase =self.image_processor(snake_case_ , return_tensors=snake_case_ ) if text is not None: lowercase =self.tokenizer( text=snake_case_ , add_special_tokens=snake_case_ , padding=snake_case_ , truncation=snake_case_ , max_length=snake_case_ , stride=snake_case_ , pad_to_multiple_of=snake_case_ , return_attention_mask=snake_case_ , return_overflowing_tokens=snake_case_ , return_special_tokens_mask=snake_case_ , return_offsets_mapping=snake_case_ , return_token_type_ids=snake_case_ , return_length=snake_case_ , verbose=snake_case_ , return_tensors=snake_case_ , **snake_case_ , ) else: lowercase =None if text_encoding is not None: encoding_image_processor.update(snake_case_ ) return encoding_image_processor def _A( self , *snake_case_ , **snake_case_ ): return self.tokenizer.batch_decode(*snake_case_ , **snake_case_ ) def _A( self , *snake_case_ , **snake_case_ ): return self.tokenizer.decode(*snake_case_ , **snake_case_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _A( self ): lowercase =self.tokenizer.model_input_names lowercase =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
72
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 snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
0
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin a_ : List[str] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class _snake_case ( A__ , unittest.TestCase ): _lowercase : Tuple = XLNetTokenizer _lowercase : List[Any] = XLNetTokenizerFast _lowercase : int = True _lowercase : Any = True def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = XLNetTokenizer(a , keep_accents=a) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = '<s>' SCREAMING_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) -> Optional[int]: SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '<unk>') self.assertEqual(vocab_keys[1] , '<s>') self.assertEqual(vocab_keys[-1] , '<eod>') self.assertEqual(len(a) , 1006) def SCREAMING_SNAKE_CASE__ ( self) -> Any: self.assertEqual(self.get_tokenizer().vocab_size , 1000) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = XLNetTokenizer(a , keep_accents=a) SCREAMING_SNAKE_CASE = tokenizer.tokenize('This is a test') self.assertListEqual(a , ['▁This', '▁is', '▁a', '▁t', 'est']) self.assertListEqual(tokenizer.convert_tokens_to_ids(a) , [285, 46, 10, 170, 382]) SCREAMING_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', 'é', '.', ] , ) SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(a) self.assertListEqual(a , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]) SCREAMING_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>', '.', ] , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = XLNetTokenizer(a , do_lower_case=a) SCREAMING_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', 'se', '.', ] , ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo') , ['▁he', 'll', 'o']) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = XLNetTokenizer(a , do_lower_case=a) SCREAMING_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', 'se', '.', ] , ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = XLNetTokenizer.from_pretrained('xlnet-base-cased') SCREAMING_SNAKE_CASE = tokenizer.encode('sequence builders' , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer.encode('multi-sequence build' , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(a) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(a , a) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: # fmt: off SCREAMING_SNAKE_CASE = {'input_ids': [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2178, 27, 1064, 22, 956, 13, 1_1101, 1429, 5854, 2_4313, 1_8953, 40, 422, 2_4366, 68, 1758, 37, 1_0483, 1_4257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 1_3894, 3380, 23, 95, 18, 1_7634, 2288, 9, 4, 3]], '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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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='xlnet-base-cased' , revision='c841166438c31ec7ca9a106dee7bb312b73ae511' , )
73
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = StableDiffusionXLImgaImgPipeline lowerCAmelCase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} lowerCAmelCase_ = PipelineTesterMixin.required_optional_params - {'''latents'''} lowerCAmelCase_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCAmelCase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase__ ( self : Any ): """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , attention_head_dim=(2, 4) , use_linear_projection=_A , addition_embed_type='''text_time''' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) __SCREAMING_SNAKE_CASE : List[str] = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='''scaled_linear''' , timestep_spacing='''leading''' , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, 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=1000 , hidden_act='''gelu''' , projection_dim=32 , ) __SCREAMING_SNAKE_CASE : int = CLIPTextModel(_A ) __SCREAMING_SNAKE_CASE : Dict = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=_A ) __SCREAMING_SNAKE_CASE : List[str] = CLIPTextModelWithProjection(_A ) __SCREAMING_SNAKE_CASE : Any = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=_A ) __SCREAMING_SNAKE_CASE : int = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''text_encoder_2''': text_encoder_a, '''tokenizer_2''': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def UpperCAmelCase__ ( self : Any , _A : Union[str, Any] , _A : Tuple=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_A ) ).to(_A ) __SCREAMING_SNAKE_CASE : Tuple = image / 2 + 0.5 if str(_A ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_A ) else: __SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device=_A ).manual_seed(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 5.0, '''output_type''': '''numpy''', '''strength''': 0.75, } return inputs def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : List[Any] = StableDiffusionXLImgaImgPipeline(**_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe(**_A ).images __SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase__ ( self : int ): """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" pass def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionXLImgaImgPipeline(**_A ) __SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) # forward without prompt embeds __SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 3 * ['''this is a negative prompt'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = negative_prompt __SCREAMING_SNAKE_CASE : List[Any] = 3 * [inputs['''prompt''']] __SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe(**_A ) __SCREAMING_SNAKE_CASE : int = output.images[0, -3:, -3:, -1] # forward with prompt embeds __SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_inputs(_A ) __SCREAMING_SNAKE_CASE : Dict = 3 * ['''this is a negative prompt'''] __SCREAMING_SNAKE_CASE : str = 3 * [inputs.pop('''prompt''' )] ( ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ) : Tuple = sd_pipe.encode_prompt(_A , negative_prompt=_A ) __SCREAMING_SNAKE_CASE : Dict = sd_pipe( **_A , prompt_embeds=_A , negative_prompt_embeds=_A , pooled_prompt_embeds=_A , negative_pooled_prompt_embeds=_A , ) __SCREAMING_SNAKE_CASE : str = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : str , _A : Union[str, Any] , _A : Tuple="cpu" , _A : str=torch.floataa , _A : List[str]=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device=_A ).manual_seed(_A ) __SCREAMING_SNAKE_CASE : Dict = np.random.RandomState(_A ).standard_normal((1, 4, 64, 64) ) __SCREAMING_SNAKE_CASE : str = torch.from_numpy(_A ).to(device=_A , dtype=_A ) __SCREAMING_SNAKE_CASE : Tuple = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_inputs(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = pipe(**_A ).images __SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7e-3
74
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline UpperCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCamelCase_ ( __a ): def __init__( self : Dict , _A : List[str] , _A : int ): '''simple docstring''' super().__init__() self.register_modules(unet=_A , scheduler=_A ) @torch.no_grad() def __call__( self : List[Any] , _A : int = 1 , _A : int = 100 , _A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _A : Optional[float] = None , _A : bool = True , ): '''simple docstring''' if audio_length_in_s is None: UpperCAmelCase__ : List[str] = self.unet.config.sample_size / self.unet.config.sample_rate UpperCAmelCase__ : Union[str, Any] = audio_length_in_s * self.unet.config.sample_rate UpperCAmelCase__ : List[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__ : List[Any] = int(_A ) if sample_size % down_scale_factor != 0: UpperCAmelCase__ : int = ( (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__ : Dict = int(_A ) UpperCAmelCase__ : Optional[Any] = next(iter(self.unet.parameters() ) ).dtype UpperCAmelCase__ : int = (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__ : List[str] = self.scheduler.timesteps.to(_A ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCAmelCase__ : Optional[int] = self.unet(_A , _A ).sample # 2. compute previous image: x_t -> t_t-1 UpperCAmelCase__ : List[Any] = self.scheduler.step(_A , _A , _A ).prev_sample UpperCAmelCase__ : Any = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCAmelCase__ : Any = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=_A )
75
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
0
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path a_ = 'src/transformers' # Matches is_xxx_available() a_ = re.compile(r'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} a_ = re.compile(r'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] a_ = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available a_ = re.compile(r'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") a_ = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] a_ = re.compile(r'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", a_ = re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], a_ = re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo a_ = re.compile(r'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: a_ = re.compile(r'^\s*try:') # Catches a line with else: a_ = re.compile(r'^\s*else:') def __UpperCAmelCase ( __UpperCamelCase ): if _re_test_backend.search(__UpperCamelCase ) is None: return None __lowercase : List[str] = [b[0] for b in _re_backend.findall(__UpperCamelCase )] backends.sort() return "_and_".join(__UpperCamelCase ) def __UpperCAmelCase ( __UpperCamelCase ): with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __lowercase : Tuple = f.readlines() __lowercase : str = 0 while line_index < len(__UpperCamelCase ) and not lines[line_index].startswith('''_import_structure = {''' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(__UpperCamelCase ): return None # First grab the objects without a specific backend in _import_structure __lowercase : List[str] = [] while not lines[line_index].startswith('''if TYPE_CHECKING''' ) and find_backend(lines[line_index] ) is None: __lowercase : List[Any] = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(__UpperCamelCase ): __lowercase : int = _re_one_line_import_struct.search(__UpperCamelCase ).groups()[0] __lowercase : Union[str, Any] = re.findall('''\[([^\]]+)\]''' , __UpperCamelCase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(''', ''' )] ) line_index += 1 continue __lowercase : Tuple = _re_import_struct_key_value.search(__UpperCamelCase ) if single_line_import_search is not None: __lowercase : Tuple = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', ''' ) if len(__UpperCamelCase ) > 0] objects.extend(__UpperCamelCase ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) line_index += 1 __lowercase : Optional[Any] = {'''none''': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('''if TYPE_CHECKING''' ): # If the line is an if not is_backend_available, we grab all objects associated. __lowercase : Dict = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __lowercase : str = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __lowercase : Optional[Any] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 4 ): __lowercase : Union[str, Any] = lines[line_index] if _re_import_struct_add_one.search(__UpperCamelCase ) is not None: objects.append(_re_import_struct_add_one.search(__UpperCamelCase ).groups()[0] ) elif _re_import_struct_add_many.search(__UpperCamelCase ) is not None: __lowercase : Optional[Any] = _re_import_struct_add_many.search(__UpperCamelCase ).groups()[0].split(''', ''' ) __lowercase : Tuple = [obj[1:-1] for obj in imports if len(__UpperCamelCase ) > 0] objects.extend(__UpperCamelCase ) elif _re_between_brackets.search(__UpperCamelCase ) is not None: __lowercase : int = _re_between_brackets.search(__UpperCamelCase ).groups()[0].split(''', ''' ) __lowercase : int = [obj[1:-1] for obj in imports if len(__UpperCamelCase ) > 0] objects.extend(__UpperCamelCase ) elif _re_quote_object.search(__UpperCamelCase ) is not None: objects.append(_re_quote_object.search(__UpperCamelCase ).groups()[0] ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) elif line.startswith(''' ''' * 12 + '''"''' ): objects.append(line[13:-3] ) line_index += 1 __lowercase : str = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __lowercase : Union[str, Any] = [] while ( line_index < len(__UpperCamelCase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('''else''' ) ): __lowercase : List[str] = lines[line_index] __lowercase : Optional[Any] = _re_import.search(__UpperCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 __lowercase : Tuple = {'''none''': objects} # Let's continue with backend-specific objects while line_index < len(__UpperCamelCase ): # If the line is an if is_backend_available, we grab all objects associated. __lowercase : List[Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __lowercase : Dict = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __lowercase : Optional[int] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 8 ): __lowercase : Optional[Any] = lines[line_index] __lowercase : Optional[int] = _re_import.search(__UpperCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 12 ): objects.append(line[12:-2] ) line_index += 1 __lowercase : List[Any] = objects else: line_index += 1 return import_dict_objects, type_hint_objects def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): def find_duplicates(__UpperCamelCase ): return [k for k, v in collections.Counter(__UpperCamelCase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __lowercase : List[str] = [] for key in import_dict_objects.keys(): __lowercase : Optional[int] = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f"""Duplicate _import_structure definitions for: {duplicate_imports}""" ) __lowercase : List[Any] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f"""Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}""" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __lowercase : List[Any] = '''base imports''' if key == '''none''' else f"""{key} backend""" errors.append(f"""Differences for {name}:""" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f""" {a} in TYPE_HINT but not in _import_structure.""" ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f""" {a} in _import_structure but not in TYPE_HINT.""" ) return errors def __UpperCAmelCase ( ): __lowercase : Tuple = [] for root, _, files in os.walk(__UpperCamelCase ): if "__init__.py" in files: __lowercase : Optional[int] = os.path.join(__UpperCamelCase , '''__init__.py''' ) __lowercase : Dict = parse_init(__UpperCamelCase ) if objects is not None: __lowercase : Dict = analyze_results(*__UpperCamelCase ) if len(__UpperCamelCase ) > 0: __lowercase : str = f"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}""" failures.append('''\n'''.join(__UpperCamelCase ) ) if len(__UpperCamelCase ) > 0: raise ValueError('''\n\n'''.join(__UpperCamelCase ) ) def __UpperCAmelCase ( ): __lowercase : int = [] for path, directories, files in os.walk(__UpperCamelCase ): for folder in directories: # Ignore private modules if folder.startswith('''_''' ): directories.remove(__UpperCamelCase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(__UpperCamelCase ) / folder).glob('''*.py''' ) ) ) == 0: continue __lowercase : Tuple = str((Path(__UpperCamelCase ) / folder).relative_to(__UpperCamelCase ) ) __lowercase : List[Any] = short_path.replace(os.path.sep , '''.''' ) submodules.append(__UpperCamelCase ) for fname in files: if fname == "__init__.py": continue __lowercase : Optional[Any] = str((Path(__UpperCamelCase ) / fname).relative_to(__UpperCamelCase ) ) __lowercase : List[str] = short_path.replace('''.py''' , '''''' ).replace(os.path.sep , '''.''' ) if len(submodule.split('''.''' ) ) == 1: submodules.append(__UpperCamelCase ) return submodules a_ = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def __UpperCAmelCase ( ): # This is to make sure the transformers module imported is the one in the repo. __lowercase : str = importlib.util.spec_from_file_location( '''transformers''' , os.path.join(__UpperCamelCase , '''__init__.py''' ) , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) __lowercase : List[Any] = spec.loader.load_module() __lowercase : int = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(__UpperCamelCase ) > 0: __lowercase : Optional[Any] = '''\n'''.join(f"""- {module}""" for module in module_not_registered ) raise ValueError( '''The following submodules are not properly registered in the main init of Transformers:\n''' f"""{list_of_modules}\n""" '''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.''' ) if __name__ == "__main__": check_all_inits() check_submodules()
76
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _UpperCamelCase ( UpperCamelCase = 8 ) -> str: """simple docstring""" __UpperCAmelCase : List[Any] = ascii_letters + digits + punctuation return "".join(secrets.choice(UpperCamelCase ) for _ in range(UpperCamelCase ) ) def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> str: """simple docstring""" # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(UpperCamelCase ) __UpperCAmelCase : int = i // 3 __UpperCAmelCase : Optional[int] = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) __UpperCAmelCase : Optional[Any] = ( chars_incl + random(UpperCamelCase , quotient + remainder ) + random(UpperCamelCase , UpperCamelCase ) + random(UpperCamelCase , UpperCamelCase ) ) __UpperCAmelCase : Union[str, Any] = list(UpperCamelCase ) shuffle(UpperCamelCase ) return "".join(UpperCamelCase ) # random is a generalised function for letters, characters and numbers def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> str: """simple docstring""" return "".join(secrets.choice(UpperCamelCase ) for _ in range(UpperCamelCase ) ) def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> Optional[Any]: """simple docstring""" pass # Put your code here... def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> Any: """simple docstring""" pass # Put your code here... def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> Union[str, Any]: """simple docstring""" pass # Put your code here... def _UpperCamelCase ( UpperCamelCase , UpperCamelCase = 8 ) -> bool: """simple docstring""" if len(UpperCamelCase ) < min_length: # Your Password must be at least 8 characters long return False __UpperCAmelCase : Tuple = any(char in ascii_uppercase for char in password ) __UpperCAmelCase : Optional[int] = any(char in ascii_lowercase for char in password ) __UpperCAmelCase : Optional[int] = any(char in digits for char in password ) __UpperCAmelCase : Any = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _UpperCamelCase ( ) -> Dict: """simple docstring""" __UpperCAmelCase : str = int(input("Please indicate the max length of your password: " ).strip() ) __UpperCAmelCase : Dict = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:" , password_generator(UpperCamelCase ) ) print( "Alternative Password generated:" , alternative_password_generator(UpperCamelCase , UpperCamelCase ) , ) print("[If you are thinking of using this passsword, You better save it.]" ) if __name__ == "__main__": main()
77
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
0
'''simple docstring''' from math import sqrt def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and ( number >= 0 ), "'number' must been an int and positive" UpperCAmelCase_ = True # 0 and 1 are none primes. if number <= 1: UpperCAmelCase_ = False for divisor in range(2 , int(round(sqrt(snake_case_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: UpperCAmelCase_ = False break # precondition assert isinstance(snake_case_ , snake_case_ ), "'status' must been from type bool" return status def lowerCAmelCase_ ( snake_case_ : List[str] ) -> List[Any]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N UpperCAmelCase_ = list(range(2 , n + 1 ) ) UpperCAmelCase_ = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(snake_case_ ) ): for j in range(i + 1 , len(snake_case_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): UpperCAmelCase_ = 0 # filters actual prime numbers. UpperCAmelCase_ = [x for x in begin_list if x != 0] # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type list" return ans def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Dict: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and (n > 2), "'N' must been an int and > 2" UpperCAmelCase_ = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(snake_case_ ): ans.append(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type list" return ans def lowerCAmelCase_ ( snake_case_ : Any ) -> int: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and number >= 0, "'number' must been an int and >= 0" UpperCAmelCase_ = [] # this list will be returns of the function. # potential prime number factors. UpperCAmelCase_ = 2 UpperCAmelCase_ = number if number == 0 or number == 1: ans.append(snake_case_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(snake_case_ ): while quotient != 1: if is_prime(snake_case_ ) and (quotient % factor == 0): ans.append(snake_case_ ) quotient /= factor else: factor += 1 else: ans.append(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type list" return ans def lowerCAmelCase_ ( snake_case_ : List[str] ) -> List[Any]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCAmelCase_ = 0 # prime factorization of 'number' UpperCAmelCase_ = prime_factorization(snake_case_ ) UpperCAmelCase_ = max(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type int" return ans def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCAmelCase_ = 0 # prime factorization of 'number' UpperCAmelCase_ = prime_factorization(snake_case_ ) UpperCAmelCase_ = min(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type int" return ans def lowerCAmelCase_ ( snake_case_ : List[str] ) -> List[str]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , snake_case_ ), "compare bust been from type bool" return number % 2 == 0 def lowerCAmelCase_ ( snake_case_ : Dict ) -> Any: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , snake_case_ ), "compare bust been from type bool" return number % 2 != 0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Any: '''simple docstring''' assert ( isinstance(snake_case_ , snake_case_ ) and (number > 2) and is_even(snake_case_ ) ), "'number' must been an int, even and > 2" UpperCAmelCase_ = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' UpperCAmelCase_ = get_prime_numbers(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # run variable for while-loops. UpperCAmelCase_ = 0 UpperCAmelCase_ = None # exit variable. for break up the loops UpperCAmelCase_ = True while i < len_pn and loop: UpperCAmelCase_ = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: UpperCAmelCase_ = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(snake_case_ , snake_case_ ) and (len(snake_case_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Optional[int] ) -> Optional[int]: '''simple docstring''' assert ( isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." UpperCAmelCase_ = 0 while numbera != 0: UpperCAmelCase_ = numbera % numbera UpperCAmelCase_ = numbera UpperCAmelCase_ = rest # precondition assert isinstance(snake_case_ , snake_case_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : Tuple ) -> Tuple: '''simple docstring''' assert ( isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." UpperCAmelCase_ = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' UpperCAmelCase_ = prime_factorization(snake_case_ ) UpperCAmelCase_ = prime_factorization(snake_case_ ) elif numbera == 1 or numbera == 1: UpperCAmelCase_ = [] UpperCAmelCase_ = [] UpperCAmelCase_ = max(snake_case_ , snake_case_ ) UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 UpperCAmelCase_ = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: UpperCAmelCase_ = prime_fac_a.count(snake_case_ ) UpperCAmelCase_ = prime_fac_a.count(snake_case_ ) for _ in range(max(snake_case_ , snake_case_ ) ): ans *= n else: UpperCAmelCase_ = prime_fac_a.count(snake_case_ ) for _ in range(snake_case_ ): ans *= n done.append(snake_case_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: UpperCAmelCase_ = prime_fac_a.count(snake_case_ ) for _ in range(snake_case_ ): ans *= n done.append(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and (n >= 0), "'number' must been a positive int" UpperCAmelCase_ = 0 UpperCAmelCase_ = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(snake_case_ ): ans += 1 # precondition assert isinstance(snake_case_ , snake_case_ ) and is_prime( snake_case_ ), "'ans' must been a prime number and from type int" return ans def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : Tuple ) -> List[str]: '''simple docstring''' assert ( is_prime(snake_case_ ) and is_prime(snake_case_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" UpperCAmelCase_ = p_number_a + 1 # jump to the next number UpperCAmelCase_ = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(snake_case_ ): number += 1 while number < p_number_a: ans.append(snake_case_ ) number += 1 # fetch the next prime number. while not is_prime(snake_case_ ): number += 1 # precondition assert ( isinstance(snake_case_ , snake_case_ ) and ans[0] != p_number_a and ans[len(snake_case_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Union[str, Any]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and (n >= 1), "'n' must been int and >= 1" UpperCAmelCase_ = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(snake_case_ ) # precondition assert ans[0] == 1 and ans[len(snake_case_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def lowerCAmelCase_ ( snake_case_ : List[str] ) -> str: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and ( number > 1 ), "'number' must been an int and >= 1" UpperCAmelCase_ = get_divisors(snake_case_ ) # precondition assert ( isinstance(snake_case_ , snake_case_ ) and (divisors[0] == 1) and (divisors[len(snake_case_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) -> int: '''simple docstring''' assert ( isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. UpperCAmelCase_ = gcd(abs(snake_case_ ) , abs(snake_case_ ) ) # precondition assert ( isinstance(snake_case_ , snake_case_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def lowerCAmelCase_ ( snake_case_ : int ) -> List[str]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and (n >= 0), "'n' must been a int and >= 0" UpperCAmelCase_ = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def lowerCAmelCase_ ( snake_case_ : List[str] ) -> Optional[Any]: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ) and (n >= 0), "'n' must been an int and >= 0" UpperCAmelCase_ = 0 UpperCAmelCase_ = 1 UpperCAmelCase_ = 1 # this will be return for _ in range(n - 1 ): UpperCAmelCase_ = ans ans += fiba UpperCAmelCase_ = tmp return ans
78
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
0
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( __lowerCamelCase ): def __init__( self , *_lowerCAmelCase , **_lowerCAmelCase ): warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , _lowerCAmelCase , ) super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
79
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
0