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 torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = (DDIMParallelScheduler,) lowerCamelCase_ : Tuple = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def lowerCamelCase (self , **__magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : List[str] = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**__magic_name__ ) return config def lowerCamelCase (self , **__magic_name__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.scheduler_classes[0] snake_case_ : Tuple = self.get_scheduler_config(**__magic_name__ ) snake_case_ : List[Any] = scheduler_class(**__magic_name__ ) snake_case_ , snake_case_ : Optional[Any] = 10, 0.0 snake_case_ : Union[str, Any] = self.dummy_model() snake_case_ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(__magic_name__ ) for t in scheduler.timesteps: snake_case_ : Optional[int] = model(__magic_name__ , __magic_name__ ) snake_case_ : Tuple = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ).prev_sample return sample def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__magic_name__ ) snake_case_ : int = self.scheduler_classes[0] snake_case_ : List[str] = self.get_scheduler_config(steps_offset=1 ) snake_case_ : Optional[int] = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__magic_name__ , beta_end=__magic_name__ ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__magic_name__ ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__magic_name__ ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' self.check_over_configs(thresholding=__magic_name__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__magic_name__ , prediction_type=__magic_name__ , sample_max_value=__magic_name__ , ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for t in [1, 10, 49]: self.check_over_forward(time_step=__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__magic_name__ , num_inference_steps=__magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__magic_name__ , eta=__magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.scheduler_classes[0] snake_case_ : List[Any] = self.get_scheduler_config() snake_case_ : Optional[Any] = scheduler_class(**__magic_name__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Any = self.scheduler_classes[0] snake_case_ : int = self.get_scheduler_config() snake_case_ : List[str] = scheduler_class(**__magic_name__ ) snake_case_ , snake_case_ : Any = 10, 0.0 scheduler.set_timesteps(__magic_name__ ) snake_case_ : List[Any] = self.dummy_model() snake_case_ : Tuple = self.dummy_sample_deter snake_case_ : Optional[Any] = self.dummy_sample_deter + 0.1 snake_case_ : Optional[Any] = self.dummy_sample_deter - 0.1 snake_case_ : str = samplea.shape[0] snake_case_ : Any = torch.stack([samplea, samplea, samplea] , dim=0 ) snake_case_ : Any = torch.arange(__magic_name__ )[0:3, None].repeat(1 , __magic_name__ ) snake_case_ : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) snake_case_ : List[Any] = scheduler.batch_step_no_noise(__magic_name__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __magic_name__ ) snake_case_ : str = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : Optional[int] = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Any = self.full_loop() snake_case_ : Optional[Any] = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : Tuple = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Optional[Any] = self.full_loop(prediction_type='''v_prediction''' ) snake_case_ : Optional[int] = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : List[str] = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.full_loop(set_alpha_to_one=__magic_name__ , beta_start=0.01 ) snake_case_ : Optional[Any] = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : Dict = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = self.full_loop(set_alpha_to_one=__magic_name__ , beta_start=0.01 ) snake_case_ : int = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : List[str] = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
60
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
68
0
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = (KDPMaDiscreteScheduler,) snake_case__ = 1_0 def a ( self : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Tuple: lowerCAmelCase__ = { "num_train_timesteps": 1_100, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**SCREAMING_SNAKE_CASE__ ) return config def a ( self : Optional[Any] ) -> Union[str, Any]: for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def a ( self : str ) -> Optional[int]: for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def a ( self : Dict ) -> List[Any]: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> Optional[Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config(prediction_type="v_prediction" ) lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6_9_3_4e-0_7 ) < 1e-2 assert abs(result_mean.item() - 6.1_1_1_2e-1_0 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 4.6_9_3_4_2_8_6_5_0_1_7_0_9_7_2e-0_7 ) < 1e-2 assert abs(result_mean.item() - 0.0_002 ) < 1e-3 def a ( self : Dict ) -> Tuple: if torch_device == "mps": return lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3 def a ( self : Optional[int] ) -> Dict: if torch_device == "mps": return lowerCAmelCase__ = self.scheduler_classes[0] lowerCAmelCase__ = self.get_scheduler_config() lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.dummy_model() lowerCAmelCase__ = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: lowerCAmelCase__ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = output.prev_sample lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if str(SCREAMING_SNAKE_CASE__ ).startswith("cpu" ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1e-2 assert abs(result_mean.item() - 0.0_266 ) < 1e-3
61
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _A ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Optional[Any]=99 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : int=5 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : str=37 , __SCREAMING_SNAKE_CASE : Union[str, Any]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : str=512 , __SCREAMING_SNAKE_CASE : Dict=16 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : List[str]=4 , ) -> Optional[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =seq_length __UpperCAmelCase =is_training __UpperCAmelCase =use_attention_mask __UpperCAmelCase =use_token_type_ids __UpperCAmelCase =use_labels __UpperCAmelCase =vocab_size __UpperCAmelCase =hidden_size __UpperCAmelCase =num_hidden_layers __UpperCAmelCase =num_attention_heads __UpperCAmelCase =intermediate_size __UpperCAmelCase =hidden_act __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =max_position_embeddings __UpperCAmelCase =type_vocab_size __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =initializer_range __UpperCAmelCase =num_choices def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase =None if self.use_attention_mask: __UpperCAmelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase =None if self.use_token_type_ids: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase =RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def _a ( self : List[str] ) -> Dict: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase =True __UpperCAmelCase =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] = True lowerCamelCase : Union[str, Any] = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =FlaxRobertaModelTester(self ) @slow def _a ( self : Optional[Any] ) -> List[Any]: for model_class_name in self.all_model_classes: __UpperCAmelCase =model_class_name.from_pretrained("""roberta-base""" , from_pt=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model(np.ones((1, 1) ) ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
68
0
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
62
from __future__ import annotations def lowercase__ ( A_: list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(A_ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
68
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_600, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_600, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class a ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self : List[str] ) -> Dict: if self.framework == "pytorch": subprocess.run( f"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding="""utf-8""" , check=__lowercase , ) assert hasattr(self , """env""" ) def UpperCAmelCase ( self : List[str] , __lowercase : Optional[Any] ) -> Any: # configuration for running training on smdistributed Model Parallel __UpperCAmelCase : List[Any] = { """enabled""": True, """processes_per_host""": 8, } __UpperCAmelCase : Optional[int] = { """enabled""": True, """parameters""": { """microbatches""": 4, """placement_strategy""": """spread""", """pipeline""": """interleaved""", """optimize""": """speed""", """partitions""": 4, """ddp""": True, }, } __UpperCAmelCase : Tuple = {"""smdistributed""": {"""modelparallel""": smp_options}, """mpi""": mpi_options} __UpperCAmelCase : Dict = """trainer""" if self.script == """run_glue.py""" else """smtrainer""" # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f"""{self.env.base_job_name}-{instance_count}-smp-{name_extension}""" , instance_count=__lowercase , instance_type=self.instance_type , debugger_hook_config=__lowercase , hyperparameters={ **self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path, """max_steps""": 500, } , metric_definitions=self.env.metric_definitions , distribution=__lowercase , py_version="""py36""" , ) def UpperCAmelCase ( self : List[str] , __lowercase : Optional[int] ) -> str: TrainingJobAnalytics(__lowercase ).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(1,)] ) def UpperCAmelCase ( self : Dict , __lowercase : Union[str, Any] ) -> Tuple: # create estimator __UpperCAmelCase : List[str] = self.create_estimator(__lowercase ) # run training estimator.fit() # result dataframe __UpperCAmelCase : Any = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __UpperCAmelCase : int = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""] ) __UpperCAmelCase : str = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __UpperCAmelCase : Dict = ( Session().describe_training_job(estimator.latest_training_job.name ).get("""TrainingTimeInSeconds""" , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy ) assert all(t <= self.results["""eval_loss"""] for t in eval_loss ) # dump tests result into json file to share in PR with open(f"""{estimator.latest_training_job.name}.json""" , """w""" ) as outfile: json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} , __lowercase )
63
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowercase__ ( A_: int , A_: int , A_: int , A_: int , A_: int , A_: int ) -> np.ndarray: """simple docstring""" if (ksize % 2) == 0: __UpperCAmelCase =ksize + 1 __UpperCAmelCase =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(A_ ): for x in range(A_ ): # distance from center __UpperCAmelCase =x - ksize // 2 __UpperCAmelCase =y - ksize // 2 # degree to radiant __UpperCAmelCase =theta / 180 * np.pi __UpperCAmelCase =np.cos(_theta ) __UpperCAmelCase =np.sin(_theta ) # get kernel x __UpperCAmelCase =cos_theta * px + sin_theta * py # get kernel y __UpperCAmelCase =-sin_theta * px + cos_theta * py # fill kernel __UpperCAmelCase =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __A = imread("../image_data/lena.jpg") # turn image in gray scale value __A = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __A = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 1_20, 1_50]: __A = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __A = out / out.max() * 2_55 __A = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
68
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _lowerCamelCase ( UpperCamelCase_ ): __a = "facebook/bart-large-mnli" __a = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) __a = "text_classifier" __a = AutoTokenizer __a = AutoModelForSequenceClassification __a = ["text", ["text"]] __a = ["text"] def UpperCamelCase_ ( self ) -> Optional[Any]: super().setup() SCREAMING_SNAKE_CASE__: str= self.model.config SCREAMING_SNAKE_CASE__: Optional[Any]= -1 for idx, label in config.idalabel.items(): if label.lower().startswith('''entail''' ): SCREAMING_SNAKE_CASE__: Optional[Any]= int(lowerCAmelCase ) if self.entailment_id == -1: raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''' ) def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__: Dict= labels return self.pre_processor( [text] * len(lowerCAmelCase ) , [f'This example is {label}' for label in labels] , return_tensors='''pt''' , padding='''max_length''' , ) def UpperCamelCase_ ( self , lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__: str= outputs.logits SCREAMING_SNAKE_CASE__: Optional[int]= torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
64
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : """simple docstring""" def __init__( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , __SCREAMING_SNAKE_CASE : List[str]=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=[1, 2, 1] , __SCREAMING_SNAKE_CASE : List[Any]=[2, 2, 4] , __SCREAMING_SNAKE_CASE : str=2 , __SCREAMING_SNAKE_CASE : Any=2.0 , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Dict=0.0 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : Any="gelu" , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : List[Any]=0.02 , __SCREAMING_SNAKE_CASE : Tuple=1e-5 , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Any=10 , __SCREAMING_SNAKE_CASE : Dict=8 , ) -> List[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =image_size __UpperCAmelCase =patch_size __UpperCAmelCase =num_channels __UpperCAmelCase =embed_dim __UpperCAmelCase =depths __UpperCAmelCase =num_heads __UpperCAmelCase =window_size __UpperCAmelCase =mlp_ratio __UpperCAmelCase =qkv_bias __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =drop_path_rate __UpperCAmelCase =hidden_act __UpperCAmelCase =use_absolute_embeddings __UpperCAmelCase =patch_norm __UpperCAmelCase =layer_norm_eps __UpperCAmelCase =initializer_range __UpperCAmelCase =is_training __UpperCAmelCase =scope __UpperCAmelCase =use_labels __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =encoder_stride def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase =None if self.use_labels: __UpperCAmelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase =self.get_config() return config, pixel_values, labels def _a ( self : List[Any] ) -> Optional[Any]: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: __UpperCAmelCase =SwinvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase =int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> Tuple: __UpperCAmelCase =SwinvaForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase =1 __UpperCAmelCase =SwinvaForMaskedImageModeling(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: __UpperCAmelCase =self.type_sequence_label_size __UpperCAmelCase =SwinvaForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self : List[str] ) -> Tuple: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[int] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCamelCase : Tuple = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowerCamelCase : Dict = False lowerCamelCase : Tuple = False lowerCamelCase : List[str] = False lowerCamelCase : Tuple = False def _a ( self : str ) -> str: __UpperCAmelCase =SwinvaModelTester(self ) __UpperCAmelCase =ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , embed_dim=37 ) def _a ( self : List[Any] ) -> Optional[int]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self : str ) -> str: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def _a ( self : Tuple ) -> Tuple: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def _a ( self : Optional[Any] ) -> int: pass def _a ( self : Tuple ) -> int: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def _a ( self : str ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase =[*signature.parameters.keys()] __UpperCAmelCase =["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =True for model_class in self.all_model_classes: __UpperCAmelCase =True __UpperCAmelCase =False __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions __UpperCAmelCase =len(self.model_tester.depths ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase =True __UpperCAmelCase =config.window_size**2 __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase =len(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __UpperCAmelCase =True __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase =self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase =2 self.assertEqual(out_len + added_hidden_states , len(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> int: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.hidden_states __UpperCAmelCase =getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # Swinv2 has a different seq_length __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase =outputs.reshaped_hidden_states self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =reshaped_hidden_states[0].shape __UpperCAmelCase =( reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self : str ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =3 __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Dict: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def _a ( self : int ) -> Dict: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase =SwinvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def _a ( self : Dict ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =_config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __UpperCAmelCase =model_class(config=__SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _A ( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self : Tuple ) -> Dict: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def _a ( self : int ) -> Optional[int]: __UpperCAmelCase =SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.default_image_processor __UpperCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase =image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE ) # verify the logits __UpperCAmelCase =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
68
0
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ : Any = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 20, """a """ * 30, """b """ * 7], } UpperCAmelCase__ : Union[str, Any] = Dataset.from_dict(__UpperCamelCase ) return dataset class __lowercase ( __lowerCamelCase ): def __lowercase ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Any = get_dataset() UpperCAmelCase__ : int = make_duplicate_clusters(A ,0.8_5 ) self.assertEqual(len(duplicate_clusters[0] ) ,2 ) def __lowercase ( self : Tuple ): '''simple docstring''' UpperCAmelCase__ : Tuple = get_dataset() UpperCAmelCase__ , UpperCAmelCase__ : Dict = deduplicate_dataset(A ) self.assertEqual(len(A ) ,2 ) print(A ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] ,2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] ,A )
65
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A = logging.get_logger(__name__) __A = {"vocab_file": "spiece.model"} __A = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } __A = { "AI-Sweden/gpt-sw3-126m": 20_48, "AI-Sweden/gpt-sw3-350m": 20_48, "AI-Sweden/gpt-sw3-1.6b": 20_48, "AI-Sweden/gpt-sw3-6.7b": 20_48, "AI-Sweden/gpt-sw3-20b": 20_48, } class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : int = VOCAB_FILES_NAMES lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : List[str]=False , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Optional[Dict[str, Any]] = None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> None: __UpperCAmelCase ={} if sp_model_kwargs is None else sp_model_kwargs __UpperCAmelCase =kwargs.get("""name_or_path""" ) if name_or_path is None: logger.warning( """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,""" """ you are testing the model, this can safely be ignored""" ) __UpperCAmelCase ="""None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __UpperCAmelCase ="""<|endoftext|>""" if eos_token is None else eos_token __UpperCAmelCase ="""<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __UpperCAmelCase =unk_token if pad_token is None else pad_token __UpperCAmelCase =eos_token if bos_token is None else bos_token else: __UpperCAmelCase ="""<pad>""" if pad_token is None else pad_token __UpperCAmelCase ="""<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=__SCREAMING_SNAKE_CASE , remove_space=__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) __UpperCAmelCase =do_lower_case __UpperCAmelCase =remove_space __UpperCAmelCase =keep_accents __UpperCAmelCase =vocab_file __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) # Used for whitespace normalization in input texts # fmt : off __UpperCAmelCase ={""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __UpperCAmelCase =re.compile( f'''[{"".join(map(__SCREAMING_SNAKE_CASE , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self : Any ) -> str: __UpperCAmelCase =self.__dict__.copy() __UpperCAmelCase =None return state def __setstate__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: __UpperCAmelCase =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __UpperCAmelCase ={} __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def _a ( self : Union[str, Any] ) -> int: return len(self.sp_model ) def _a ( self : Dict , __SCREAMING_SNAKE_CASE : str ) -> str: __UpperCAmelCase =self.non_printing_characters_re.sub("""""" , __SCREAMING_SNAKE_CASE ) # Normalize whitespaces __UpperCAmelCase ="""""".join([char if char not in self.whitespaces else """ """ for char in text] ) # NFC Unicode normalization __UpperCAmelCase =unicodedata.normalize("""NFC""" , __SCREAMING_SNAKE_CASE ) return text def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str ) -> int: return self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : int ) -> str: return self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) @staticmethod def _a ( __SCREAMING_SNAKE_CASE : str ) -> str: return out_string def _a ( self : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> str: __UpperCAmelCase =[] __UpperCAmelCase ="""""" __UpperCAmelCase =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token __UpperCAmelCase =True __UpperCAmelCase =[] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =False out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string def _a ( self : Any ) -> Dict[str, int]: __UpperCAmelCase ={self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __UpperCAmelCase =os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , """wb""" ) as fi: __UpperCAmelCase =self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, List[str]] , __SCREAMING_SNAKE_CASE : Union[str, bool] = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) else: __UpperCAmelCase =[self.preprocess_text(__SCREAMING_SNAKE_CASE ) for t in text] __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) if return_tensors is True or return_tensors == "pt": __UpperCAmelCase =torch.tensor(__SCREAMING_SNAKE_CASE ) return token_ids def _a ( self : str , __SCREAMING_SNAKE_CASE : Union[int, List[int]] ) -> str: return self.sp_model.decode(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : "Conversation" ) -> List[int]: __UpperCAmelCase =[f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __UpperCAmelCase =( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(__SCREAMING_SNAKE_CASE ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=__SCREAMING_SNAKE_CASE )
68
0
from functools import lru_cache def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> set: _lowercase : Union[str, Any] = 2 _lowercase : Optional[Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(SCREAMING_SNAKE_CASE ) if n > 1: factors.add(SCREAMING_SNAKE_CASE ) return factors @lru_cache def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> int: return len(unique_prime_factors(SCREAMING_SNAKE_CASE ) ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> bool: return len(set(SCREAMING_SNAKE_CASE ) ) in (0, 1) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> list: _lowercase : Tuple = 2 while True: # Increment each value of a generated range _lowercase : List[str] = [base + i for i in range(SCREAMING_SNAKE_CASE )] # Run elements through out unique_prime_factors function # Append our target number to the end. _lowercase : List[str] = [upf_len(SCREAMING_SNAKE_CASE ) for x in group] checker.append(SCREAMING_SNAKE_CASE ) # If all numbers in the list are equal, return the group variable. if equality(SCREAMING_SNAKE_CASE ): return group # Increment our base variable by 1 base += 1 def __magic_name__ ( SCREAMING_SNAKE_CASE = 4 ) -> int: _lowercase : Dict = run(SCREAMING_SNAKE_CASE ) return results[0] if len(SCREAMING_SNAKE_CASE ) else None if __name__ == "__main__": print(solution())
66
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __A = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : Union[str, None] = None , __SCREAMING_SNAKE_CASE : Union[List[str], None] = None , __SCREAMING_SNAKE_CASE : Union[str, List[str], None] = None , __SCREAMING_SNAKE_CASE : bool = True , ) -> List[str]: __UpperCAmelCase =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )] if identifier is not None: __UpperCAmelCase =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n_ in n_identifier: __UpperCAmelCase =[file for file in files if n_ not in file] else: __UpperCAmelCase =[file for file in files if n_identifier not in file] __UpperCAmelCase =ignore_files or [] ignore_files.append("""__init__.py""" ) __UpperCAmelCase =[file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , __SCREAMING_SNAKE_CASE ) if only_modules: __UpperCAmelCase =file.split(""".""" )[0] try: __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: __UpperCAmelCase =doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _a ( self : Optional[Any] ) -> List[str]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""modeling""" __UpperCAmelCase =[ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""tokenization""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] ) -> Optional[Any]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""configuration""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : List[Any] ) -> Tuple: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase =["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase =Path("""docs/source""" ) __UpperCAmelCase =["""favicon.ico"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
68
0
def SCREAMING_SNAKE_CASE__ ( snake_case__ :str ) -> Union[str, Any]: _lowercase = len(snake_case__ ) _lowercase = sum(snake_case__ ) _lowercase = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): _lowercase = True for i in range(1 , s + 1 ): _lowercase = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): _lowercase = dp[i][j - 1] if arr[i - 1] <= j: _lowercase = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: _lowercase = s - 2 * j break return diff
67
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __A = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def lowercase__ ( A_: int , A_: Optional[Any] , A_: List[str]=None ) -> List[str]: """simple docstring""" if rng is None: __UpperCAmelCase =random.Random() __UpperCAmelCase =1 for dim in shape: total_dims *= dim __UpperCAmelCase =[] for _ in range(A_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __UpperCAmelCase =np.array(A_ , dtype=jnp.intaa ).reshape(A_ ) return output def lowercase__ ( A_: List[str] , A_: List[str]=None ) -> Any: """simple docstring""" __UpperCAmelCase =ids_tensor(A_ , vocab_size=2 , rng=A_ ) # make sure that at least one token is attended to for each batch __UpperCAmelCase =1 return attn_mask @require_flax class _A : """simple docstring""" lowerCamelCase : Optional[Any] = None lowerCamelCase : int = () def _a ( self : str ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __UpperCAmelCase =2 __UpperCAmelCase =inputs["""input_ids"""].shape[-1] // 2 __UpperCAmelCase =inputs["""input_ids"""][:max_batch_size, :sequence_length] __UpperCAmelCase =jnp.ones_like(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __UpperCAmelCase =input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __UpperCAmelCase =config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _a ( self : Union[str, Any] ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =0 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model_class.__name__[4:] # Skip the "Flax" at the beginning __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =pt_model_class(__SCREAMING_SNAKE_CASE ).eval() __UpperCAmelCase =load_flax_weights_in_pytorch_model(__SCREAMING_SNAKE_CASE , flax_model.params ) __UpperCAmelCase =flax_model.generate(__SCREAMING_SNAKE_CASE ).sequences __UpperCAmelCase =pt_model.generate(torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __UpperCAmelCase =flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[Any] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _a ( self : Union[str, Any] ) -> List[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length __UpperCAmelCase =0.8 __UpperCAmelCase =10 __UpperCAmelCase =0.3 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[str] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =2 __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : int ) -> Any: __UpperCAmelCase =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) __UpperCAmelCase =FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) __UpperCAmelCase ="""Hello world""" __UpperCAmelCase =tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """do_samples""" ): model.generate(__SCREAMING_SNAKE_CASE , do_samples=__SCREAMING_SNAKE_CASE ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """foo""" ): __UpperCAmelCase ={"""foo""": """bar"""} model.generate(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' import functools from typing import Any def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : list[str] ) -> bool: # Validation if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or len(_UpperCAmelCase ) == 0: raise ValueError("the string should be not empty string" ) if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or not all( isinstance(_UpperCAmelCase , _UpperCAmelCase ) and len(_UpperCAmelCase ) > 0 for item in words ): raise ValueError("the words should be a list of non-empty strings" ) # Build trie __snake_case = {} __snake_case = "WORD_KEEPER" for word in words: __snake_case = trie for c in word: if c not in trie_node: __snake_case = {} __snake_case = trie_node[c] __snake_case = True __snake_case = len(_UpperCAmelCase ) # Dynamic programming method @functools.cache def is_breakable(_UpperCAmelCase : int ) -> bool: if index == len_string: return True __snake_case = trie for i in range(_UpperCAmelCase , _UpperCAmelCase ): __snake_case = trie_node.get(string[i] , _UpperCAmelCase ) if trie_node is None: return False if trie_node.get(_UpperCAmelCase , _UpperCAmelCase ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
69
from __future__ import annotations from collections.abc import Iterator class _A : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : int ) -> None: __UpperCAmelCase =value __UpperCAmelCase =None __UpperCAmelCase =None class _A : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Node ) -> None: __UpperCAmelCase =tree def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : int ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
68
0
def _SCREAMING_SNAKE_CASE ( lowercase : Optional[Any] , lowercase : Union[str, Any] ): '''simple docstring''' lowerCamelCase_ = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _SCREAMING_SNAKE_CASE ( lowercase : List[str] , lowercase : str , lowercase : Dict ): '''simple docstring''' lowerCamelCase_ = 0 while b > 0: if b & 1: lowerCamelCase_ = ((res % c) + (a % c)) % c a += a b >>= 1 return res
70
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def lowercase__ ( A_: Union[str, Any] ) -> List[Any]: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=A_ , AssumeRolePolicyDocument=json.dumps(A_ , indent=2 ) ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=A_ , PolicyName=F'''{role_name}_policy_permission''' , PolicyDocument=json.dumps(A_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F'''role {role_name} already exists. Using existing one''' ) def lowercase__ ( A_: Dict ) -> Any: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) return iam_client.get_role(RoleName=A_ )["Role"]["Arn"] def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase =_ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , A_ , ) __UpperCAmelCase =None if credentials_configuration == 0: __UpperCAmelCase =_ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) __UpperCAmelCase =aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __UpperCAmelCase =_ask_field("""AWS Access Key ID: """ ) __UpperCAmelCase =aws_access_key_id __UpperCAmelCase =_ask_field("""AWS Secret Access Key: """ ) __UpperCAmelCase =aws_secret_access_key __UpperCAmelCase =_ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) __UpperCAmelCase =aws_region __UpperCAmelCase =_ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , A_ , ) if role_management == 0: __UpperCAmelCase =_ask_field("""Enter your IAM role name: """ ) else: __UpperCAmelCase ="""accelerate_sagemaker_execution_role""" print(F'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(A_ ) __UpperCAmelCase =_ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_custom_docker_image: __UpperCAmelCase =_ask_field("""Enter your Docker image: """ , lambda A_ : str(A_ ).lower() ) __UpperCAmelCase =_ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_inputs_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_metrics_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) __UpperCAmelCase ={} __UpperCAmelCase =_ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_dynamo: __UpperCAmelCase ="""dynamo_""" __UpperCAmelCase =_ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __UpperCAmelCase =_ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_custom_options: __UpperCAmelCase =_ask_options( """Which mode do you want to use?""" , A_ , lambda A_ : TORCH_DYNAMO_MODES[int(A_ )] , default="""default""" , ) __UpperCAmelCase =_ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =_ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase ="""Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __UpperCAmelCase =_ask_options( A_ , A_ , lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __UpperCAmelCase =_ask_field(A_ , lambda A_ : str(A_ ).lower() , default="""ml.p3.2xlarge""" ) __UpperCAmelCase =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __UpperCAmelCase =_ask_field( """How many machines do you want use? [1]: """ , A_ , default=1 , ) __UpperCAmelCase =_ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=A_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=A_ , use_cpu=A_ , dynamo_config=A_ , eca_instance_type=A_ , profile=A_ , region=A_ , iam_role_name=A_ , mixed_precision=A_ , num_machines=A_ , sagemaker_inputs_file=A_ , sagemaker_metrics_file=A_ , )
68
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } _lowerCamelCase = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def a__ ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Dict ) -> Union[str, Any]: """simple docstring""" for attribute in key.split("." ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models UpperCAmelCase_ : Any = "lm_head" UpperCAmelCase_ : Tuple = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: UpperCAmelCase_ : Optional[int] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: UpperCAmelCase_ : Dict = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCAmelCase_ : Any = value elif weight_type == "weight_g": UpperCAmelCase_ : Optional[int] = value elif weight_type == "weight_v": UpperCAmelCase_ : Dict = value elif weight_type == "bias": UpperCAmelCase_ : Dict = value else: UpperCAmelCase_ : Tuple = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def a__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[int] ) -> Tuple: """simple docstring""" UpperCAmelCase_ : int = [] UpperCAmelCase_ : List[str] = fairseq_model.state_dict() UpperCAmelCase_ : List[str] = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): UpperCAmelCase_ : Dict = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == "group" , ) UpperCAmelCase_ : int = True else: for key, mapped_key in MAPPING.items(): UpperCAmelCase_ : List[Any] = "unispeech." + 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]: UpperCAmelCase_ : Optional[int] = True if "*" in mapped_key: UpperCAmelCase_ : Tuple = name.split(_SCREAMING_SNAKE_CASE )[0].split("." )[-2] UpperCAmelCase_ : Dict = mapped_key.replace("*" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: UpperCAmelCase_ : int = "weight_g" elif "weight_v" in name: UpperCAmelCase_ : List[str] = "weight_v" elif "bias" in name: UpperCAmelCase_ : List[Any] = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCAmelCase_ : List[Any] = "weight" else: UpperCAmelCase_ : Dict = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F'''Unused weights: {unused_weights}''' ) def a__ ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Any ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : str = full_name.split("conv_layers." )[-1] UpperCAmelCase_ : Optional[int] = name.split("." ) UpperCAmelCase_ : Tuple = int(items[0] ) UpperCAmelCase_ : List[str] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCAmelCase_ : Dict = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCAmelCase_ : str = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) UpperCAmelCase_ : Dict = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCAmelCase_ : Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def a__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : int=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None , _SCREAMING_SNAKE_CASE : Optional[Any]=True ) -> List[Any]: """simple docstring""" if config_path is not None: UpperCAmelCase_ : Optional[int] = UniSpeechConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: UpperCAmelCase_ : Tuple = UniSpeechConfig() if is_finetuned: if dict_path: UpperCAmelCase_ : str = Dictionary.load_from_json(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCAmelCase_ : Optional[int] = target_dict.pad_index UpperCAmelCase_ : List[str] = target_dict.bos_index UpperCAmelCase_ : Optional[Any] = target_dict.eos_index UpperCAmelCase_ : int = len(target_dict.symbols ) UpperCAmelCase_ : int = os.path.join(_SCREAMING_SNAKE_CASE , "vocab.json" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : Optional[Any] = target_dict.indices # fairseq has the <pad> and <s> switched UpperCAmelCase_ : str = 42 UpperCAmelCase_ : str = 43 with open(_SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : Any = WavaVecaPhonemeCTCTokenizer( _SCREAMING_SNAKE_CASE , 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=_SCREAMING_SNAKE_CASE , ) UpperCAmelCase_ : Tuple = True if config.feat_extract_norm == "layer" else False UpperCAmelCase_ : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) UpperCAmelCase_ : List[str] = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : str = UniSpeechForCTC(_SCREAMING_SNAKE_CASE ) else: UpperCAmelCase_ : Any = UniSpeechForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] ), "w2v_path": checkpoint_path} ) else: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) UpperCAmelCase_ : str = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) hf_unispeech.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": _lowerCamelCase = 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""" ) _lowerCamelCase = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
71
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Tuple = 'ctrl' lowerCamelCase : Any = ['past_key_values'] lowerCamelCase : Optional[int] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=246534 , __SCREAMING_SNAKE_CASE : int=256 , __SCREAMING_SNAKE_CASE : Optional[Any]=1280 , __SCREAMING_SNAKE_CASE : Optional[Any]=8192 , __SCREAMING_SNAKE_CASE : int=48 , __SCREAMING_SNAKE_CASE : Union[str, Any]=16 , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : List[Any]=1e-6 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : Union[str, Any]=True , **__SCREAMING_SNAKE_CASE : int , ) -> Any: __UpperCAmelCase =vocab_size __UpperCAmelCase =n_positions __UpperCAmelCase =n_embd __UpperCAmelCase =n_layer __UpperCAmelCase =n_head __UpperCAmelCase =dff __UpperCAmelCase =resid_pdrop __UpperCAmelCase =embd_pdrop __UpperCAmelCase =layer_norm_epsilon __UpperCAmelCase =initializer_range __UpperCAmelCase =use_cache super().__init__(**__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __magic_name__ ( unittest.TestCase ): def __init__( self , snake_case_ , snake_case_=7 , snake_case_=3 , snake_case_=18 , snake_case_=30 , snake_case_=4_00 , snake_case_=True , snake_case_=None , snake_case_=True , snake_case_=None , ): lowercase =size if size is not None else {'''shortest_edge''': 20} lowercase =crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} lowercase =parent lowercase =batch_size lowercase =num_channels lowercase =image_size lowercase =min_resolution lowercase =max_resolution lowercase =do_resize lowercase =size lowercase =do_center_crop lowercase =crop_size def _A( self ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __magic_name__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): UpperCamelCase__ = MobileNetVaImageProcessor if is_vision_available() else None def _A( self ): lowercase =MobileNetVaImageProcessingTester(self ) @property def _A( self ): return self.image_processor_tester.prepare_image_processor_dict() def _A( self ): lowercase =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case_ , '''do_resize''' ) ) self.assertTrue(hasattr(snake_case_ , '''size''' ) ) self.assertTrue(hasattr(snake_case_ , '''do_center_crop''' ) ) self.assertTrue(hasattr(snake_case_ , '''crop_size''' ) ) def _A( self ): lowercase =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) lowercase =self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def _A( self ): pass def _A( self ): # Initialize image_processing lowercase =self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase =prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , Image.Image ) # Test not batched input lowercase =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched lowercase =image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _A( self ): # Initialize image_processing lowercase =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase =prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , numpify=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , np.ndarray ) # Test not batched input lowercase =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched lowercase =image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _A( self ): # Initialize image_processing lowercase =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase =prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , torchify=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , torch.Tensor ) # Test not batched input lowercase =image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched lowercase =image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
72
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = [ ["attention", "attn"], ["encoder_attention", "encoder_attn"], ["q_lin", "q_proj"], ["k_lin", "k_proj"], ["v_lin", "v_proj"], ["out_lin", "out_proj"], ["norm_embeddings", "layernorm_embedding"], ["position_embeddings", "embed_positions"], ["embeddings", "embed_tokens"], ["ffn.lin", "fc"], ] def lowercase__ ( A_: Optional[Any] ) -> Union[str, Any]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __UpperCAmelCase =k.replace(A_ , A_ ) if k.startswith("""encoder""" ): __UpperCAmelCase =k.replace(""".attn""" , """.self_attn""" ) __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """encoder_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm3""" , """final_layer_norm""" ) return k def lowercase__ ( A_: Tuple ) -> str: """simple docstring""" __UpperCAmelCase =[ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: __UpperCAmelCase =sd.pop(A_ ) __UpperCAmelCase =k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd __UpperCAmelCase =v __A = ["START"] @torch.no_grad() def lowercase__ ( A_: List[Any] , A_: str , A_: int ) -> Optional[int]: """simple docstring""" __UpperCAmelCase =torch.load(A_ , map_location="""cpu""" ) __UpperCAmelCase =model["""model"""] __UpperCAmelCase =BlenderbotConfig.from_json_file(A_ ) __UpperCAmelCase =BlenderbotForConditionalGeneration(A_ ) __UpperCAmelCase =m.model.state_dict().keys() __UpperCAmelCase =[] __UpperCAmelCase ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue __UpperCAmelCase =rename_state_dict_key(A_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __UpperCAmelCase =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(A_ ) m.model.load_state_dict(A_ , strict=A_ ) m.half() m.save_pretrained(A_ ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin") parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.") parser.add_argument( "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use" ) __A = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
68
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a_ : Any = { 'configuration_owlvit': [ 'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OwlViTConfig', 'OwlViTOnnxConfig', 'OwlViTTextConfig', 'OwlViTVisionConfig', ], 'processing_owlvit': ['OwlViTProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['OwlViTFeatureExtractor'] a_ : List[str] = ['OwlViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = [ 'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OwlViTModel', 'OwlViTPreTrainedModel', 'OwlViTTextModel', 'OwlViTVisionModel', 'OwlViTForObjectDetection', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys a_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
from itertools import permutations def lowercase__ ( A_: tuple ) -> bool: """simple docstring""" 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 =[7, 11, 13, 17] for i, test in enumerate(A_ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def lowercase__ ( A_: int = 10 ) -> int: """simple docstring""" return sum( int("""""".join(map(A_ , A_ ) ) ) for num in permutations(range(A_ ) ) if is_substring_divisible(A_ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
68
0
from __future__ import annotations import math lowercase_ = """2020.9.26""" lowercase_ = """xcodz-dot, cclaus, dhruvmanila""" def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case ): """simple docstring""" if not all(isinstance(snake_case , (float, int) ) for val in locals().values() ): __SCREAMING_SNAKE_CASE : Optional[int] = F'''Input values must either be float or int: {list(locals().values() )}''' raise TypeError(snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ((x * distance) / (z + distance)) * scale __SCREAMING_SNAKE_CASE : int = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case ): """simple docstring""" if not isinstance(snake_case , snake_case ): raise TypeError('''Axis must be a str''' ) __SCREAMING_SNAKE_CASE : List[str] = locals() del input_variables["axis"] if not all(isinstance(snake_case , (float, int) ) for val in input_variables.values() ): __SCREAMING_SNAKE_CASE : List[Any] = ( '''Input values except axis must either be float or int: ''' F'''{list(input_variables.values() )}''' ) raise TypeError(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = (angle % 360) / 450 * 180 / math.pi if axis == "z": __SCREAMING_SNAKE_CASE : Tuple = x * math.cos(snake_case ) - y * math.sin(snake_case ) __SCREAMING_SNAKE_CASE : List[Any] = y * math.cos(snake_case ) + x * math.sin(snake_case ) __SCREAMING_SNAKE_CASE : Optional[int] = z elif axis == "x": __SCREAMING_SNAKE_CASE : List[str] = y * math.cos(snake_case ) - z * math.sin(snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = z * math.cos(snake_case ) + y * math.sin(snake_case ) __SCREAMING_SNAKE_CASE : Tuple = x elif axis == "y": __SCREAMING_SNAKE_CASE : List[str] = x * math.cos(snake_case ) - z * math.sin(snake_case ) __SCREAMING_SNAKE_CASE : Optional[Any] = z * math.cos(snake_case ) + x * math.sin(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = y else: raise ValueError('''not a valid axis, choose one of \'x\', \'y\', \'z\'''' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(f'''{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }''') print(f'''{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }''')
74
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __A = TypeVar("T") def lowercase__ ( A_: int ) -> int: """simple docstring""" return (position - 1) // 2 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 1 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 2 class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[str] ) -> None: __UpperCAmelCase =[] __UpperCAmelCase ={} __UpperCAmelCase =0 def __len__( self : str ) -> int: return self.elements def __repr__( self : Dict ) -> str: return str(self.heap ) def _a ( self : Optional[int] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __UpperCAmelCase =self.elements self.elements += 1 self._bubble_up(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __UpperCAmelCase , __UpperCAmelCase =self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __UpperCAmelCase , __UpperCAmelCase =self.heap[0] self._bubble_down(__SCREAMING_SNAKE_CASE ) return elem def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Update the weight of the given key __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase =(elem, weight) if position > 0: __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._bubble_up(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __UpperCAmelCase =self.position_map[elem] if curr_pos == 0: return None __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_up(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase =get_child_left_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =get_child_right_position(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements and child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) else: return None if child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ) -> None: # Swap the nodes at the given positions __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase , __UpperCAmelCase =( self.heap[nodea_pos], self.heap[nodea_pos], ) __UpperCAmelCase =nodea_pos __UpperCAmelCase =nodea_pos class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[Any] ) -> None: __UpperCAmelCase ={} __UpperCAmelCase =0 def __repr__( self : Tuple ) -> str: return str(self.connections ) def __len__( self : str ) -> int: return self.nodes def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __UpperCAmelCase ={} self.nodes += 1 def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(__SCREAMING_SNAKE_CASE ) self.add_node(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =weight __UpperCAmelCase =weight def lowercase__ ( A_: GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: """simple docstring""" __UpperCAmelCase ={node: maxsize for node in graph.connections} __UpperCAmelCase ={node: None for node in graph.connections} __UpperCAmelCase =MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(A_ , A_ ) if priority_queue.is_empty(): return dist, parent # initialization __UpperCAmelCase =priority_queue.extract_min() __UpperCAmelCase =0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node # running prim's algorithm while not priority_queue.is_empty(): __UpperCAmelCase =priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node return dist, parent
68
0
'''simple docstring''' 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 UpperCamelCase__ = get_tests_dir('''fixtures/test_sentencepiece.model''') UpperCamelCase__ = get_tests_dir('''fixtures/test_sentencepiece_bpe.model''') UpperCamelCase__ = '''pt''' if is_torch_available() else '''tf''' @require_sentencepiece @require_tokenizers class lowerCamelCase_ ( __a , unittest.TestCase ): lowerCAmelCase__ = CamembertTokenizer lowerCAmelCase__ = CamembertTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True def lowercase_ ( self : str ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase__ : Optional[int] = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase_ ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = '''<pad>''' UpperCAmelCase__ : Tuple = 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 : Tuple ): '''simple docstring''' UpperCAmelCase__ : Optional[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 ) , 1_004 ) def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_005 ) def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : Dict = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) UpperCAmelCase__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) UpperCAmelCase__ : Any = '''I was born in 92000, and this is falsé.''' UpperCAmelCase__ : Any = tokenizer.encode(_A ) UpperCAmelCase__ : Tuple = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) UpperCAmelCase__ : Dict = tokenizer.encode(_A , add_special_tokens=_A ) UpperCAmelCase__ : Optional[Any] = 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) UpperCAmelCase__ : Tuple = tokenizer.convert_ids_to_tokens(_A ) UpperCAmelCase__ : int = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def lowercase_ ( self : Optional[Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return UpperCAmelCase__ : str = self.get_tokenizer() UpperCAmelCase__ : Tuple = self.get_rust_tokenizer() UpperCAmelCase__ : List[Any] = '''I was born in 92000, and this is falsé.''' UpperCAmelCase__ : List[str] = tokenizer.tokenize(_A ) UpperCAmelCase__ : Any = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) UpperCAmelCase__ : Any = tokenizer.encode(_A , add_special_tokens=_A ) UpperCAmelCase__ : Optional[int] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) UpperCAmelCase__ : str = self.get_rust_tokenizer() UpperCAmelCase__ : Optional[int] = tokenizer.encode(_A ) UpperCAmelCase__ : Optional[Any] = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def lowercase_ ( self : Any ): '''simple docstring''' UpperCAmelCase__ : int = {'''input_ids''': [[5, 54, 7_196, 297, 30, 23, 776, 18, 11, 3_215, 3_705, 8_252, 22, 3_164, 1_181, 2_116, 29, 16, 813, 25, 791, 3_314, 20, 3_446, 38, 27_575, 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, 9_088, 20, 1_517, 8, 22_804, 18_818, 10, 38, 629, 607, 607, 142, 19, 7_196, 867, 56, 10_326, 24, 2_267, 20, 416, 5_072, 15_612, 233, 734, 7, 2_399, 27, 16, 3_015, 1_649, 7, 24, 20, 4_338, 2_399, 27, 13, 3_400, 14, 13, 6_189, 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. UpperCAmelCase__ : Tuple = [ '''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 , )
75
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 __A = logging.get_logger(__name__) @dataclass class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[int] = [ 'no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process', ] def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __UpperCAmelCase =deprecated_arg[3:] __UpperCAmelCase =not kwargs.pop(__SCREAMING_SNAKE_CASE ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) __UpperCAmelCase =kwargs.pop("""tpu_name""" , self.tpu_name ) __UpperCAmelCase =kwargs.pop("""device_idx""" , self.device_idx ) __UpperCAmelCase =kwargs.pop("""eager_mode""" , self.eager_mode ) __UpperCAmelCase =kwargs.pop("""use_xla""" , self.use_xla ) super().__init__(**__SCREAMING_SNAKE_CASE ) lowerCamelCase : str = field( default=UpperCamelCase , metadata={'help': 'Name of TPU'} , ) lowerCamelCase : int = field( default=0 , metadata={'help': 'CPU / GPU device index. Defaults to 0.'} , ) lowerCamelCase : bool = field(default=UpperCamelCase , metadata={'help': 'Benchmark models in eager model.'} ) lowerCamelCase : 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 _a ( self : List[str] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) __UpperCAmelCase =None if self.tpu: try: if self.tpu_name: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __UpperCAmelCase =None return tpu @cached_property def _a ( self : Tuple ) -> 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 ) __UpperCAmelCase =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""" ) __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , """GPU""" ) # disable GPU __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/cpu:{self.device_idx}''' ) return strategy @property def _a ( self : Optional[Any] ) -> bool: requires_backends(self , ["""tf"""] ) return self._setup_tpu is not None @property def _a ( self : str ) -> "tf.distribute.Strategy": requires_backends(self , ["""tf"""] ) return self._setup_strategy @property def _a ( self : Dict ) -> Optional[int]: requires_backends(self , ["""tf"""] ) return tf.config.list_physical_devices("""GPU""" ) @property def _a ( self : List[str] ) -> int: requires_backends(self , ["""tf"""] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _a ( self : List[str] ) -> bool: return self.n_gpu > 0
68
0
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False" ) ) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env" ) @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_50, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "pytorch", "script": "run_ddp.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "tensorflow", "script": "run_tf_dist.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.6, "eval_loss": 0.7}, }, ] ) class UpperCAmelCase_ ( unittest.TestCase ): def _lowerCamelCase ( self ) -> Optional[Any]: if self.framework == "pytorch": subprocess.run( F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='''utf-8''' , check=UpperCamelCase_ , ) assert hasattr(self , '''env''' ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> Union[str, Any]: __lowercase : str = F"""{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}""" # distributed data settings __lowercase : List[str] = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=UpperCamelCase_ , instance_count=UpperCamelCase_ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase_ , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=UpperCamelCase_ , py_version='''py36''' , ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[Any]: TrainingJobAnalytics(UpperCamelCase_ ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> Any: # create estimator __lowercase : List[str] = self.create_estimator(UpperCamelCase_ ) # run training estimator.fit() # result dataframe __lowercase : Dict = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowercase : int = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowercase : Optional[Any] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowercase : int = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"""{estimator.latest_training_job.name}.json""" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , UpperCamelCase_ )
76
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 _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Dict: torch.manual_seed(0 ) __UpperCAmelCase =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 _a ( self : int ) -> Union[str, Any]: __UpperCAmelCase =self.dummy_uncond_unet __UpperCAmelCase =ScoreSdeVeScheduler() __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE )[ 0 ] __UpperCAmelCase =image[0, -3:, -3:, -1] __UpperCAmelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCAmelCase =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 _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Optional[int] ) -> int: __UpperCAmelCase ="""google/ncsnpp-church-256""" __UpperCAmelCase =UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVeScheduler.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=10 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCAmelCase =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
68
0
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging A = logging.get_logger(__name__) A = { """Salesforce/codegen-350M-nl""": """https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json""", """Salesforce/codegen-350M-multi""": """https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json""", """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json""", """Salesforce/codegen-2B-nl""": """https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json""", """Salesforce/codegen-2B-multi""": """https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json""", """Salesforce/codegen-2B-mono""": """https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json""", """Salesforce/codegen-6B-nl""": """https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json""", """Salesforce/codegen-6B-multi""": """https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json""", """Salesforce/codegen-6B-mono""": """https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json""", """Salesforce/codegen-16B-nl""": """https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json""", """Salesforce/codegen-16B-multi""": """https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json""", """Salesforce/codegen-16B-mono""": """https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json""", } class a__ ( __magic_name__ ): lowercase_ = "codegen" lowercase_ = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Optional[int] , UpperCamelCase_ : Optional[int]=50400 , UpperCamelCase_ : Tuple=2048 , UpperCamelCase_ : Optional[int]=2048 , UpperCamelCase_ : Optional[int]=4096 , UpperCamelCase_ : Optional[Any]=28 , UpperCamelCase_ : Union[str, Any]=16 , UpperCamelCase_ : List[Any]=64 , UpperCamelCase_ : Dict=None , UpperCamelCase_ : int="gelu_new" , UpperCamelCase_ : Any=0.0 , UpperCamelCase_ : str=0.0 , UpperCamelCase_ : Any=0.0 , UpperCamelCase_ : List[str]=1e-5 , UpperCamelCase_ : Union[str, Any]=0.02 , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : List[str]=50256 , UpperCamelCase_ : int=50256 , UpperCamelCase_ : Optional[Any]=False , **UpperCamelCase_ : List[str] , ): """simple docstring""" __UpperCAmelCase : Tuple = vocab_size __UpperCAmelCase : Union[str, Any] = n_ctx __UpperCAmelCase : List[str] = n_positions __UpperCAmelCase : Dict = n_embd __UpperCAmelCase : List[Any] = n_layer __UpperCAmelCase : List[Any] = n_head __UpperCAmelCase : int = n_inner __UpperCAmelCase : Optional[int] = rotary_dim __UpperCAmelCase : Union[str, Any] = activation_function __UpperCAmelCase : Optional[Any] = resid_pdrop __UpperCAmelCase : Tuple = embd_pdrop __UpperCAmelCase : List[Any] = attn_pdrop __UpperCAmelCase : Union[str, Any] = layer_norm_epsilon __UpperCAmelCase : Tuple = initializer_range __UpperCAmelCase : Optional[Any] = use_cache __UpperCAmelCase : Union[str, Any] = bos_token_id __UpperCAmelCase : Optional[Any] = eos_token_id super().__init__( bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , tie_word_embeddings=UpperCamelCase_ , **UpperCamelCase_) class a__ ( __magic_name__ ): def __init__( self : List[str] , UpperCamelCase_ : PretrainedConfig , UpperCamelCase_ : str = "default" , UpperCamelCase_ : List[PatchingSpec] = None , UpperCamelCase_ : bool = False , ): """simple docstring""" super().__init__(UpperCamelCase_ , task=UpperCamelCase_ , patching_specs=UpperCamelCase_ , use_past=UpperCamelCase_) if not getattr(self._config , "pad_token_id" , UpperCamelCase_): # TODO: how to do that better? __UpperCAmelCase : Optional[Any] = 0 @property def a_ ( self : Optional[int]): """simple docstring""" __UpperCAmelCase : Dict = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}) if self.use_past: self.fill_with_past_key_values_(UpperCamelCase_ , direction="inputs") __UpperCAmelCase : Dict = {0: "batch", 1: "past_sequence + sequence"} else: __UpperCAmelCase : int = {0: "batch", 1: "sequence"} return common_inputs @property def a_ ( self : Optional[Any]): """simple docstring""" return self._config.n_layer @property def a_ ( self : Optional[int]): """simple docstring""" return self._config.n_head def a_ ( self : Optional[int] , UpperCamelCase_ : PreTrainedTokenizer , UpperCamelCase_ : int = -1 , UpperCamelCase_ : int = -1 , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[TensorType] = None , ): """simple docstring""" __UpperCAmelCase : str = super(UpperCamelCase_ , self).generate_dummy_inputs( UpperCamelCase_ , batch_size=UpperCamelCase_ , seq_length=UpperCamelCase_ , is_pair=UpperCamelCase_ , framework=UpperCamelCase_) # We need to order the input in the way they appears in the forward() __UpperCAmelCase : str = OrderedDict({"input_ids": common_inputs["input_ids"]}) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.") else: import torch __UpperCAmelCase , __UpperCAmelCase : Dict = common_inputs["input_ids"].shape # Not using the same length for past_key_values __UpperCAmelCase : List[Any] = seqlen + 2 __UpperCAmelCase : List[Any] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __UpperCAmelCase : Any = [ (torch.zeros(UpperCamelCase_), torch.zeros(UpperCamelCase_)) for _ in range(self.num_layers) ] __UpperCAmelCase : Dict = common_inputs["attention_mask"] if self.use_past: __UpperCAmelCase : Any = ordered_inputs["attention_mask"].dtype __UpperCAmelCase : Any = torch.cat( [ordered_inputs["attention_mask"], torch.ones(UpperCamelCase_ , UpperCamelCase_ , dtype=UpperCamelCase_)] , dim=1) return ordered_inputs @property def a_ ( self : Union[str, Any]): """simple docstring""" return 13
77
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __A = logging.get_logger(__name__) __A = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class _A ( UpperCamelCase ): """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : str=None , *__SCREAMING_SNAKE_CASE : Union[str, Any] , **__SCREAMING_SNAKE_CASE : List[Any] ) -> Any: super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if config is None: assert isinstance(self.model , __SCREAMING_SNAKE_CASE ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f''' {self.model.__class__}''' ) __UpperCAmelCase =self.model.config else: __UpperCAmelCase =config __UpperCAmelCase =data_args __UpperCAmelCase =self.config.tgt_vocab_size if isinstance(self.config , __SCREAMING_SNAKE_CASE ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' """ padding..""" ) if self.args.label_smoothing == 0: __UpperCAmelCase =torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __UpperCAmelCase =label_smoothed_nll_loss def _a ( self : Any , __SCREAMING_SNAKE_CASE : int ) -> Any: if self.optimizer is None: __UpperCAmelCase =["""bias""", """LayerNorm.weight"""] __UpperCAmelCase =[ { """params""": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], """weight_decay""": self.args.weight_decay, }, { """params""": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], """weight_decay""": 0.0, }, ] __UpperCAmelCase =Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __UpperCAmelCase =Adafactor __UpperCAmelCase ={"""scale_parameter""": False, """relative_step""": False} else: __UpperCAmelCase =AdamW __UpperCAmelCase ={ """betas""": (self.args.adam_betaa, self.args.adam_betaa), """eps""": self.args.adam_epsilon, } __UpperCAmelCase =self.args.learning_rate if self.sharded_ddp: __UpperCAmelCase =OSS( params=__SCREAMING_SNAKE_CASE , optim=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: __UpperCAmelCase =optimizer_cls(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if self.lr_scheduler is None: __UpperCAmelCase =self._get_lr_scheduler(__SCREAMING_SNAKE_CASE ) else: # ignoring --lr_scheduler logger.warning("""scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.""" ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Any: __UpperCAmelCase =arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __UpperCAmelCase =schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __UpperCAmelCase =schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __UpperCAmelCase =schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=__SCREAMING_SNAKE_CASE ) return scheduler def _a ( self : Optional[Any] ) -> Optional[torch.utils.data.Sampler]: if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Tuple: if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __UpperCAmelCase , __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[:2] else: # compute label smoothed loss __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =torch.nn.functional.log_softmax(__SCREAMING_SNAKE_CASE , dim=-1 ) __UpperCAmelCase , __UpperCAmelCase =self.loss_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: __UpperCAmelCase =inputs.pop("""labels""" ) __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return loss def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : nn.Module , __SCREAMING_SNAKE_CASE : Dict[str, Union[torch.Tensor, Any]] , __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : Optional[List[str]] = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: __UpperCAmelCase =self._prepare_inputs(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """max_length""": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, """num_beams""": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __UpperCAmelCase =self.model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , **__SCREAMING_SNAKE_CASE , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) __UpperCAmelCase =inputs.pop("""labels""" ) with torch.no_grad(): # compute loss on predict data __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __UpperCAmelCase =generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) return (loss, logits, labels) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: # If PAD token is not defined at least EOS token has to be defined __UpperCAmelCase =self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( """Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be""" f''' padded to `max_length`={max_length}''' ) __UpperCAmelCase =pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __UpperCAmelCase =tensor return padded_tensor
68
0
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE_: Union[str, Any] =get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right SCREAMING_SNAKE_CASE_: Any =25_00_04 SCREAMING_SNAKE_CASE_: int =25_00_20 @require_sentencepiece @require_tokenizers class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : Tuple = MBartaaTokenizer a__ : str = MBartaaTokenizerFast a__ : Union[str, Any] = True a__ : Dict = True def _lowercase (self : int ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase_ = MBartaaTokenizer(__a , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase (self : Tuple ): UpperCAmelCase_ = "<s>" UpperCAmelCase_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(__a ) , 1054 ) def _lowercase (self : Optional[int] ): self.assertEqual(self.get_tokenizer().vocab_size , 1054 ) def _lowercase (self : int ): UpperCAmelCase_ = MBartaaTokenizer(__a , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__a ) UpperCAmelCase_ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCAmelCase_ = 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", "é", "."] , ) UpperCAmelCase_ = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCAmelCase_ = 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>", "."] , ) @slow def _lowercase (self : Tuple ): # fmt: off UpperCAmelCase_ = {"input_ids": [[250004, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 5428, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 12399, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 122009, 115774, 23, 805, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [250004, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [250004, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="facebook/mbart-large-50" , revision="d3913889c59cd5c9e456b269c376325eabad57e2" , ) def _lowercase (self : List[str] ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return UpperCAmelCase_ = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart50", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCAmelCase_ = self.rust_tokenizer_class.from_pretrained(__a , **__a ) UpperCAmelCase_ = self.tokenizer_class.from_pretrained(__a , **__a ) UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = tokenizer_r.save_pretrained(__a ) UpperCAmelCase_ = tokenizer_p.save_pretrained(__a ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) UpperCAmelCase_ = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(__a , __a ) # Checks everything loads correctly in the same way UpperCAmelCase_ = tokenizer_r.from_pretrained(__a ) UpperCAmelCase_ = tokenizer_p.from_pretrained(__a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__a , __a ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__a ) # Save tokenizer rust, legacy_format=True UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = tokenizer_r.save_pretrained(__a , legacy_format=__a ) UpperCAmelCase_ = tokenizer_p.save_pretrained(__a ) # Checks it save with the same files self.assertSequenceEqual(__a , __a ) # Checks everything loads correctly in the same way UpperCAmelCase_ = tokenizer_r.from_pretrained(__a ) UpperCAmelCase_ = tokenizer_p.from_pretrained(__a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__a , __a ) ) shutil.rmtree(__a ) # Save tokenizer rust, legacy_format=False UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = tokenizer_r.save_pretrained(__a , legacy_format=__a ) UpperCAmelCase_ = tokenizer_p.save_pretrained(__a ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCAmelCase_ = tokenizer_r.from_pretrained(__a ) UpperCAmelCase_ = tokenizer_p.from_pretrained(__a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__a , __a ) ) shutil.rmtree(__a ) @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): a__ : Optional[Any] = """facebook/mbart-large-50-one-to-many-mmt""" a__ : List[Any] = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] a__ : Optional[int] = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei""" """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor""" """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] a__ : Tuple = [EN_CODE, 8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2] @classmethod def _lowercase (cls : str ): UpperCAmelCase_ = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) UpperCAmelCase_ = 1 return cls def _lowercase (self : List[Any] ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 250020 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["mr_IN"] , 250038 ) def _lowercase (self : Any ): UpperCAmelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __a ) def _lowercase (self : List[Any] ): self.assertIn(__a , self.tokenizer.all_special_ids ) UpperCAmelCase_ = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] UpperCAmelCase_ = self.tokenizer.decode(__a , skip_special_tokens=__a ) UpperCAmelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__a ) self.assertEqual(__a , __a ) self.assertNotIn(self.tokenizer.eos_token , __a ) def _lowercase (self : Any ): UpperCAmelCase_ = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , __a ) UpperCAmelCase_ = 10 UpperCAmelCase_ = self.tokenizer(__a , max_length=__a , truncation=__a ).input_ids[0] self.assertEqual(ids[0] , __a ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__a ) , __a ) def _lowercase (self : Optional[Any] ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [250053, 250001] ) def _lowercase (self : List[str] ): UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__a ) UpperCAmelCase_ = MBartaaTokenizer.from_pretrained(__a ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __a ) @require_torch def _lowercase (self : Dict ): UpperCAmelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__a , return_tensors="pt" ) UpperCAmelCase_ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def _lowercase (self : int ): UpperCAmelCase_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__a , truncation=__a , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) UpperCAmelCase_ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(__a , __a ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) UpperCAmelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __a ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.tokenizer(self.src_text , padding=__a , truncation=__a , max_length=3 , return_tensors="pt" ) UpperCAmelCase_ = self.tokenizer( text_target=self.tgt_text , padding=__a , truncation=__a , max_length=10 , return_tensors="pt" ) UpperCAmelCase_ = targets["input_ids"] UpperCAmelCase_ = shift_tokens_right(__a , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _lowercase (self : Dict ): UpperCAmelCase_ = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(__a ) , { # en_XX, A, test, EOS "input_ids": [[250004, 62, 3034, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 250001, } , )
78
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : List[Any] = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str=0 ) -> Any: __UpperCAmelCase =floats_tensor((1, 3, 128, 128) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =np.random.RandomState(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """strength""": 0.75, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _a ( self : Optional[Any] ) -> int: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Union[str, Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Optional[Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # warmup pass to apply optimizations __UpperCAmelCase =pipe(**self.get_dummy_inputs() ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Optional[int]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _a ( self : Dict ) -> int: __UpperCAmelCase =ort.SessionOptions() __UpperCAmelCase =False return options def _a ( self : Dict ) -> Any: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) # using the PNDM scheduler by default __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _a ( self : List[str] ) -> str: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) __UpperCAmelCase =LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
68
0
import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase="shi-labs/oneformer_demo" ) -> str: '''simple docstring''' with open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) as f: UpperCAmelCase__ : int = json.load(__lowerCamelCase ) UpperCAmelCase__ : Dict = {} UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : int = [] for key, info in class_info.items(): UpperCAmelCase__ : int = info["""name"""] class_names.append(info["""name"""] ) if info["isthing"]: thing_ids.append(int(__lowerCamelCase ) ) UpperCAmelCase__ : List[str] = thing_ids UpperCAmelCase__ : Any = class_names return metadata class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase=7 , _lowerCAmelCase=3 , _lowerCAmelCase=30 , _lowerCAmelCase=400 , _lowerCAmelCase=None , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=[0.5, 0.5, 0.5] , _lowerCAmelCase=[0.5, 0.5, 0.5] , _lowerCAmelCase=10 , _lowerCAmelCase=False , _lowerCAmelCase=255 , _lowerCAmelCase="shi-labs/oneformer_demo" , _lowerCAmelCase="ade20k_panoptic.json" , _lowerCAmelCase=10 , ): UpperCAmelCase__ : Any = parent UpperCAmelCase__ : Tuple = batch_size UpperCAmelCase__ : List[Any] = num_channels UpperCAmelCase__ : str = min_resolution UpperCAmelCase__ : Dict = max_resolution UpperCAmelCase__ : List[str] = do_resize UpperCAmelCase__ : Union[str, Any] = {"""shortest_edge""": 32, """longest_edge""": 1333} if size is None else size UpperCAmelCase__ : str = do_normalize UpperCAmelCase__ : Optional[Any] = image_mean UpperCAmelCase__ : Any = image_std UpperCAmelCase__ : str = class_info_file UpperCAmelCase__ : Tuple = prepare_metadata(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : Dict = num_text UpperCAmelCase__ : Dict = repo_path # for the post_process_functions UpperCAmelCase__ : Union[str, Any] = 2 UpperCAmelCase__ : int = 10 UpperCAmelCase__ : int = 10 UpperCAmelCase__ : int = 3 UpperCAmelCase__ : int = 4 UpperCAmelCase__ : Any = num_labels UpperCAmelCase__ : List[Any] = do_reduce_labels UpperCAmelCase__ : int = ignore_index def __UpperCAmelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=False ): if not batched: UpperCAmelCase__ : Any = image_inputs[0] if isinstance(_lowerCAmelCase , Image.Image ): UpperCAmelCase__ , UpperCAmelCase__ : Tuple = image.size else: UpperCAmelCase__ , UpperCAmelCase__ : Any = image.shape[1], image.shape[2] if w < h: UpperCAmelCase__ : Dict = int(self.size["""shortest_edge"""] * h / w ) UpperCAmelCase__ : Tuple = self.size["""shortest_edge"""] elif w > h: UpperCAmelCase__ : Dict = self.size["""shortest_edge"""] UpperCAmelCase__ : Optional[int] = int(self.size["""shortest_edge"""] * w / h ) else: UpperCAmelCase__ : List[str] = self.size["""shortest_edge"""] UpperCAmelCase__ : Optional[Any] = self.size["""shortest_edge"""] else: UpperCAmelCase__ : int = [] for image in image_inputs: UpperCAmelCase__ , UpperCAmelCase__ : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCAmelCase__ : Optional[Any] = max(_lowerCAmelCase , key=lambda _lowerCAmelCase : item[0] )[0] UpperCAmelCase__ : Dict = max(_lowerCAmelCase , key=lambda _lowerCAmelCase : item[1] )[1] return expected_height, expected_width def __UpperCAmelCase ( self ): return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string __lowerCamelCase = image_processing_class def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = OneFormerImageProcessorTester(self ) @property def __UpperCAmelCase ( self ): return self.image_processing_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase , """image_mean""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """image_std""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_normalize""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """size""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """ignore_index""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """class_info_file""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """num_text""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """repo_path""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """metadata""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_reduce_labels""" ) ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): # Initialize image_processor UpperCAmelCase__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase__ : Optional[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , Image.Image ) # Test not batched input UpperCAmelCase__ : Optional[int] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.image_processing_tester.get_expected_values(_lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.image_processing_tester.get_expected_values(_lowerCAmelCase , batched=_lowerCAmelCase ) UpperCAmelCase__ : str = image_processor( _lowerCAmelCase , ["""semantic"""] * len(_lowerCAmelCase ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self ): # Initialize image_processor UpperCAmelCase__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase__ : Union[str, Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowerCAmelCase , numpify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , np.ndarray ) # Test not batched input UpperCAmelCase__ : Optional[Any] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : List[str] = self.image_processing_tester.get_expected_values(_lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = self.image_processing_tester.get_expected_values(_lowerCAmelCase , batched=_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = image_processor( _lowerCAmelCase , ["""semantic"""] * len(_lowerCAmelCase ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self ): # Initialize image_processor UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase__ : Union[str, Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowerCAmelCase , torchify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , torch.Tensor ) # Test not batched input UpperCAmelCase__ : Optional[Any] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.image_processing_tester.get_expected_values(_lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ , UpperCAmelCase__ : List[str] = self.image_processing_tester.get_expected_values(_lowerCAmelCase , batched=_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = image_processor( _lowerCAmelCase , ["""semantic"""] * len(_lowerCAmelCase ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase="np" ): UpperCAmelCase__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # prepare image and target UpperCAmelCase__ : Union[str, Any] = self.image_processing_tester.num_labels UpperCAmelCase__ : Tuple = None UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : Optional[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowerCAmelCase ) if with_segmentation_maps: UpperCAmelCase__ : int = num_labels if is_instance_map: UpperCAmelCase__ : Optional[int] = list(range(_lowerCAmelCase ) ) * 2 UpperCAmelCase__ : Dict = dict(enumerate(_lowerCAmelCase ) ) UpperCAmelCase__ : int = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": UpperCAmelCase__ : List[str] = [Image.fromarray(_lowerCAmelCase ) for annotation in annotations] UpperCAmelCase__ : List[Any] = image_processor( _lowerCAmelCase , ["""semantic"""] * len(_lowerCAmelCase ) , _lowerCAmelCase , return_tensors="""pt""" , instance_id_to_semantic_id=_lowerCAmelCase , pad_and_return_pixel_mask=_lowerCAmelCase , ) return inputs def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): def common(_lowerCAmelCase=False , _lowerCAmelCase=None ): UpperCAmelCase__ : List[str] = self.comm_get_image_processor_inputs( with_segmentation_maps=_lowerCAmelCase , is_instance_map=_lowerCAmelCase , segmentation_type=_lowerCAmelCase ) UpperCAmelCase__ : Any = inputs["""mask_labels"""] UpperCAmelCase__ : Optional[Any] = inputs["""class_labels"""] UpperCAmelCase__ : Any = inputs["""pixel_values"""] UpperCAmelCase__ : Any = inputs["""text_inputs"""] # check the batch_size for mask_label, class_label, text_input in zip(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(_lowerCAmelCase ) , self.image_processing_tester.num_text ) common() common(is_instance_map=_lowerCAmelCase ) common(is_instance_map=_lowerCAmelCase , segmentation_type="""pil""" ) common(is_instance_map=_lowerCAmelCase , segmentation_type="""pil""" ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = np.zeros((20, 50) ) UpperCAmelCase__ : List[Any] = 1 UpperCAmelCase__ : List[Any] = 1 UpperCAmelCase__ : int = 1 UpperCAmelCase__ : str = binary_mask_to_rle(_lowerCAmelCase ) self.assertEqual(len(_lowerCAmelCase ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCAmelCase__ : Tuple = self.image_processing_tester.get_fake_oneformer_outputs() UpperCAmelCase__ : str = fature_extractor.post_process_semantic_segmentation(_lowerCAmelCase ) self.assertEqual(len(_lowerCAmelCase ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) UpperCAmelCase__ : Tuple = [(1, 4) for i in range(self.image_processing_tester.batch_size )] UpperCAmelCase__ : Union[str, Any] = fature_extractor.post_process_semantic_segmentation(_lowerCAmelCase , target_sizes=_lowerCAmelCase ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCAmelCase__ : str = self.image_processing_tester.get_fake_oneformer_outputs() UpperCAmelCase__ : Optional[int] = image_processor.post_process_instance_segmentation(_lowerCAmelCase , threshold=0 ) self.assertTrue(len(_lowerCAmelCase ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , _lowerCAmelCase ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCAmelCase__ : List[Any] = self.image_processing_tester.get_fake_oneformer_outputs() UpperCAmelCase__ : List[Any] = image_processor.post_process_panoptic_segmentation(_lowerCAmelCase , threshold=0 ) self.assertTrue(len(_lowerCAmelCase ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , _lowerCAmelCase ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
79
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors __A = logging.getLogger(__name__) class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[Any] = 'sequence-classification' def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Tuple ) -> Optional[Any]: if type(__SCREAMING_SNAKE_CASE ) == dict: __UpperCAmelCase =Namespace(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =glue_output_modes[hparams.task] __UpperCAmelCase =glue_tasks_num_labels[hparams.task] super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.mode ) def _a ( self : str , **__SCREAMING_SNAKE_CASE : Dict ) -> List[str]: return self.model(**__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ) -> List[Any]: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =outputs[0] __UpperCAmelCase =self.trainer.lr_schedulers[0]["""scheduler"""] __UpperCAmelCase ={"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def _a ( self : Tuple ) -> List[Any]: __UpperCAmelCase =self.hparams __UpperCAmelCase =processors[args.task]() __UpperCAmelCase =processor.get_labels() for mode in ["train", "dev"]: __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) if os.path.exists(__SCREAMING_SNAKE_CASE ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) __UpperCAmelCase =( processor.get_dev_examples(args.data_dir ) if mode == """dev""" else processor.get_train_examples(args.data_dir ) ) __UpperCAmelCase =convert_examples_to_features( __SCREAMING_SNAKE_CASE , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("""Saving features into cached file %s""" , __SCREAMING_SNAKE_CASE ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ) -> DataLoader: __UpperCAmelCase ="""dev""" if mode == """test""" else mode __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.load(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , batch_size=__SCREAMING_SNAKE_CASE , shuffle=__SCREAMING_SNAKE_CASE , ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ) -> str: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =outputs[:2] __UpperCAmelCase =logits.detach().cpu().numpy() __UpperCAmelCase =inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Any ) -> tuple: __UpperCAmelCase =torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item() __UpperCAmelCase =np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =np.argmax(__SCREAMING_SNAKE_CASE , axis=1 ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =np.squeeze(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =np.concatenate([x["""target"""] for x in outputs] , axis=0 ) __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase ={**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} __UpperCAmelCase =dict(results.items() ) __UpperCAmelCase =results return ret, preds_list, out_label_list def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : list ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _a ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[Any]: BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) parser.add_argument( """--max_seq_length""" , default=128 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--task""" , default="""""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The GLUE task to run""" , ) parser.add_argument( """--gpus""" , default=0 , type=__SCREAMING_SNAKE_CASE , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser def lowercase__ ( ) -> str: """simple docstring""" __UpperCAmelCase =argparse.ArgumentParser() add_generic_args(A_ , os.getcwd() ) __UpperCAmelCase =GLUETransformer.add_model_specific_args(A_ , os.getcwd() ) __UpperCAmelCase =parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __UpperCAmelCase =os.path.join( """./results""" , F'''{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}''' , ) os.makedirs(args.output_dir ) __UpperCAmelCase =GLUETransformer(A_ ) __UpperCAmelCase =generic_train(A_ , A_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __UpperCAmelCase =sorted(glob.glob(os.path.join(args.output_dir , """checkpoint-epoch=*.ckpt""" ) , recursive=A_ ) ) __UpperCAmelCase =model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(A_ ) if __name__ == "__main__": main()
68
0
from math import sqrt def snake_case ( lowerCamelCase ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(lowerCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def snake_case ( lowerCamelCase = 10_001 ): '''simple docstring''' __lowercase = 0 __lowercase = 1 while count != nth and number < 3: number += 1 if is_prime(lowerCamelCase ): count += 1 while count != nth: number += 2 if is_prime(lowerCamelCase ): count += 1 return number if __name__ == "__main__": print(F'''{solution() = }''')
80
def lowercase__ ( A_: int , A_: int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def lowercase__ ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
import torch def lowerCAmelCase_ ( ): if torch.cuda.is_available(): __snake_case : int = torch.cuda.device_count() else: __snake_case : Tuple = 0 print(F'Successfully ran on {num_gpus} GPUs' ) if __name__ == "__main__": main()
81
from __future__ import annotations import bisect def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] < item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_left(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_right(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =0 __UpperCAmelCase =len(A_ ) - 1 while left <= right: __UpperCAmelCase =left + (right - left) // 2 __UpperCAmelCase =sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __UpperCAmelCase =midpoint - 1 else: __UpperCAmelCase =midpoint + 1 return None def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =bisect.bisect_left(A_ , A_ ) if index != len(A_ ) and sorted_collection[index] == item: return index return None def lowercase__ ( A_: list[int] , A_: int , A_: int , A_: int ) -> int | None: """simple docstring""" if right < left: return None __UpperCAmelCase =left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(A_ , A_ , A_ , midpoint - 1 ) else: return binary_search_by_recursion(A_ , A_ , midpoint + 1 , A_ ) if __name__ == "__main__": __A = input("Enter numbers separated by comma:\n").strip() __A = sorted(int(item) for item in user_input.split(",")) __A = int(input("Enter a single number to be found in the list:\n")) __A = binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
68
0
"""simple docstring""" def a__ ( lowerCAmelCase__ ): if n_term == "": return [] UpperCAmelCase_ = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f"""1/{temp + 1}""" if series else "1" ) return series if __name__ == "__main__": lowerCamelCase = input("""Enter the last number (nth term) of the Harmonic Series""") print("""Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n""") print(harmonic_series(nth_term))
82
from typing import List from .keymap import KEYMAP, get_character def lowercase__ ( A_: str ) -> str: """simple docstring""" def decorator(A_: int ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += [key] setattr(A_ , """handle_key""" , A_ ) return func return decorator def lowercase__ ( *A_: List[str] ) -> Optional[int]: """simple docstring""" def decorator(A_: Tuple ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += keys setattr(A_ , """handle_key""" , A_ ) return func return decorator class _A ( UpperCamelCase ): """simple docstring""" def __new__( cls : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> int: __UpperCAmelCase =super().__new__(cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if not hasattr(__SCREAMING_SNAKE_CASE , """key_handler""" ): setattr(__SCREAMING_SNAKE_CASE , """key_handler""" , {} ) setattr(__SCREAMING_SNAKE_CASE , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , """handle_key""" , [] ) for key in handled_keys: __UpperCAmelCase =value return new_cls @staticmethod def _a ( cls : Dict ) -> List[Any]: __UpperCAmelCase =get_character() if char != KEYMAP["undefined"]: __UpperCAmelCase =ord(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =cls.key_handler.get(__SCREAMING_SNAKE_CASE ) if handler: __UpperCAmelCase =char return handler(cls ) else: return None def lowercase__ ( cls: str ) -> int: """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
68
0
"""simple docstring""" from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
83
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
68
0
import os import numpy import onnx def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = a.name lowercase = b.name lowercase = '' lowercase = '' lowercase = a == b lowercase = name_a lowercase = name_b return res def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _graph_replace_input_with(node_proto.attribute[1].g , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n in graph_proto.node: _node_replace_input_with(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = list(model.graph.initializer ) lowercase = 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 lowercase = inits[i].name lowercase = 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 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ): lowercase = os.path.dirname(__SCREAMING_SNAKE_CASE ) lowercase = os.path.basename(__SCREAMING_SNAKE_CASE ) lowercase = onnx.load(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) lowercase = list(model.graph.initializer ) lowercase = set() lowercase = {} lowercase = [] lowercase = 0 for i in range(len(__SCREAMING_SNAKE_CASE ) ): if i in dup_set: continue for j in range(i + 1 , len(__SCREAMING_SNAKE_CASE ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(__SCREAMING_SNAKE_CASE ) dup_set.add(__SCREAMING_SNAKE_CASE ) lowercase = inits[j].data_type lowercase = 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: ' , __SCREAMING_SNAKE_CASE ) total_reduced_size += mem_size lowercase = inits[i].name lowercase = inits[j].name if name_i in dup_map: dup_map[name_i].append(__SCREAMING_SNAKE_CASE ) else: lowercase = [name_j] ind_to_replace.append((j, i) ) print('total reduced size: ' , total_reduced_size / 1024 / 1024 / 1024 , 'GB' ) lowercase = sorted(__SCREAMING_SNAKE_CASE ) _remove_dup_initializers_from_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase = 'optimized_' + model_file_name lowercase = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) onnx.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return new_model
84
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _A ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Optional[Any]=99 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : int=5 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : str=37 , __SCREAMING_SNAKE_CASE : Union[str, Any]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : str=512 , __SCREAMING_SNAKE_CASE : Dict=16 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : List[str]=4 , ) -> Optional[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =seq_length __UpperCAmelCase =is_training __UpperCAmelCase =use_attention_mask __UpperCAmelCase =use_token_type_ids __UpperCAmelCase =use_labels __UpperCAmelCase =vocab_size __UpperCAmelCase =hidden_size __UpperCAmelCase =num_hidden_layers __UpperCAmelCase =num_attention_heads __UpperCAmelCase =intermediate_size __UpperCAmelCase =hidden_act __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =max_position_embeddings __UpperCAmelCase =type_vocab_size __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =initializer_range __UpperCAmelCase =num_choices def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase =None if self.use_attention_mask: __UpperCAmelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase =None if self.use_token_type_ids: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase =RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def _a ( self : List[str] ) -> Dict: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase =True __UpperCAmelCase =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] = True lowerCamelCase : Union[str, Any] = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =FlaxRobertaModelTester(self ) @slow def _a ( self : Optional[Any] ) -> List[Any]: for model_class_name in self.all_model_classes: __UpperCAmelCase =model_class_name.from_pretrained("""roberta-base""" , from_pt=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model(np.ones((1, 1) ) ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
68
0
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : List[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[int] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : int = 1 # (0 is vertical, 1 is horizontal) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = get_dataset(lowercase__ , lowercase__ ) print('Processing...' ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(lowercase__ , lowercase__ , lowercase__ ) for index, image in enumerate(lowercase__ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : Optional[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , lowercase__ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(lowercase__ )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : str = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Optional[int] = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(lowercase__ ) with open(f'''/{file_root}.txt''' , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Tuple = [] for label_file in glob.glob(os.path.join(lowercase__ , '*.txt' ) ): SCREAMING_SNAKE_CASE__ : Dict = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(lowercase__ ) as in_file: SCREAMING_SNAKE_CASE__ : Optional[Any] = in_file.readlines() SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(lowercase__ , f'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : str = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : List[Any] = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(lowercase__ ) labels.append(lowercase__ ) return img_paths, labels def _a ( lowercase__ : list , lowercase__ : list , lowercase__ : int = 1 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : int = [] for idx in range(len(lowercase__ ) ): SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : Tuple = img_list[idx] path_list.append(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = anno_list[idx] SCREAMING_SNAKE_CASE__ : List[str] = cva.imread(lowercase__ ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(lowercase__ , lowercase__ ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = cva.flip(lowercase__ , lowercase__ ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Dict = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(lowercase__ ) new_imgs_list.append(lowercase__ ) return new_imgs_list, new_annos_lists, path_list def _a ( lowercase__ : int = 32 ): '''simple docstring''' assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : Dict = ascii_lowercase + digits return "".join(random.choice(lowercase__ ) for _ in range(lowercase__ ) ) if __name__ == "__main__": main() print("DONE ✅")
85
from __future__ import annotations def lowercase__ ( A_: list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(A_ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
68
0
from ..utils import DummyObject, requires_backends class _a ( metaclass=snake_case_ ): """simple docstring""" _lowerCamelCase : List[Any] = ['torch', 'torchsde'] def __init__( self : Any , *UpperCAmelCase : int , **UpperCAmelCase : int ): requires_backends(self , ["torch", "torchsde"] ) @classmethod def __A ( cls : Optional[int] , *UpperCAmelCase : Any , **UpperCAmelCase : int ): requires_backends(cls , ["torch", "torchsde"] ) @classmethod def __A ( cls : int , *UpperCAmelCase : Tuple , **UpperCAmelCase : List[Any] ): requires_backends(cls , ["torch", "torchsde"] )
86
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowercase__ ( A_: int , A_: int , A_: int , A_: int , A_: int , A_: int ) -> np.ndarray: """simple docstring""" if (ksize % 2) == 0: __UpperCAmelCase =ksize + 1 __UpperCAmelCase =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(A_ ): for x in range(A_ ): # distance from center __UpperCAmelCase =x - ksize // 2 __UpperCAmelCase =y - ksize // 2 # degree to radiant __UpperCAmelCase =theta / 180 * np.pi __UpperCAmelCase =np.cos(_theta ) __UpperCAmelCase =np.sin(_theta ) # get kernel x __UpperCAmelCase =cos_theta * px + sin_theta * py # get kernel y __UpperCAmelCase =-sin_theta * px + cos_theta * py # fill kernel __UpperCAmelCase =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __A = imread("../image_data/lena.jpg") # turn image in gray scale value __A = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __A = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 1_20, 1_50]: __A = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __A = out / out.max() * 2_55 __A = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
68
0
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = (DDPMScheduler,) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **UpperCAmelCase__ : Union[str, Any]) ->Any: '''simple docstring''' A__ = { '''num_train_timesteps''': 1_000, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**UpperCAmelCase__) return config def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[Any]: '''simple docstring''' for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->str: '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2]): self.check_over_configs(beta_start=UpperCAmelCase__ , beta_end=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : str) ->Dict: '''simple docstring''' for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->List[Any]: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Tuple: '''simple docstring''' self.check_over_configs(thresholding=UpperCAmelCase__) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=UpperCAmelCase__ , prediction_type=UpperCAmelCase__ , sample_max_value=UpperCAmelCase__ , ) def SCREAMING_SNAKE_CASE ( self : List[str]) ->str: '''simple docstring''' for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' for t in [0, 500, 999]: self.check_over_forward(time_step=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Union[str, Any]: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config() A__ = scheduler_class(**UpperCAmelCase__) assert torch.sum(torch.abs(scheduler._get_variance(0) - 0.0)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487) - 0.00979)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999) - 0.02)) < 1e-5 def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[Any]: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config() A__ = scheduler_class(**UpperCAmelCase__) A__ = len(UpperCAmelCase__) A__ = self.dummy_model() A__ = self.dummy_sample_deter A__ = torch.manual_seed(0) for t in reversed(range(UpperCAmelCase__)): # 1. predict noise residual A__ = model(UpperCAmelCase__ , UpperCAmelCase__) # 2. predict previous mean of sample x_t-1 A__ = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance A__ = pred_prev_sample A__ = torch.sum(torch.abs(UpperCAmelCase__)) A__ = torch.mean(torch.abs(UpperCAmelCase__)) assert abs(result_sum.item() - 258.9606) < 1e-2 assert abs(result_mean.item() - 0.3372) < 1e-3 def SCREAMING_SNAKE_CASE ( self : int) ->int: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config(prediction_type='''v_prediction''') A__ = scheduler_class(**UpperCAmelCase__) A__ = len(UpperCAmelCase__) A__ = self.dummy_model() A__ = self.dummy_sample_deter A__ = torch.manual_seed(0) for t in reversed(range(UpperCAmelCase__)): # 1. predict noise residual A__ = model(UpperCAmelCase__ , UpperCAmelCase__) # 2. predict previous mean of sample x_t-1 A__ = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance A__ = pred_prev_sample A__ = torch.sum(torch.abs(UpperCAmelCase__)) A__ = torch.mean(torch.abs(UpperCAmelCase__)) assert abs(result_sum.item() - 202.0296) < 1e-2 assert abs(result_mean.item() - 0.2631) < 1e-3 def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Tuple: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config() A__ = scheduler_class(**UpperCAmelCase__) A__ = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=UpperCAmelCase__) A__ = scheduler.timesteps for i, timestep in enumerate(UpperCAmelCase__): if i == len(UpperCAmelCase__) - 1: A__ = -1 else: A__ = timesteps[i + 1] A__ = scheduler.previous_timestep(UpperCAmelCase__) A__ = prev_t.item() self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[str]: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config() A__ = scheduler_class(**UpperCAmelCase__) A__ = [100, 87, 50, 51, 0] with self.assertRaises(UpperCAmelCase__ , msg='''`custom_timesteps` must be in descending order.'''): scheduler.set_timesteps(timesteps=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config() A__ = scheduler_class(**UpperCAmelCase__) A__ = [100, 87, 50, 1, 0] A__ = len(UpperCAmelCase__) with self.assertRaises(UpperCAmelCase__ , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.'''): scheduler.set_timesteps(num_inference_steps=UpperCAmelCase__ , timesteps=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->List[str]: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config() A__ = scheduler_class(**UpperCAmelCase__) A__ = [scheduler.config.num_train_timesteps] with self.assertRaises( UpperCAmelCase__ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=UpperCAmelCase__)
87
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : """simple docstring""" def __init__( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , __SCREAMING_SNAKE_CASE : List[str]=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=[1, 2, 1] , __SCREAMING_SNAKE_CASE : List[Any]=[2, 2, 4] , __SCREAMING_SNAKE_CASE : str=2 , __SCREAMING_SNAKE_CASE : Any=2.0 , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Dict=0.0 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : Any="gelu" , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : List[Any]=0.02 , __SCREAMING_SNAKE_CASE : Tuple=1e-5 , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Any=10 , __SCREAMING_SNAKE_CASE : Dict=8 , ) -> List[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =image_size __UpperCAmelCase =patch_size __UpperCAmelCase =num_channels __UpperCAmelCase =embed_dim __UpperCAmelCase =depths __UpperCAmelCase =num_heads __UpperCAmelCase =window_size __UpperCAmelCase =mlp_ratio __UpperCAmelCase =qkv_bias __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =drop_path_rate __UpperCAmelCase =hidden_act __UpperCAmelCase =use_absolute_embeddings __UpperCAmelCase =patch_norm __UpperCAmelCase =layer_norm_eps __UpperCAmelCase =initializer_range __UpperCAmelCase =is_training __UpperCAmelCase =scope __UpperCAmelCase =use_labels __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =encoder_stride def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase =None if self.use_labels: __UpperCAmelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase =self.get_config() return config, pixel_values, labels def _a ( self : List[Any] ) -> Optional[Any]: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: __UpperCAmelCase =SwinvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase =int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> Tuple: __UpperCAmelCase =SwinvaForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase =1 __UpperCAmelCase =SwinvaForMaskedImageModeling(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: __UpperCAmelCase =self.type_sequence_label_size __UpperCAmelCase =SwinvaForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self : List[str] ) -> Tuple: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[int] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCamelCase : Tuple = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowerCamelCase : Dict = False lowerCamelCase : Tuple = False lowerCamelCase : List[str] = False lowerCamelCase : Tuple = False def _a ( self : str ) -> str: __UpperCAmelCase =SwinvaModelTester(self ) __UpperCAmelCase =ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , embed_dim=37 ) def _a ( self : List[Any] ) -> Optional[int]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self : str ) -> str: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def _a ( self : Tuple ) -> Tuple: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def _a ( self : Optional[Any] ) -> int: pass def _a ( self : Tuple ) -> int: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def _a ( self : str ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase =[*signature.parameters.keys()] __UpperCAmelCase =["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =True for model_class in self.all_model_classes: __UpperCAmelCase =True __UpperCAmelCase =False __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions __UpperCAmelCase =len(self.model_tester.depths ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase =True __UpperCAmelCase =config.window_size**2 __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase =len(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __UpperCAmelCase =True __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase =self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase =2 self.assertEqual(out_len + added_hidden_states , len(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> int: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.hidden_states __UpperCAmelCase =getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # Swinv2 has a different seq_length __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase =outputs.reshaped_hidden_states self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =reshaped_hidden_states[0].shape __UpperCAmelCase =( reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self : str ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =3 __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Dict: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def _a ( self : int ) -> Dict: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase =SwinvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def _a ( self : Dict ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =_config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __UpperCAmelCase =model_class(config=__SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _A ( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self : Tuple ) -> Dict: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def _a ( self : int ) -> Optional[int]: __UpperCAmelCase =SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.default_image_processor __UpperCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase =image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE ) # verify the logits __UpperCAmelCase =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
68
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) 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. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = 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_mae""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _lowerCamelCase : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : str = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A = logging.get_logger(__name__) __A = {"vocab_file": "spiece.model"} __A = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } __A = { "AI-Sweden/gpt-sw3-126m": 20_48, "AI-Sweden/gpt-sw3-350m": 20_48, "AI-Sweden/gpt-sw3-1.6b": 20_48, "AI-Sweden/gpt-sw3-6.7b": 20_48, "AI-Sweden/gpt-sw3-20b": 20_48, } class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : int = VOCAB_FILES_NAMES lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : List[str]=False , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Optional[Dict[str, Any]] = None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> None: __UpperCAmelCase ={} if sp_model_kwargs is None else sp_model_kwargs __UpperCAmelCase =kwargs.get("""name_or_path""" ) if name_or_path is None: logger.warning( """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,""" """ you are testing the model, this can safely be ignored""" ) __UpperCAmelCase ="""None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __UpperCAmelCase ="""<|endoftext|>""" if eos_token is None else eos_token __UpperCAmelCase ="""<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __UpperCAmelCase =unk_token if pad_token is None else pad_token __UpperCAmelCase =eos_token if bos_token is None else bos_token else: __UpperCAmelCase ="""<pad>""" if pad_token is None else pad_token __UpperCAmelCase ="""<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=__SCREAMING_SNAKE_CASE , remove_space=__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) __UpperCAmelCase =do_lower_case __UpperCAmelCase =remove_space __UpperCAmelCase =keep_accents __UpperCAmelCase =vocab_file __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) # Used for whitespace normalization in input texts # fmt : off __UpperCAmelCase ={""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __UpperCAmelCase =re.compile( f'''[{"".join(map(__SCREAMING_SNAKE_CASE , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self : Any ) -> str: __UpperCAmelCase =self.__dict__.copy() __UpperCAmelCase =None return state def __setstate__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: __UpperCAmelCase =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __UpperCAmelCase ={} __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def _a ( self : Union[str, Any] ) -> int: return len(self.sp_model ) def _a ( self : Dict , __SCREAMING_SNAKE_CASE : str ) -> str: __UpperCAmelCase =self.non_printing_characters_re.sub("""""" , __SCREAMING_SNAKE_CASE ) # Normalize whitespaces __UpperCAmelCase ="""""".join([char if char not in self.whitespaces else """ """ for char in text] ) # NFC Unicode normalization __UpperCAmelCase =unicodedata.normalize("""NFC""" , __SCREAMING_SNAKE_CASE ) return text def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str ) -> int: return self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : int ) -> str: return self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) @staticmethod def _a ( __SCREAMING_SNAKE_CASE : str ) -> str: return out_string def _a ( self : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> str: __UpperCAmelCase =[] __UpperCAmelCase ="""""" __UpperCAmelCase =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token __UpperCAmelCase =True __UpperCAmelCase =[] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =False out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string def _a ( self : Any ) -> Dict[str, int]: __UpperCAmelCase ={self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __UpperCAmelCase =os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , """wb""" ) as fi: __UpperCAmelCase =self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, List[str]] , __SCREAMING_SNAKE_CASE : Union[str, bool] = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) else: __UpperCAmelCase =[self.preprocess_text(__SCREAMING_SNAKE_CASE ) for t in text] __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) if return_tensors is True or return_tensors == "pt": __UpperCAmelCase =torch.tensor(__SCREAMING_SNAKE_CASE ) return token_ids def _a ( self : str , __SCREAMING_SNAKE_CASE : Union[int, List[int]] ) -> str: return self.sp_model.decode(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : "Conversation" ) -> List[int]: __UpperCAmelCase =[f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __UpperCAmelCase =( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(__SCREAMING_SNAKE_CASE ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=__SCREAMING_SNAKE_CASE )
68
0
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : List[Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE : int = { "vocab_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", }, "tokenizer_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/tokenizer.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/tokenizer.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/tokenizer.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/tokenizer.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/tokenizer.json", }, } # TODO(PVP) - this should be removed in Transformers v5 SCREAMING_SNAKE_CASE : List[Any] = { "t5-small": 512, "t5-base": 512, "t5-large": 512, "t5-3b": 512, "t5-11b": 512, } class _lowerCamelCase( _a ): lowercase_ : Tuple = VOCAB_FILES_NAMES lowercase_ : Any = PRETRAINED_VOCAB_FILES_MAP lowercase_ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ : Any = ["""input_ids""", """attention_mask"""] lowercase_ : List[str] = TaTokenizer lowercase_ : List[int] = [] def __init__( self, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase="</s>", lowerCamelCase="<unk>", lowerCamelCase="<pad>", lowerCamelCase=1_00, lowerCamelCase=None, **lowerCamelCase, ) -> Optional[int]: """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: _lowercase : Tuple = [F'''<extra_id_{i}>''' for i in range(lowerCamelCase)] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens _lowercase : Optional[int] = len(set(filter(lambda lowerCamelCase: bool('extra_id_' in str(lowerCamelCase)), lowerCamelCase))) if extra_tokens != extra_ids: raise ValueError( F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids' ' tokens') super().__init__( lowerCamelCase, tokenizer_file=lowerCamelCase, eos_token=lowerCamelCase, unk_token=lowerCamelCase, pad_token=lowerCamelCase, extra_ids=lowerCamelCase, additional_special_tokens=lowerCamelCase, **lowerCamelCase, ) _lowercase : Any = vocab_file _lowercase : Dict = False if not self.vocab_file else True _lowercase : Dict = extra_ids @staticmethod def UpperCamelCase ( lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Dict: """simple docstring""" if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: _lowercase : Dict = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( 'This tokenizer was incorrectly instantiated with a model max length of' F''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ' behavior is kept to avoid breaking backwards compatibility when padding/encoding with' ' `truncation is True`.\n- Be aware that you SHOULD NOT rely on' F''' {pretrained_model_name_or_path} automatically truncating your input to''' F''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' F''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please' ' instantiate this tokenizer with `model_max_length` set to your preferred value.', lowerCamelCase, ) return max_model_length def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.') if not os.path.isdir(lowerCamelCase): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''') return _lowercase : List[Any] = os.path.join( lowerCamelCase, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCamelCase): copyfile(self.vocab_file, lowerCamelCase) logger.info(F'''Copy vocab file to {out_vocab_file}''') return (out_vocab_file,) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> List[int]: """simple docstring""" _lowercase : List[Any] = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: _lowercase : Tuple = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> List[int]: """simple docstring""" _lowercase : List[Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos) * [0] return len(token_ids_a + eos + token_ids_a + eos) * [0] def UpperCamelCase ( self) -> int: """simple docstring""" return list( set(filter(lambda lowerCamelCase: bool(re.search(R'<extra_id_\d+>', lowerCamelCase)) is not None, self.additional_special_tokens))) def UpperCamelCase ( self) -> List[str]: """simple docstring""" return [self.convert_tokens_to_ids(lowerCamelCase) for token in self.get_sentinel_tokens()]
89
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __A = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : Union[str, None] = None , __SCREAMING_SNAKE_CASE : Union[List[str], None] = None , __SCREAMING_SNAKE_CASE : Union[str, List[str], None] = None , __SCREAMING_SNAKE_CASE : bool = True , ) -> List[str]: __UpperCAmelCase =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )] if identifier is not None: __UpperCAmelCase =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n_ in n_identifier: __UpperCAmelCase =[file for file in files if n_ not in file] else: __UpperCAmelCase =[file for file in files if n_identifier not in file] __UpperCAmelCase =ignore_files or [] ignore_files.append("""__init__.py""" ) __UpperCAmelCase =[file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , __SCREAMING_SNAKE_CASE ) if only_modules: __UpperCAmelCase =file.split(""".""" )[0] try: __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: __UpperCAmelCase =doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _a ( self : Optional[Any] ) -> List[str]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""modeling""" __UpperCAmelCase =[ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""tokenization""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] ) -> Optional[Any]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""configuration""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : List[Any] ) -> Tuple: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase =["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase =Path("""docs/source""" ) __UpperCAmelCase =["""favicon.ico"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __UpperCAmelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class a__ ( a__ ): '''simple docstring''' lowercase__ : List[str] = ["pixel_values"] def __init__( self , lowerCamelCase_ = True , lowerCamelCase_ = None , lowerCamelCase_ = PILImageResampling.BICUBIC , lowerCamelCase_ = True , lowerCamelCase_ = None , lowerCamelCase_ = True , lowerCamelCase_ = 1 / 2_55 , lowerCamelCase_ = True , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = True , **lowerCamelCase_ , ) -> None: super().__init__(**lowerCamelCase_ ) lowerCAmelCase__ = size if size is not None else {'''shortest_edge''': 2_24} lowerCAmelCase__ = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ ) lowerCAmelCase__ = crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24} lowerCAmelCase__ = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ , param_name='''crop_size''' ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = resample lowerCAmelCase__ = do_center_crop lowerCAmelCase__ = crop_size lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCAmelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD lowerCAmelCase__ = do_convert_rgb def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = PILImageResampling.BICUBIC , lowerCamelCase_ = None , **lowerCamelCase_ , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) lowerCAmelCase__ = get_resize_output_image_size(lowerCamelCase_ , size=size['''shortest_edge'''] , default_to_square=lowerCamelCase_ ) return resize(lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = None , **lowerCamelCase_ , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(lowerCamelCase_ ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(lowerCamelCase_ , size=(size['''height'''], size['''width''']) , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = None , **lowerCamelCase_ , ) -> str: return rescale(lowerCamelCase_ , scale=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = None , **lowerCamelCase_ , ) -> np.ndarray: return normalize(lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = ChannelDimension.FIRST , **lowerCamelCase_ , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(lowerCamelCase_ , param_name='''size''' , default_to_square=lowerCamelCase_ ) lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCAmelCase__ = crop_size if crop_size is not None else self.crop_size lowerCAmelCase__ = get_size_dict(lowerCamelCase_ , param_name='''crop_size''' , default_to_square=lowerCamelCase_ ) lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCAmelCase__ = make_list_of_images(lowerCamelCase_ ) if not valid_images(lowerCamelCase_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowerCAmelCase__ = [convert_to_rgb(lowerCamelCase_ ) for image in images] # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(lowerCamelCase_ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ ) for image in images] if do_center_crop: lowerCAmelCase__ = [self.center_crop(image=lowerCamelCase_ , size=lowerCamelCase_ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=lowerCamelCase_ , scale=lowerCamelCase_ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(lowerCamelCase_ , lowerCamelCase_ ) for image in images] lowerCAmelCase__ = {'''pixel_values''': images} return BatchFeature(data=lowerCamelCase_ , tensor_type=lowerCamelCase_ )
90
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __A = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def lowercase__ ( A_: int , A_: Optional[Any] , A_: List[str]=None ) -> List[str]: """simple docstring""" if rng is None: __UpperCAmelCase =random.Random() __UpperCAmelCase =1 for dim in shape: total_dims *= dim __UpperCAmelCase =[] for _ in range(A_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __UpperCAmelCase =np.array(A_ , dtype=jnp.intaa ).reshape(A_ ) return output def lowercase__ ( A_: List[str] , A_: List[str]=None ) -> Any: """simple docstring""" __UpperCAmelCase =ids_tensor(A_ , vocab_size=2 , rng=A_ ) # make sure that at least one token is attended to for each batch __UpperCAmelCase =1 return attn_mask @require_flax class _A : """simple docstring""" lowerCamelCase : Optional[Any] = None lowerCamelCase : int = () def _a ( self : str ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __UpperCAmelCase =2 __UpperCAmelCase =inputs["""input_ids"""].shape[-1] // 2 __UpperCAmelCase =inputs["""input_ids"""][:max_batch_size, :sequence_length] __UpperCAmelCase =jnp.ones_like(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __UpperCAmelCase =input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __UpperCAmelCase =config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _a ( self : Union[str, Any] ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =0 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model_class.__name__[4:] # Skip the "Flax" at the beginning __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =pt_model_class(__SCREAMING_SNAKE_CASE ).eval() __UpperCAmelCase =load_flax_weights_in_pytorch_model(__SCREAMING_SNAKE_CASE , flax_model.params ) __UpperCAmelCase =flax_model.generate(__SCREAMING_SNAKE_CASE ).sequences __UpperCAmelCase =pt_model.generate(torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __UpperCAmelCase =flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[Any] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _a ( self : Union[str, Any] ) -> List[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length __UpperCAmelCase =0.8 __UpperCAmelCase =10 __UpperCAmelCase =0.3 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[str] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =2 __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : int ) -> Any: __UpperCAmelCase =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) __UpperCAmelCase =FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) __UpperCAmelCase ="""Hello world""" __UpperCAmelCase =tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """do_samples""" ): model.generate(__SCREAMING_SNAKE_CASE , do_samples=__SCREAMING_SNAKE_CASE ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """foo""" ): __UpperCAmelCase ={"""foo""": """bar"""} model.generate(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
68
0
"""simple docstring""" def _snake_case ( snake_case__ : int ): if num < 0: return False A = num A = 0 while num > 0: A = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
91
from __future__ import annotations from collections.abc import Iterator class _A : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : int ) -> None: __UpperCAmelCase =value __UpperCAmelCase =None __UpperCAmelCase =None class _A : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Node ) -> None: __UpperCAmelCase =tree def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : int ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def _lowerCAmelCase ( __magic_name__ : Any , __magic_name__ : Tuple=7 ) -> List[Any]: lowercase : str =None if token is not None: lowercase : List[str] ={'''Accept''': '''application/vnd.github+json''', '''Authorization''': f'''Bearer {token}'''} # The id of a workflow (not of a workflow run) lowercase : Optional[int] ='''636036''' lowercase : Union[str, Any] =f'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += f'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' lowercase : Optional[int] =requests.get(__magic_name__ , headers=__magic_name__ ).json() return result["workflow_runs"] def _lowerCAmelCase ( __magic_name__ : Optional[int] ) -> Optional[Any]: lowercase : Dict =get_daily_ci_runs(__magic_name__ ) lowercase : Optional[Any] =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": lowercase : Tuple =workflow_run['''id'''] break return workflow_run_id def _lowerCAmelCase ( __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : int ) -> Tuple: lowercase : Tuple =get_last_daily_ci_runs(__magic_name__ ) if workflow_run_id is not None: lowercase : str =get_artifacts_links(worflow_run_id=__magic_name__ , token=__magic_name__ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: lowercase : int =artifacts_links[artifact_name] download_artifact( artifact_name=__magic_name__ , artifact_url=__magic_name__ , output_dir=__magic_name__ , token=__magic_name__ ) def _lowerCAmelCase ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] ) -> int: get_last_daily_ci_artifacts(__magic_name__ , __magic_name__ , __magic_name__ ) lowercase : List[str] ={} for artifact_name in artifact_names: lowercase : Any =os.path.join(__magic_name__ , f'''{artifact_name}.zip''' ) if os.path.isfile(__magic_name__ ): lowercase : List[Any] ={} with zipfile.ZipFile(__magic_name__ ) as z: for filename in z.namelist(): if not os.path.isdir(__magic_name__ ): # read the file with z.open(__magic_name__ ) as f: lowercase : List[str] =f.read().decode('''UTF-8''' ) return results
92
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def lowercase__ ( A_: Union[str, Any] ) -> List[Any]: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=A_ , AssumeRolePolicyDocument=json.dumps(A_ , indent=2 ) ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=A_ , PolicyName=F'''{role_name}_policy_permission''' , PolicyDocument=json.dumps(A_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F'''role {role_name} already exists. Using existing one''' ) def lowercase__ ( A_: Dict ) -> Any: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) return iam_client.get_role(RoleName=A_ )["Role"]["Arn"] def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase =_ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , A_ , ) __UpperCAmelCase =None if credentials_configuration == 0: __UpperCAmelCase =_ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) __UpperCAmelCase =aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __UpperCAmelCase =_ask_field("""AWS Access Key ID: """ ) __UpperCAmelCase =aws_access_key_id __UpperCAmelCase =_ask_field("""AWS Secret Access Key: """ ) __UpperCAmelCase =aws_secret_access_key __UpperCAmelCase =_ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) __UpperCAmelCase =aws_region __UpperCAmelCase =_ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , A_ , ) if role_management == 0: __UpperCAmelCase =_ask_field("""Enter your IAM role name: """ ) else: __UpperCAmelCase ="""accelerate_sagemaker_execution_role""" print(F'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(A_ ) __UpperCAmelCase =_ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_custom_docker_image: __UpperCAmelCase =_ask_field("""Enter your Docker image: """ , lambda A_ : str(A_ ).lower() ) __UpperCAmelCase =_ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_inputs_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_metrics_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) __UpperCAmelCase ={} __UpperCAmelCase =_ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_dynamo: __UpperCAmelCase ="""dynamo_""" __UpperCAmelCase =_ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __UpperCAmelCase =_ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_custom_options: __UpperCAmelCase =_ask_options( """Which mode do you want to use?""" , A_ , lambda A_ : TORCH_DYNAMO_MODES[int(A_ )] , default="""default""" , ) __UpperCAmelCase =_ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =_ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase ="""Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __UpperCAmelCase =_ask_options( A_ , A_ , lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __UpperCAmelCase =_ask_field(A_ , lambda A_ : str(A_ ).lower() , default="""ml.p3.2xlarge""" ) __UpperCAmelCase =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __UpperCAmelCase =_ask_field( """How many machines do you want use? [1]: """ , A_ , default=1 , ) __UpperCAmelCase =_ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=A_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=A_ , use_cpu=A_ , dynamo_config=A_ , eca_instance_type=A_ , profile=A_ , region=A_ , iam_role_name=A_ , mixed_precision=A_ , num_machines=A_ , sagemaker_inputs_file=A_ , sagemaker_metrics_file=A_ , )
68
0
"""simple docstring""" from __future__ import annotations import time __A = list[tuple[int, int]] __A = [ [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 = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = pos_x lowerCAmelCase__ :str = pos_y lowerCAmelCase__ :int = (pos_y, pos_x) lowerCAmelCase__ :List[Any] = goal_x lowerCAmelCase__ :List[Any] = goal_y lowerCAmelCase__ :List[Any] = parent class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = Node(start[1] , start[0] , goal[1] , goal[0] , __UpperCAmelCase ) lowerCAmelCase__ :Any = Node(goal[1] , goal[0] , goal[1] , goal[0] , __UpperCAmelCase ) lowerCAmelCase__ :Any = [self.start] lowerCAmelCase__ :Optional[Any] = False def snake_case ( self ): '''simple docstring''' while self.node_queue: lowerCAmelCase__ :List[Any] = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: lowerCAmelCase__ :Dict = True return self.retrace_path(__UpperCAmelCase ) lowerCAmelCase__ :Dict = self.get_successors(__UpperCAmelCase ) for node in successors: self.node_queue.append(__UpperCAmelCase ) if not self.reached: return [self.start.pos] return None def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = [] for action in delta: lowerCAmelCase__ :str = parent.pos_x + action[1] lowerCAmelCase__ :Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__UpperCAmelCase ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(__UpperCAmelCase , __UpperCAmelCase , self.target.pos_y , self.target.pos_x , __UpperCAmelCase ) ) return successors def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = node lowerCAmelCase__ :int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) lowerCAmelCase__ :Any = current_node.parent path.reverse() return path class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = BreadthFirstSearch(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = BreadthFirstSearch(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = False def snake_case ( self ): '''simple docstring''' while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: lowerCAmelCase__ :List[Any] = self.fwd_bfs.node_queue.pop(0 ) lowerCAmelCase__ :List[str] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: lowerCAmelCase__ :Dict = True return self.retrace_bidirectional_path( __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Tuple = current_bwd_node lowerCAmelCase__ :int = current_fwd_node lowerCAmelCase__ :Any = { self.fwd_bfs: self.fwd_bfs.get_successors(__UpperCAmelCase ), self.bwd_bfs: self.bwd_bfs.get_successors(__UpperCAmelCase ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(__UpperCAmelCase ) if not self.reached: return [self.fwd_bfs.start.pos] return None def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.fwd_bfs.retrace_path(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self.bwd_bfs.retrace_path(__UpperCAmelCase ) bwd_path.pop() bwd_path.reverse() lowerCAmelCase__ :List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() __A = (0, 0) __A = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __A = time.time() __A = BreadthFirstSearch(init, goal) __A = bfs.search() __A = time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) __A = time.time() __A = BidirectionalBreadthFirstSearch(init, goal) __A = bd_bfs.search() __A = time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
93
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Tuple = 'ctrl' lowerCamelCase : Any = ['past_key_values'] lowerCamelCase : Optional[int] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=246534 , __SCREAMING_SNAKE_CASE : int=256 , __SCREAMING_SNAKE_CASE : Optional[Any]=1280 , __SCREAMING_SNAKE_CASE : Optional[Any]=8192 , __SCREAMING_SNAKE_CASE : int=48 , __SCREAMING_SNAKE_CASE : Union[str, Any]=16 , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : List[Any]=1e-6 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : Union[str, Any]=True , **__SCREAMING_SNAKE_CASE : int , ) -> Any: __UpperCAmelCase =vocab_size __UpperCAmelCase =n_positions __UpperCAmelCase =n_embd __UpperCAmelCase =n_layer __UpperCAmelCase =n_head __UpperCAmelCase =dff __UpperCAmelCase =resid_pdrop __UpperCAmelCase =embd_pdrop __UpperCAmelCase =layer_norm_epsilon __UpperCAmelCase =initializer_range __UpperCAmelCase =use_cache super().__init__(**__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCAmelCase_ ( __A ): """simple docstring""" UpperCamelCase_ = '''facebook/bart-large-mnli''' UpperCamelCase_ = ( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) UpperCamelCase_ = '''text_classifier''' UpperCamelCase_ = AutoTokenizer UpperCamelCase_ = AutoModelForSequenceClassification UpperCamelCase_ = ['''text''', ['''text''']] UpperCamelCase_ = ['''text'''] def A__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' super().setup() lowercase : Dict =self.model.config lowercase : Tuple =-1 for idx, label in config.idalabel.items(): if label.lower().startswith('''entail''' ): lowercase : int =int(UpperCAmelCase ) if self.entailment_id == -1: raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''' ) def A__ ( self : List[str] , UpperCAmelCase : Optional[int] , UpperCAmelCase : List[str] ) -> Union[str, Any]: '''simple docstring''' lowercase : Dict =labels return self.pre_processor( [text] * len(UpperCAmelCase ) , [f'This example is {label}' for label in labels] , return_tensors='''pt''' , padding='''max_length''' , ) def A__ ( self : Optional[int] , UpperCAmelCase : Dict ) -> Tuple: '''simple docstring''' lowercase : int =outputs.logits lowercase : Optional[int] =torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
94
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = [ ["attention", "attn"], ["encoder_attention", "encoder_attn"], ["q_lin", "q_proj"], ["k_lin", "k_proj"], ["v_lin", "v_proj"], ["out_lin", "out_proj"], ["norm_embeddings", "layernorm_embedding"], ["position_embeddings", "embed_positions"], ["embeddings", "embed_tokens"], ["ffn.lin", "fc"], ] def lowercase__ ( A_: Optional[Any] ) -> Union[str, Any]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __UpperCAmelCase =k.replace(A_ , A_ ) if k.startswith("""encoder""" ): __UpperCAmelCase =k.replace(""".attn""" , """.self_attn""" ) __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """encoder_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm3""" , """final_layer_norm""" ) return k def lowercase__ ( A_: Tuple ) -> str: """simple docstring""" __UpperCAmelCase =[ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: __UpperCAmelCase =sd.pop(A_ ) __UpperCAmelCase =k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd __UpperCAmelCase =v __A = ["START"] @torch.no_grad() def lowercase__ ( A_: List[Any] , A_: str , A_: int ) -> Optional[int]: """simple docstring""" __UpperCAmelCase =torch.load(A_ , map_location="""cpu""" ) __UpperCAmelCase =model["""model"""] __UpperCAmelCase =BlenderbotConfig.from_json_file(A_ ) __UpperCAmelCase =BlenderbotForConditionalGeneration(A_ ) __UpperCAmelCase =m.model.state_dict().keys() __UpperCAmelCase =[] __UpperCAmelCase ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue __UpperCAmelCase =rename_state_dict_key(A_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __UpperCAmelCase =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(A_ ) m.model.load_state_dict(A_ , strict=A_ ) m.half() m.save_pretrained(A_ ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin") parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.") parser.add_argument( "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use" ) __A = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
68
0
"""simple docstring""" import unittest from transformers import DonutProcessor lowerCamelCase_ = '''naver-clova-ix/donut-base''' class UpperCamelCase_ (unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: UpperCAmelCase_ : Optional[int] = DonutProcessor.from_pretrained(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: UpperCAmelCase_ : Any = { "name": "John Doe", "age": "99", "city": "Atlanta", "state": "GA", "zip": "30301", "phone": "123-4567", "nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}], } UpperCAmelCase_ : List[str] = ( "<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>" "<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>" "<s_nicknames><s_nickname>Johnny</s_nickname>" "<sep/><s_nickname>JD</s_nickname></s_nicknames>" ) UpperCAmelCase_ : Dict = self.processor.tokenajson(lowerCAmelCase_ ) self.assertDictEqual(lowerCAmelCase_ , lowerCAmelCase_ )
95
from itertools import permutations def lowercase__ ( A_: tuple ) -> bool: """simple docstring""" 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 =[7, 11, 13, 17] for i, test in enumerate(A_ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def lowercase__ ( A_: int = 10 ) -> int: """simple docstring""" return sum( int("""""".join(map(A_ , A_ ) ) ) for num in permutations(range(A_ ) ) if is_substring_divisible(A_ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
68
0
"""simple docstring""" import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __A ( SCREAMING_SNAKE_CASE_ ): UpperCAmelCase__ = ["image_processor", "tokenizer"] UpperCAmelCase__ = "FlavaImageProcessor" UpperCAmelCase__ = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Optional[Any] , __snake_case : Dict=None , __snake_case : List[str]=None , **__snake_case : int ) -> Any: __magic_name__: str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __snake_case , ) __magic_name__: List[str] = kwargs.pop("""feature_extractor""" ) __magic_name__: Optional[int] = 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__(__snake_case , __snake_case ) __magic_name__: Any = self.image_processor def __call__( self : str , __snake_case : Optional[ImageInput] = None , __snake_case : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , __snake_case : bool = True , __snake_case : Union[bool, str, PaddingStrategy] = False , __snake_case : Union[bool, str, TruncationStrategy] = False , __snake_case : Optional[int] = None , __snake_case : int = 0 , __snake_case : Optional[int] = None , __snake_case : Optional[bool] = None , __snake_case : Optional[bool] = None , __snake_case : Optional[bool] = None , __snake_case : Optional[bool] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : bool = False , __snake_case : bool = False , __snake_case : bool = True , __snake_case : Optional[Union[str, TensorType]] = None , **__snake_case : Any , ) -> Optional[int]: 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: __magic_name__: Optional[Any] = 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_token_type_ids=__snake_case , return_attention_mask=__snake_case , return_overflowing_tokens=__snake_case , return_special_tokens_mask=__snake_case , return_offsets_mapping=__snake_case , return_length=__snake_case , verbose=__snake_case , return_tensors=__snake_case , **__snake_case , ) if images is not None: __magic_name__: List[str] = self.image_processor( __snake_case , return_image_mask=__snake_case , return_codebook_pixels=__snake_case , return_tensors=__snake_case , **__snake_case , ) if text is not None and images is not None: encoding.update(__snake_case ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__snake_case ) , tensor_type=__snake_case ) def lowerCamelCase__ ( self : Union[str, Any] , *__snake_case : Optional[int] , **__snake_case : Optional[int] ) -> Dict: return self.tokenizer.batch_decode(*__snake_case , **__snake_case ) def lowerCamelCase__ ( self : Dict , *__snake_case : List[Any] , **__snake_case : Optional[int] ) -> int: return self.tokenizer.decode(*__snake_case , **__snake_case ) @property def lowerCamelCase__ ( self : Union[str, Any] ) -> str: __magic_name__: List[str] = self.tokenizer.model_input_names __magic_name__: List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCamelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __snake_case , ) return self.image_processor_class @property def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __snake_case , ) return self.image_processor
96
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __A = TypeVar("T") def lowercase__ ( A_: int ) -> int: """simple docstring""" return (position - 1) // 2 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 1 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 2 class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[str] ) -> None: __UpperCAmelCase =[] __UpperCAmelCase ={} __UpperCAmelCase =0 def __len__( self : str ) -> int: return self.elements def __repr__( self : Dict ) -> str: return str(self.heap ) def _a ( self : Optional[int] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __UpperCAmelCase =self.elements self.elements += 1 self._bubble_up(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __UpperCAmelCase , __UpperCAmelCase =self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __UpperCAmelCase , __UpperCAmelCase =self.heap[0] self._bubble_down(__SCREAMING_SNAKE_CASE ) return elem def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Update the weight of the given key __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase =(elem, weight) if position > 0: __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._bubble_up(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __UpperCAmelCase =self.position_map[elem] if curr_pos == 0: return None __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_up(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase =get_child_left_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =get_child_right_position(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements and child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) else: return None if child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ) -> None: # Swap the nodes at the given positions __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase , __UpperCAmelCase =( self.heap[nodea_pos], self.heap[nodea_pos], ) __UpperCAmelCase =nodea_pos __UpperCAmelCase =nodea_pos class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[Any] ) -> None: __UpperCAmelCase ={} __UpperCAmelCase =0 def __repr__( self : Tuple ) -> str: return str(self.connections ) def __len__( self : str ) -> int: return self.nodes def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __UpperCAmelCase ={} self.nodes += 1 def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(__SCREAMING_SNAKE_CASE ) self.add_node(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =weight __UpperCAmelCase =weight def lowercase__ ( A_: GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: """simple docstring""" __UpperCAmelCase ={node: maxsize for node in graph.connections} __UpperCAmelCase ={node: None for node in graph.connections} __UpperCAmelCase =MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(A_ , A_ ) if priority_queue.is_empty(): return dist, parent # initialization __UpperCAmelCase =priority_queue.extract_min() __UpperCAmelCase =0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node # running prim's algorithm while not priority_queue.is_empty(): __UpperCAmelCase =priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node return dist, parent
68
0
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract __a = logging.get_logger(__name__) def a ( snake_case__: List[str] , snake_case__: int , snake_case__: str ): '''simple docstring''' return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def a ( snake_case__: np.ndarray , snake_case__: Optional[str] , snake_case__: Optional[str] = None ): '''simple docstring''' lowercase_ = tesseract_config if tesseract_config is not None else '''''' # apply OCR lowercase_ = to_pil_image(snake_case__ ) lowercase_ , lowercase_ = pil_image.size lowercase_ = pytesseract.image_to_data(snake_case__ , lang=snake_case__ , output_type='''dict''' , config=snake_case__ ) lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates lowercase_ = [idx for idx, word in enumerate(snake_case__ ) if not word.strip()] lowercase_ = [word for idx, word in enumerate(snake_case__ ) if idx not in irrelevant_indices] lowercase_ = [coord for idx, coord in enumerate(snake_case__ ) if idx not in irrelevant_indices] lowercase_ = [coord for idx, coord in enumerate(snake_case__ ) if idx not in irrelevant_indices] lowercase_ = [coord for idx, coord in enumerate(snake_case__ ) if idx not in irrelevant_indices] lowercase_ = [coord for idx, coord in enumerate(snake_case__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format lowercase_ = [] for x, y, w, h in zip(snake_case__ , snake_case__ , snake_case__ , snake_case__ ): lowercase_ = [x, y, x + w, y + h] actual_boxes.append(snake_case__ ) # finally, normalize the bounding boxes lowercase_ = [] for box in actual_boxes: normalized_boxes.append(normalize_box(snake_case__ , snake_case__ , snake_case__ ) ) assert len(snake_case__ ) == len(snake_case__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowercase__( UpperCAmelCase ): """simple docstring""" a :int = ['pixel_values'] def __init__( self : int , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : Dict[str, int] = None , SCREAMING_SNAKE_CASE_ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = "" , **SCREAMING_SNAKE_CASE_ : Optional[Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE_ ) lowercase_ = size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) lowercase_ = do_resize lowercase_ = size lowercase_ = resample lowercase_ = apply_ocr lowercase_ = ocr_lang lowercase_ = tesseract_config def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : Dict[str, int] , SCREAMING_SNAKE_CASE_ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE_ : int , ) -> np.ndarray: lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) lowercase_ = (size['''height'''], size['''width''']) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : ImageInput , SCREAMING_SNAKE_CASE_ : bool = None , SCREAMING_SNAKE_CASE_ : Dict[str, int] = None , SCREAMING_SNAKE_CASE_ : PILImageResampling = None , SCREAMING_SNAKE_CASE_ : bool = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ : Union[str, Any] , ) -> PIL.Image.Image: lowercase_ = do_resize if do_resize is not None else self.do_resize lowercase_ = size if size is not None else self.size lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) lowercase_ = resample if resample is not None else self.resample lowercase_ = apply_ocr if apply_ocr is not None else self.apply_ocr lowercase_ = ocr_lang if ocr_lang is not None else self.ocr_lang lowercase_ = tesseract_config if tesseract_config is not None else self.tesseract_config lowercase_ = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) # All transformations expect numpy arrays. lowercase_ = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) lowercase_ = [] lowercase_ = [] for image in images: lowercase_ , lowercase_ = apply_tesseract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) words_batch.append(SCREAMING_SNAKE_CASE_ ) boxes_batch.append(SCREAMING_SNAKE_CASE_ ) if do_resize: lowercase_ = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) lowercase_ = [flip_channel_order(SCREAMING_SNAKE_CASE_ ) for image in images] lowercase_ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] lowercase_ = BatchFeature(data={'''pixel_values''': images} , tensor_type=SCREAMING_SNAKE_CASE_ ) if apply_ocr: lowercase_ = words_batch lowercase_ = boxes_batch return data
97
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 __A = logging.get_logger(__name__) @dataclass class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[int] = [ 'no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process', ] def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __UpperCAmelCase =deprecated_arg[3:] __UpperCAmelCase =not kwargs.pop(__SCREAMING_SNAKE_CASE ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) __UpperCAmelCase =kwargs.pop("""tpu_name""" , self.tpu_name ) __UpperCAmelCase =kwargs.pop("""device_idx""" , self.device_idx ) __UpperCAmelCase =kwargs.pop("""eager_mode""" , self.eager_mode ) __UpperCAmelCase =kwargs.pop("""use_xla""" , self.use_xla ) super().__init__(**__SCREAMING_SNAKE_CASE ) lowerCamelCase : str = field( default=UpperCamelCase , metadata={'help': 'Name of TPU'} , ) lowerCamelCase : int = field( default=0 , metadata={'help': 'CPU / GPU device index. Defaults to 0.'} , ) lowerCamelCase : bool = field(default=UpperCamelCase , metadata={'help': 'Benchmark models in eager model.'} ) lowerCamelCase : 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 _a ( self : List[str] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) __UpperCAmelCase =None if self.tpu: try: if self.tpu_name: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __UpperCAmelCase =None return tpu @cached_property def _a ( self : Tuple ) -> 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 ) __UpperCAmelCase =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""" ) __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , """GPU""" ) # disable GPU __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/cpu:{self.device_idx}''' ) return strategy @property def _a ( self : Optional[Any] ) -> bool: requires_backends(self , ["""tf"""] ) return self._setup_tpu is not None @property def _a ( self : str ) -> "tf.distribute.Strategy": requires_backends(self , ["""tf"""] ) return self._setup_strategy @property def _a ( self : Dict ) -> Optional[int]: requires_backends(self , ["""tf"""] ) return tf.config.list_physical_devices("""GPU""" ) @property def _a ( self : List[str] ) -> int: requires_backends(self , ["""tf"""] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _a ( self : List[str] ) -> bool: return self.n_gpu > 0
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase__ : Tuple = {'configuration_xglm': ['XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XGLMConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Optional[int] = ['XGLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[Any] = ['XGLMTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Union[str, Any] = [ 'XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XGLMForCausalLM', 'XGLMModel', 'XGLMPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[Any] = [ 'FlaxXGLMForCausalLM', 'FlaxXGLMModel', 'FlaxXGLMPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[str] = [ 'TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXGLMForCausalLM', 'TFXGLMModel', 'TFXGLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
98
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 _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Dict: torch.manual_seed(0 ) __UpperCAmelCase =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 _a ( self : int ) -> Union[str, Any]: __UpperCAmelCase =self.dummy_uncond_unet __UpperCAmelCase =ScoreSdeVeScheduler() __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE )[ 0 ] __UpperCAmelCase =image[0, -3:, -3:, -1] __UpperCAmelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCAmelCase =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 _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Optional[int] ) -> int: __UpperCAmelCase ="""google/ncsnpp-church-256""" __UpperCAmelCase =UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVeScheduler.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=10 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCAmelCase =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
68
0
from itertools import count def a (lowerCAmelCase__ = 50 ): __a = [1] * min_block_length for n in count(lowerCAmelCase__ ): fill_count_functions.append(1 ) for block_length in range(lowerCAmelCase__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f'''{solution() = }''')
99
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __A = logging.get_logger(__name__) __A = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class _A ( UpperCamelCase ): """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : str=None , *__SCREAMING_SNAKE_CASE : Union[str, Any] , **__SCREAMING_SNAKE_CASE : List[Any] ) -> Any: super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if config is None: assert isinstance(self.model , __SCREAMING_SNAKE_CASE ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f''' {self.model.__class__}''' ) __UpperCAmelCase =self.model.config else: __UpperCAmelCase =config __UpperCAmelCase =data_args __UpperCAmelCase =self.config.tgt_vocab_size if isinstance(self.config , __SCREAMING_SNAKE_CASE ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' """ padding..""" ) if self.args.label_smoothing == 0: __UpperCAmelCase =torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __UpperCAmelCase =label_smoothed_nll_loss def _a ( self : Any , __SCREAMING_SNAKE_CASE : int ) -> Any: if self.optimizer is None: __UpperCAmelCase =["""bias""", """LayerNorm.weight"""] __UpperCAmelCase =[ { """params""": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], """weight_decay""": self.args.weight_decay, }, { """params""": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], """weight_decay""": 0.0, }, ] __UpperCAmelCase =Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __UpperCAmelCase =Adafactor __UpperCAmelCase ={"""scale_parameter""": False, """relative_step""": False} else: __UpperCAmelCase =AdamW __UpperCAmelCase ={ """betas""": (self.args.adam_betaa, self.args.adam_betaa), """eps""": self.args.adam_epsilon, } __UpperCAmelCase =self.args.learning_rate if self.sharded_ddp: __UpperCAmelCase =OSS( params=__SCREAMING_SNAKE_CASE , optim=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: __UpperCAmelCase =optimizer_cls(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if self.lr_scheduler is None: __UpperCAmelCase =self._get_lr_scheduler(__SCREAMING_SNAKE_CASE ) else: # ignoring --lr_scheduler logger.warning("""scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.""" ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Any: __UpperCAmelCase =arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __UpperCAmelCase =schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __UpperCAmelCase =schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __UpperCAmelCase =schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=__SCREAMING_SNAKE_CASE ) return scheduler def _a ( self : Optional[Any] ) -> Optional[torch.utils.data.Sampler]: if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Tuple: if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __UpperCAmelCase , __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[:2] else: # compute label smoothed loss __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =torch.nn.functional.log_softmax(__SCREAMING_SNAKE_CASE , dim=-1 ) __UpperCAmelCase , __UpperCAmelCase =self.loss_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: __UpperCAmelCase =inputs.pop("""labels""" ) __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return loss def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : nn.Module , __SCREAMING_SNAKE_CASE : Dict[str, Union[torch.Tensor, Any]] , __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : Optional[List[str]] = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: __UpperCAmelCase =self._prepare_inputs(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """max_length""": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, """num_beams""": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __UpperCAmelCase =self.model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , **__SCREAMING_SNAKE_CASE , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) __UpperCAmelCase =inputs.pop("""labels""" ) with torch.no_grad(): # compute loss on predict data __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __UpperCAmelCase =generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) return (loss, logits, labels) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: # If PAD token is not defined at least EOS token has to be defined __UpperCAmelCase =self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( """Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be""" f''' padded to `max_length`={max_length}''' ) __UpperCAmelCase =pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __UpperCAmelCase =tensor return padded_tensor
68
0
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap _A : Tuple = """Usage of script: script_name <size_of_canvas:int>""" _A : Dict = [0] * 1_00 + [1] * 10 random.shuffle(choice) def __snake_case ( lowerCAmelCase_ ) -> list[list[bool]]: SCREAMING_SNAKE_CASE__ = [[False for i in range(lowerCAmelCase_ )] for j in range(lowerCAmelCase_ )] return canvas def __snake_case ( lowerCAmelCase_ ) -> None: for i, row in enumerate(lowerCAmelCase_ ): for j, _ in enumerate(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE__ = bool(random.getrandbits(1 ) ) def __snake_case ( lowerCAmelCase_ ) -> list[list[bool]]: SCREAMING_SNAKE_CASE__ = np.array(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(lowerCAmelCase_ ): for c, pt in enumerate(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE__ = __judge_point( lowerCAmelCase_ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) SCREAMING_SNAKE_CASE__ = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. SCREAMING_SNAKE_CASE__ = current_canvas.tolist() return return_canvas def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> bool: SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. SCREAMING_SNAKE_CASE__ = pt if pt: if alive < 2: SCREAMING_SNAKE_CASE__ = False elif alive == 2 or alive == 3: SCREAMING_SNAKE_CASE__ = True elif alive > 3: SCREAMING_SNAKE_CASE__ = False else: if alive == 3: SCREAMING_SNAKE_CASE__ = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) _A : str = int(sys.argv[1]) # main working structure of this module. _A : Optional[int] = create_canvas(canvas_size) seed(c) _A, _A : List[Any] = plt.subplots() fig.show() _A : List[Any] = ListedColormap(["""w""", """k"""]) try: while True: _A : Dict = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
100
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : List[Any] = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str=0 ) -> Any: __UpperCAmelCase =floats_tensor((1, 3, 128, 128) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =np.random.RandomState(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """strength""": 0.75, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _a ( self : Optional[Any] ) -> int: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Union[str, Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Optional[Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # warmup pass to apply optimizations __UpperCAmelCase =pipe(**self.get_dummy_inputs() ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Optional[int]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _a ( self : Dict ) -> int: __UpperCAmelCase =ort.SessionOptions() __UpperCAmelCase =False return options def _a ( self : Dict ) -> Any: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) # using the PNDM scheduler by default __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _a ( self : List[str] ) -> str: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) __UpperCAmelCase =LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
68
0
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __lowercase (unittest.TestCase ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=9_9 , lowerCAmelCase__=3_2 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=3_7 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_6 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=4 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = parent SCREAMING_SNAKE_CASE_ : List[str] = batch_size SCREAMING_SNAKE_CASE_ : Dict = seq_length SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Union[str, Any] = use_attention_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : List[Any] = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : Dict = hidden_size SCREAMING_SNAKE_CASE_ : Any = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE_ : int = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE_ : Any = type_vocab_size SCREAMING_SNAKE_CASE_ : str = type_sequence_label_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_choices def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : str = None if self.use_attention_mask: SCREAMING_SNAKE_CASE_ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Any = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCAmelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = config_and_inputs SCREAMING_SNAKE_CASE_ : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask} return config, inputs_dict def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : Dict = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowercase (__SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" _UpperCAmelCase = True _UpperCAmelCase = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = FlaxRobertaModelTester(self ) @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE_ : List[str] = model_class_name.from_pretrained('roberta-base' , from_pt=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : str = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCAmelCase__ )
101
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors __A = logging.getLogger(__name__) class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[Any] = 'sequence-classification' def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Tuple ) -> Optional[Any]: if type(__SCREAMING_SNAKE_CASE ) == dict: __UpperCAmelCase =Namespace(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =glue_output_modes[hparams.task] __UpperCAmelCase =glue_tasks_num_labels[hparams.task] super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.mode ) def _a ( self : str , **__SCREAMING_SNAKE_CASE : Dict ) -> List[str]: return self.model(**__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ) -> List[Any]: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =outputs[0] __UpperCAmelCase =self.trainer.lr_schedulers[0]["""scheduler"""] __UpperCAmelCase ={"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def _a ( self : Tuple ) -> List[Any]: __UpperCAmelCase =self.hparams __UpperCAmelCase =processors[args.task]() __UpperCAmelCase =processor.get_labels() for mode in ["train", "dev"]: __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) if os.path.exists(__SCREAMING_SNAKE_CASE ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) __UpperCAmelCase =( processor.get_dev_examples(args.data_dir ) if mode == """dev""" else processor.get_train_examples(args.data_dir ) ) __UpperCAmelCase =convert_examples_to_features( __SCREAMING_SNAKE_CASE , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("""Saving features into cached file %s""" , __SCREAMING_SNAKE_CASE ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ) -> DataLoader: __UpperCAmelCase ="""dev""" if mode == """test""" else mode __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.load(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , batch_size=__SCREAMING_SNAKE_CASE , shuffle=__SCREAMING_SNAKE_CASE , ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ) -> str: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =outputs[:2] __UpperCAmelCase =logits.detach().cpu().numpy() __UpperCAmelCase =inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Any ) -> tuple: __UpperCAmelCase =torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item() __UpperCAmelCase =np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =np.argmax(__SCREAMING_SNAKE_CASE , axis=1 ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =np.squeeze(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =np.concatenate([x["""target"""] for x in outputs] , axis=0 ) __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase ={**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} __UpperCAmelCase =dict(results.items() ) __UpperCAmelCase =results return ret, preds_list, out_label_list def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : list ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _a ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[Any]: BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) parser.add_argument( """--max_seq_length""" , default=128 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--task""" , default="""""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The GLUE task to run""" , ) parser.add_argument( """--gpus""" , default=0 , type=__SCREAMING_SNAKE_CASE , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser def lowercase__ ( ) -> str: """simple docstring""" __UpperCAmelCase =argparse.ArgumentParser() add_generic_args(A_ , os.getcwd() ) __UpperCAmelCase =GLUETransformer.add_model_specific_args(A_ , os.getcwd() ) __UpperCAmelCase =parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __UpperCAmelCase =os.path.join( """./results""" , F'''{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}''' , ) os.makedirs(args.output_dir ) __UpperCAmelCase =GLUETransformer(A_ ) __UpperCAmelCase =generic_train(A_ , A_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __UpperCAmelCase =sorted(glob.glob(os.path.join(args.output_dir , """checkpoint-epoch=*.ckpt""" ) , recursive=A_ ) ) __UpperCAmelCase =model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(A_ ) if __name__ == "__main__": main()
68
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class lowercase__ ( unittest.TestCase ): """simple docstring""" @slow def _a ( self ): '''simple docstring''' UpperCamelCase : List[str] = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) UpperCamelCase : Dict = { """input_ids""": tf.convert_to_tensor([[0, 2_6_4_6, 1_0_2_6_9, 8_3, 9_9_9_4_2, 2]] , dtype=tf.intaa ), # "My dog is cute" """attention_mask""": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } UpperCamelCase : Tuple = model(_A )["""last_hidden_state"""] UpperCamelCase : Union[str, Any] = tf.TensorShape((1, 6, 7_6_8) ) self.assertEqual(output.shape , _A ) # compare the actual values for a slice. UpperCamelCase : Any = tf.convert_to_tensor( [ [ [0.0_68_17_62, 0.10_89_44_51, 0.06_77_25_04], [-0.06_42_36_68, 0.02_36_66_15, 0.04_32_93_44], [-0.06_05_72_95, 0.09_97_41_35, -0.00_07_05_84], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
102
def lowercase__ ( A_: int , A_: int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def lowercase__ ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
"""simple docstring""" def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str: if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) _snake_case = str(bin(lowerCAmelCase_ ) ) binary_number += "0" * shift_amount return binary_number def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str: if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) _snake_case = str(bin(lowerCAmelCase_ ) )[2:] if shift_amount >= len(lowerCAmelCase_ ): return "0b0" _snake_case = binary_number[: len(lowerCAmelCase_ ) - shift_amount] return "0b" + shifted_binary_number def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str: if number >= 0: # Get binary representation of positive number _snake_case = '''0''' + str(bin(lowerCAmelCase_ ) ).strip('''-''' )[2:] else: # Get binary (2's complement) representation of negative number _snake_case = len(bin(lowerCAmelCase_ )[3:] ) # Find 2's complement of number _snake_case = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] _snake_case = ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase_ )) + binary_number ) if shift_amount >= len(lowerCAmelCase_ ): return "0b" + binary_number[0] * len(lowerCAmelCase_ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(lowerCAmelCase_ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
103
from __future__ import annotations import bisect def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] < item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_left(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_right(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =0 __UpperCAmelCase =len(A_ ) - 1 while left <= right: __UpperCAmelCase =left + (right - left) // 2 __UpperCAmelCase =sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __UpperCAmelCase =midpoint - 1 else: __UpperCAmelCase =midpoint + 1 return None def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =bisect.bisect_left(A_ , A_ ) if index != len(A_ ) and sorted_collection[index] == item: return index return None def lowercase__ ( A_: list[int] , A_: int , A_: int , A_: int ) -> int | None: """simple docstring""" if right < left: return None __UpperCAmelCase =left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(A_ , A_ , A_ , midpoint - 1 ) else: return binary_search_by_recursion(A_ , A_ , midpoint + 1 , A_ ) if __name__ == "__main__": __A = input("Enter numbers separated by comma:\n").strip() __A = sorted(int(item) for item in user_input.split(",")) __A = int(input("Enter a single number to be found in the list:\n")) __A = binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
68
0
"""simple docstring""" import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) def _lowerCamelCase ( UpperCAmelCase_ : str, UpperCAmelCase_ : Dict, UpperCAmelCase_ : str ) -> List[str]: """simple docstring""" A__ = os.path.abspath(UpperCAmelCase_ ) logger.info(F"""Converting TensorFlow checkpoint from {tf_path}""" ) # Load weights from TF model A__ = tf.train.list_variables(UpperCAmelCase_ ) A__ = [] A__ = [] A__ = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") A__ = full_name.split("/" ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(F"""Skipping non-model layer {full_name}""" ) continue if "optimizer" in full_name: logger.info(F"""Skipping optimization layer {full_name}""" ) continue if name[0] == "model": # ignore initial 'model' A__ = name[1:] # figure out how many levels deep the name is A__ = 0 for _name in name: if _name.startswith("layer_with_weights" ): depth += 1 else: break layer_depth.append(UpperCAmelCase_ ) # read data A__ = tf.train.load_variable(UpperCAmelCase_, UpperCAmelCase_ ) names.append("/".join(UpperCAmelCase_ ) ) arrays.append(UpperCAmelCase_ ) logger.info(F"""Read a total of {len(UpperCAmelCase_ ):,} layers""" ) # Sanity check if len(set(UpperCAmelCase_ ) ) != 1: raise ValueError(F"""Found layer names with different depths (layer depth {list(set(UpperCAmelCase_ ) )})""" ) A__ = list(set(UpperCAmelCase_ ) )[0] if layer_depth != 1: raise ValueError( "The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP" " heads." ) # convert layers logger.info("Converting weights..." ) for full_name, array in zip(UpperCAmelCase_, UpperCAmelCase_ ): A__ = full_name.split("/" ) A__ = model A__ = [] for i, m_name in enumerate(UpperCAmelCase_ ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith("layer_with_weights" ): A__ = int(m_name.split("-" )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(["embeddings", "LayerNorm"] ) A__ = getattr(UpperCAmelCase_, "embeddings" ) A__ = getattr(UpperCAmelCase_, "LayerNorm" ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(["encoder", "layer", str(layer_num - 4 )] ) A__ = getattr(UpperCAmelCase_, "encoder" ) A__ = getattr(UpperCAmelCase_, "layer" ) A__ = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(["pooler", "dense"] ) A__ = getattr(UpperCAmelCase_, "pooler" ) A__ = getattr(UpperCAmelCase_, "dense" ) elif m_name == "embeddings": trace.append("embeddings" ) A__ = getattr(UpperCAmelCase_, "embeddings" ) if layer_num == 0: trace.append("word_embeddings" ) A__ = getattr(UpperCAmelCase_, "word_embeddings" ) elif layer_num == 1: trace.append("position_embeddings" ) A__ = getattr(UpperCAmelCase_, "position_embeddings" ) elif layer_num == 2: trace.append("token_type_embeddings" ) A__ = getattr(UpperCAmelCase_, "token_type_embeddings" ) else: raise ValueError(F"""Unknown embedding layer with name {full_name}""" ) trace.append("weight" ) A__ = getattr(UpperCAmelCase_, "weight" ) elif m_name == "_attention_layer": # self-attention layer trace.extend(["attention", "self"] ) A__ = getattr(UpperCAmelCase_, "attention" ) A__ = getattr(UpperCAmelCase_, "self" ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(["attention", "output", "LayerNorm"] ) A__ = getattr(UpperCAmelCase_, "attention" ) A__ = getattr(UpperCAmelCase_, "output" ) A__ = getattr(UpperCAmelCase_, "LayerNorm" ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(["attention", "output", "dense"] ) A__ = getattr(UpperCAmelCase_, "attention" ) A__ = getattr(UpperCAmelCase_, "output" ) A__ = getattr(UpperCAmelCase_, "dense" ) elif m_name == "_output_dense": # output dense trace.extend(["output", "dense"] ) A__ = getattr(UpperCAmelCase_, "output" ) A__ = getattr(UpperCAmelCase_, "dense" ) elif m_name == "_output_layer_norm": # output dense trace.extend(["output", "LayerNorm"] ) A__ = getattr(UpperCAmelCase_, "output" ) A__ = getattr(UpperCAmelCase_, "LayerNorm" ) elif m_name == "_key_dense": # attention key trace.append("key" ) A__ = getattr(UpperCAmelCase_, "key" ) elif m_name == "_query_dense": # attention query trace.append("query" ) A__ = getattr(UpperCAmelCase_, "query" ) elif m_name == "_value_dense": # attention value trace.append("value" ) A__ = getattr(UpperCAmelCase_, "value" ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(["intermediate", "dense"] ) A__ = getattr(UpperCAmelCase_, "intermediate" ) A__ = getattr(UpperCAmelCase_, "dense" ) elif m_name == "_output_layer_norm": # output layer norm trace.append("output" ) A__ = getattr(UpperCAmelCase_, "output" ) # weights & biases elif m_name in ["bias", "beta"]: trace.append("bias" ) A__ = getattr(UpperCAmelCase_, "bias" ) elif m_name in ["kernel", "gamma"]: trace.append("weight" ) A__ = getattr(UpperCAmelCase_, "weight" ) else: logger.warning(F"""Ignored {m_name}""" ) # for certain layers reshape is necessary A__ = ".".join(UpperCAmelCase_ ) if re.match(r"(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)", UpperCAmelCase_ ) or re.match( r"(\S+)\.attention\.output\.dense\.weight", UpperCAmelCase_ ): A__ = array.reshape(pointer.data.shape ) if "kernel" in full_name: A__ = array.transpose() if pointer.shape == array.shape: A__ = torch.from_numpy(UpperCAmelCase_ ) else: raise ValueError( F"""Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:""" F""" {array.shape}""" ) logger.info(F"""Successfully set variable {full_name} to PyTorch layer {trace}""" ) return model def _lowerCamelCase ( UpperCAmelCase_ : Any, UpperCAmelCase_ : Union[str, Any], UpperCAmelCase_ : Any ) -> List[str]: """simple docstring""" logger.info(F"""Loading model based on config from {config_path}...""" ) A__ = BertConfig.from_json_file(UpperCAmelCase_ ) A__ = BertModel(UpperCAmelCase_ ) # Load weights from checkpoint logger.info(F"""Loading weights from checkpoint {tf_checkpoint_path}...""" ) load_tfa_weights_in_bert(UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ ) # Save pytorch-model logger.info(F"""Saving PyTorch model to {pytorch_dump_path}...""" ) torch.save(model.state_dict(), UpperCAmelCase_ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( """--tf_checkpoint_path""", type=str, required=True, help="""Path to the TensorFlow 2.x checkpoint path.""" ) parser.add_argument( """--bert_config_file""", type=str, required=True, help="""The config json file corresponding to the BERT model. This specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", type=str, required=True, help="""Path to the output PyTorch model (must include filename).""", ) UpperCamelCase = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
104
from typing import List from .keymap import KEYMAP, get_character def lowercase__ ( A_: str ) -> str: """simple docstring""" def decorator(A_: int ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += [key] setattr(A_ , """handle_key""" , A_ ) return func return decorator def lowercase__ ( *A_: List[str] ) -> Optional[int]: """simple docstring""" def decorator(A_: Tuple ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += keys setattr(A_ , """handle_key""" , A_ ) return func return decorator class _A ( UpperCamelCase ): """simple docstring""" def __new__( cls : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> int: __UpperCAmelCase =super().__new__(cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if not hasattr(__SCREAMING_SNAKE_CASE , """key_handler""" ): setattr(__SCREAMING_SNAKE_CASE , """key_handler""" , {} ) setattr(__SCREAMING_SNAKE_CASE , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , """handle_key""" , [] ) for key in handled_keys: __UpperCAmelCase =value return new_cls @staticmethod def _a ( cls : Dict ) -> List[Any]: __UpperCAmelCase =get_character() if char != KEYMAP["undefined"]: __UpperCAmelCase =ord(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =cls.key_handler.get(__SCREAMING_SNAKE_CASE ) if handler: __UpperCAmelCase =char return handler(cls ) else: return None def lowercase__ ( cls: str ) -> int: """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
68
0
from __future__ import annotations def __UpperCAmelCase ( lowerCamelCase_ : tuple[int, int] , lowerCamelCase_ : int ) -> list[tuple[int, int]]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = position SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] SCREAMING_SNAKE_CASE_ : str = [] for position in positions: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(lowerCamelCase_ ) return permissible_positions def __UpperCAmelCase ( lowerCamelCase_ : list[list[int]] ) -> bool: """simple docstring""" return not any(elem == 0 for row in board for elem in row ) def __UpperCAmelCase ( lowerCamelCase_ : list[list[int]] , lowerCamelCase_ : tuple[int, int] , lowerCamelCase_ : int ) -> bool: """simple docstring""" if is_complete(lowerCamelCase_ ): return True for position in get_valid_pos(lowerCamelCase_ , len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = position if board[y][x] == 0: SCREAMING_SNAKE_CASE_ : int = curr + 1 if open_knight_tour_helper(lowerCamelCase_ , lowerCamelCase_ , curr + 1 ): return True SCREAMING_SNAKE_CASE_ : str = 0 return False def __UpperCAmelCase ( lowerCamelCase_ : int ) -> list[list[int]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [[0 for i in range(lowerCamelCase_ )] for j in range(lowerCamelCase_ )] for i in range(lowerCamelCase_ ): for j in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 if open_knight_tour_helper(lowerCamelCase_ , (i, j) , 1 ): return board SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : str = F'Open Kight Tour cannot be performed on a board of size {n}' raise ValueError(lowerCamelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
105
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
68
0
from __future__ import annotations from cmath import sqrt def lowerCamelCase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> tuple[complex, complex]: '''simple docstring''' if a == 0: raise ValueError('Coefficient \'a\' must not be zero.' ) A = b * b - 4 * a * c A = (-b + sqrt(lowerCAmelCase__ )) / (2 * a) A = (-b - sqrt(lowerCAmelCase__ )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def lowerCamelCase_ ( ) -> List[Any]: '''simple docstring''' A , A = quadratic_roots(a=5 , b=6 , c=1 ) print(F'''The solutions are: {solutiona} and {solutiona}''' ) if __name__ == "__main__": main()
106
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _A ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Optional[Any]=99 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : int=5 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : str=37 , __SCREAMING_SNAKE_CASE : Union[str, Any]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : str=512 , __SCREAMING_SNAKE_CASE : Dict=16 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : List[str]=4 , ) -> Optional[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =seq_length __UpperCAmelCase =is_training __UpperCAmelCase =use_attention_mask __UpperCAmelCase =use_token_type_ids __UpperCAmelCase =use_labels __UpperCAmelCase =vocab_size __UpperCAmelCase =hidden_size __UpperCAmelCase =num_hidden_layers __UpperCAmelCase =num_attention_heads __UpperCAmelCase =intermediate_size __UpperCAmelCase =hidden_act __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =max_position_embeddings __UpperCAmelCase =type_vocab_size __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =initializer_range __UpperCAmelCase =num_choices def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase =None if self.use_attention_mask: __UpperCAmelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase =None if self.use_token_type_ids: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase =RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def _a ( self : List[str] ) -> Dict: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase =True __UpperCAmelCase =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] = True lowerCamelCase : Union[str, Any] = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =FlaxRobertaModelTester(self ) @slow def _a ( self : Optional[Any] ) -> List[Any]: for model_class_name in self.all_model_classes: __UpperCAmelCase =model_class_name.from_pretrained("""roberta-base""" , from_pt=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model(np.ones((1, 1) ) ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' _UpperCAmelCase : str = frozenset( [ '''prompt''', '''height''', '''width''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', '''cross_attention_kwargs''', ] ) _UpperCAmelCase : str = frozenset(['''prompt''', '''negative_prompt''']) _UpperCAmelCase : List[str] = frozenset([]) _UpperCAmelCase : Any = frozenset(['''image''']) _UpperCAmelCase : List[str] = frozenset( [ '''image''', '''height''', '''width''', '''guidance_scale''', ] ) _UpperCAmelCase : int = frozenset(['''image''']) _UpperCAmelCase : Union[str, Any] = frozenset( [ '''prompt''', '''image''', '''height''', '''width''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', ] ) _UpperCAmelCase : Tuple = frozenset(['''prompt''', '''image''', '''negative_prompt''']) _UpperCAmelCase : Optional[int] = frozenset( [ # Text guided image variation with an image mask '''prompt''', '''image''', '''mask_image''', '''height''', '''width''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', ] ) _UpperCAmelCase : Dict = frozenset(['''prompt''', '''image''', '''mask_image''', '''negative_prompt''']) _UpperCAmelCase : Union[str, Any] = frozenset( [ # image variation with an image mask '''image''', '''mask_image''', '''height''', '''width''', '''guidance_scale''', ] ) _UpperCAmelCase : str = frozenset(['''image''', '''mask_image''']) _UpperCAmelCase : Optional[Any] = frozenset( [ '''example_image''', '''image''', '''mask_image''', '''height''', '''width''', '''guidance_scale''', ] ) _UpperCAmelCase : Tuple = frozenset(['''example_image''', '''image''', '''mask_image''']) _UpperCAmelCase : int = frozenset(['''class_labels''']) _UpperCAmelCase : Dict = frozenset(['''class_labels''']) _UpperCAmelCase : Optional[int] = frozenset(['''batch_size''']) _UpperCAmelCase : str = frozenset([]) _UpperCAmelCase : Optional[Any] = frozenset(['''batch_size''']) _UpperCAmelCase : int = frozenset([]) _UpperCAmelCase : Union[str, Any] = frozenset( [ '''prompt''', '''audio_length_in_s''', '''guidance_scale''', '''negative_prompt''', '''prompt_embeds''', '''negative_prompt_embeds''', '''cross_attention_kwargs''', ] ) _UpperCAmelCase : Any = frozenset(['''prompt''', '''negative_prompt''']) _UpperCAmelCase : Union[str, Any] = frozenset(['''input_tokens''']) _UpperCAmelCase : str = frozenset(['''input_tokens'''])
107
from __future__ import annotations def lowercase__ ( A_: list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(A_ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
68
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a: List[Any] = { '''configuration_trajectory_transformer''': [ '''TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrajectoryTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a: Optional[Any] = [ '''TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrajectoryTransformerModel''', '''TrajectoryTransformerPreTrainedModel''', '''load_tf_weights_in_trajectory_transformer''', ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys __a: Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
108
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowercase__ ( A_: int , A_: int , A_: int , A_: int , A_: int , A_: int ) -> np.ndarray: """simple docstring""" if (ksize % 2) == 0: __UpperCAmelCase =ksize + 1 __UpperCAmelCase =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(A_ ): for x in range(A_ ): # distance from center __UpperCAmelCase =x - ksize // 2 __UpperCAmelCase =y - ksize // 2 # degree to radiant __UpperCAmelCase =theta / 180 * np.pi __UpperCAmelCase =np.cos(_theta ) __UpperCAmelCase =np.sin(_theta ) # get kernel x __UpperCAmelCase =cos_theta * px + sin_theta * py # get kernel y __UpperCAmelCase =-sin_theta * px + cos_theta * py # fill kernel __UpperCAmelCase =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __A = imread("../image_data/lena.jpg") # turn image in gray scale value __A = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __A = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 1_20, 1_50]: __A = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __A = out / out.max() * 2_55 __A = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
68
0
'''simple docstring''' import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.bert.modeling_flax_bert import ( FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, ) class __a ( unittest.TestCase ): def __init__( self : List[Any] ,lowerCamelCase : List[str] ,lowerCamelCase : Optional[Any]=13 ,lowerCamelCase : List[str]=7 ,lowerCamelCase : Optional[Any]=True ,lowerCamelCase : List[str]=True ,lowerCamelCase : int=True ,lowerCamelCase : Any=True ,lowerCamelCase : List[str]=99 ,lowerCamelCase : List[str]=32 ,lowerCamelCase : str=5 ,lowerCamelCase : int=4 ,lowerCamelCase : Any=37 ,lowerCamelCase : List[Any]="gelu" ,lowerCamelCase : List[Any]=0.1 ,lowerCamelCase : str=0.1 ,lowerCamelCase : str=512 ,lowerCamelCase : Union[str, Any]=16 ,lowerCamelCase : List[str]=2 ,lowerCamelCase : Tuple=0.02 ,lowerCamelCase : int=4 ,): '''simple docstring''' __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_attention_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_choices def UpperCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_attention_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) __SCREAMING_SNAKE_CASE = BertConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=lowerCamelCase ,initializer_range=self.initializer_range ,) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase__ ( self : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __a ( _snake_case, unittest.TestCase ): __UpperCamelCase : Dict = True __UpperCamelCase : List[Any] = ( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase__ ( self : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE = FlaxBertModelTester(self ) @slow def UpperCAmelCase__ ( self : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained("""bert-base-cased""" ) __SCREAMING_SNAKE_CASE = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase )
109
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : """simple docstring""" def __init__( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , __SCREAMING_SNAKE_CASE : List[str]=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=[1, 2, 1] , __SCREAMING_SNAKE_CASE : List[Any]=[2, 2, 4] , __SCREAMING_SNAKE_CASE : str=2 , __SCREAMING_SNAKE_CASE : Any=2.0 , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Dict=0.0 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : Any="gelu" , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : List[Any]=0.02 , __SCREAMING_SNAKE_CASE : Tuple=1e-5 , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Any=10 , __SCREAMING_SNAKE_CASE : Dict=8 , ) -> List[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =image_size __UpperCAmelCase =patch_size __UpperCAmelCase =num_channels __UpperCAmelCase =embed_dim __UpperCAmelCase =depths __UpperCAmelCase =num_heads __UpperCAmelCase =window_size __UpperCAmelCase =mlp_ratio __UpperCAmelCase =qkv_bias __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =drop_path_rate __UpperCAmelCase =hidden_act __UpperCAmelCase =use_absolute_embeddings __UpperCAmelCase =patch_norm __UpperCAmelCase =layer_norm_eps __UpperCAmelCase =initializer_range __UpperCAmelCase =is_training __UpperCAmelCase =scope __UpperCAmelCase =use_labels __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =encoder_stride def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase =None if self.use_labels: __UpperCAmelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase =self.get_config() return config, pixel_values, labels def _a ( self : List[Any] ) -> Optional[Any]: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: __UpperCAmelCase =SwinvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase =int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> Tuple: __UpperCAmelCase =SwinvaForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase =1 __UpperCAmelCase =SwinvaForMaskedImageModeling(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: __UpperCAmelCase =self.type_sequence_label_size __UpperCAmelCase =SwinvaForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self : List[str] ) -> Tuple: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[int] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCamelCase : Tuple = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowerCamelCase : Dict = False lowerCamelCase : Tuple = False lowerCamelCase : List[str] = False lowerCamelCase : Tuple = False def _a ( self : str ) -> str: __UpperCAmelCase =SwinvaModelTester(self ) __UpperCAmelCase =ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , embed_dim=37 ) def _a ( self : List[Any] ) -> Optional[int]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self : str ) -> str: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def _a ( self : Tuple ) -> Tuple: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def _a ( self : Optional[Any] ) -> int: pass def _a ( self : Tuple ) -> int: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def _a ( self : str ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase =[*signature.parameters.keys()] __UpperCAmelCase =["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =True for model_class in self.all_model_classes: __UpperCAmelCase =True __UpperCAmelCase =False __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions __UpperCAmelCase =len(self.model_tester.depths ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase =True __UpperCAmelCase =config.window_size**2 __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase =len(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __UpperCAmelCase =True __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase =self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase =2 self.assertEqual(out_len + added_hidden_states , len(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> int: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.hidden_states __UpperCAmelCase =getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # Swinv2 has a different seq_length __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase =outputs.reshaped_hidden_states self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =reshaped_hidden_states[0].shape __UpperCAmelCase =( reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self : str ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =3 __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Dict: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def _a ( self : int ) -> Dict: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase =SwinvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def _a ( self : Dict ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =_config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __UpperCAmelCase =model_class(config=__SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _A ( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self : Tuple ) -> Dict: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def _a ( self : int ) -> Optional[int]: __UpperCAmelCase =SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.default_image_processor __UpperCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase =image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE ) # verify the logits __UpperCAmelCase =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
68
0
"""simple docstring""" from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata UpperCamelCase__ = '' if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'): class a ( tr.AbstractTransform ): def __init__( self , UpperCamelCase_ = " " ): UpperCAmelCase__ : Union[str, Any] = sentence_delimiter def __snake_case ( self , UpperCamelCase_ ): return list(UpperCamelCase_ ) def __snake_case ( self , UpperCamelCase_ ): UpperCAmelCase__ : Tuple = [] for sent_idx, sentence in enumerate(UpperCamelCase_ ): chars.extend(self.process_string(UpperCamelCase_ ) ) if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(UpperCamelCase_ ) - 1: chars.append(self.sentence_delimiter ) return chars UpperCamelCase__ = tr.Compose( [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)] ) else: UpperCamelCase__ = tr.Compose( [ tr.RemoveMultipleSpaces(), tr.Strip(), tr.ReduceToSingleSentence(SENTENCE_DELIMITER), tr.ReduceToListOfListOfChars(), ] ) UpperCamelCase__ = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' UpperCamelCase__ = '\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n' UpperCamelCase__ = '\nComputes CER score of transcribed segments against references.\nArgs:\n references: list of references for each speech input.\n predictions: list of transcribtions to score.\n concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n (float): the character error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> cer = datasets.load_metric("cer")\n >>> cer_score = cer.compute(predictions=predictions, references=references)\n >>> print(cer_score)\n 0.34146341463414637\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a ( datasets.Metric ): def __snake_case ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/jitsi/jiwer/'] , reference_urls=[ 'https://en.wikipedia.org/wiki/Word_error_rate', 'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates', ] , ) def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=False ): if concatenate_texts: return jiwer.compute_measures( UpperCamelCase_ , UpperCamelCase_ , truth_transform=UpperCamelCase_ , hypothesis_transform=UpperCamelCase_ , )["wer"] UpperCAmelCase__ : Union[str, Any] = 0 UpperCAmelCase__ : Tuple = 0 for prediction, reference in zip(UpperCamelCase_ , UpperCamelCase_ ): UpperCAmelCase__ : Union[str, Any] = jiwer.compute_measures( UpperCamelCase_ , UpperCamelCase_ , truth_transform=UpperCamelCase_ , hypothesis_transform=UpperCamelCase_ , ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
110
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A = logging.get_logger(__name__) __A = {"vocab_file": "spiece.model"} __A = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } __A = { "AI-Sweden/gpt-sw3-126m": 20_48, "AI-Sweden/gpt-sw3-350m": 20_48, "AI-Sweden/gpt-sw3-1.6b": 20_48, "AI-Sweden/gpt-sw3-6.7b": 20_48, "AI-Sweden/gpt-sw3-20b": 20_48, } class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : int = VOCAB_FILES_NAMES lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : List[str]=False , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Optional[Dict[str, Any]] = None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> None: __UpperCAmelCase ={} if sp_model_kwargs is None else sp_model_kwargs __UpperCAmelCase =kwargs.get("""name_or_path""" ) if name_or_path is None: logger.warning( """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,""" """ you are testing the model, this can safely be ignored""" ) __UpperCAmelCase ="""None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __UpperCAmelCase ="""<|endoftext|>""" if eos_token is None else eos_token __UpperCAmelCase ="""<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __UpperCAmelCase =unk_token if pad_token is None else pad_token __UpperCAmelCase =eos_token if bos_token is None else bos_token else: __UpperCAmelCase ="""<pad>""" if pad_token is None else pad_token __UpperCAmelCase ="""<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=__SCREAMING_SNAKE_CASE , remove_space=__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) __UpperCAmelCase =do_lower_case __UpperCAmelCase =remove_space __UpperCAmelCase =keep_accents __UpperCAmelCase =vocab_file __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) # Used for whitespace normalization in input texts # fmt : off __UpperCAmelCase ={""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __UpperCAmelCase =re.compile( f'''[{"".join(map(__SCREAMING_SNAKE_CASE , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self : Any ) -> str: __UpperCAmelCase =self.__dict__.copy() __UpperCAmelCase =None return state def __setstate__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: __UpperCAmelCase =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __UpperCAmelCase ={} __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def _a ( self : Union[str, Any] ) -> int: return len(self.sp_model ) def _a ( self : Dict , __SCREAMING_SNAKE_CASE : str ) -> str: __UpperCAmelCase =self.non_printing_characters_re.sub("""""" , __SCREAMING_SNAKE_CASE ) # Normalize whitespaces __UpperCAmelCase ="""""".join([char if char not in self.whitespaces else """ """ for char in text] ) # NFC Unicode normalization __UpperCAmelCase =unicodedata.normalize("""NFC""" , __SCREAMING_SNAKE_CASE ) return text def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str ) -> int: return self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : int ) -> str: return self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) @staticmethod def _a ( __SCREAMING_SNAKE_CASE : str ) -> str: return out_string def _a ( self : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> str: __UpperCAmelCase =[] __UpperCAmelCase ="""""" __UpperCAmelCase =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token __UpperCAmelCase =True __UpperCAmelCase =[] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =False out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string def _a ( self : Any ) -> Dict[str, int]: __UpperCAmelCase ={self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __UpperCAmelCase =os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , """wb""" ) as fi: __UpperCAmelCase =self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, List[str]] , __SCREAMING_SNAKE_CASE : Union[str, bool] = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) else: __UpperCAmelCase =[self.preprocess_text(__SCREAMING_SNAKE_CASE ) for t in text] __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) if return_tensors is True or return_tensors == "pt": __UpperCAmelCase =torch.tensor(__SCREAMING_SNAKE_CASE ) return token_ids def _a ( self : str , __SCREAMING_SNAKE_CASE : Union[int, List[int]] ) -> str: return self.sp_model.decode(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : "Conversation" ) -> List[int]: __UpperCAmelCase =[f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __UpperCAmelCase =( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(__SCREAMING_SNAKE_CASE ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=__SCREAMING_SNAKE_CASE )
68
0
"""simple docstring""" from __future__ import annotations import os from typing import Any import requests UpperCamelCase_ : Union[str, Any] = '''https://api.github.com''' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user UpperCamelCase_ : Union[str, Any] = BASE_URL + '''/user''' # https://github.com/settings/tokens UpperCamelCase_ : Optional[Any] = os.environ.get('''USER_TOKEN''', '''''') def A_ (__a ): '''simple docstring''' A_ = { "Authorization": f'token {auth_token}', "Accept": "application/vnd.github.v3+json", } return requests.get(A_ , headers=A_ ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(F"""{key}: {value}""") else: raise ValueError('''\'USER_TOKEN\' field cannot be empty.''')
115
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __A = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : Union[str, None] = None , __SCREAMING_SNAKE_CASE : Union[List[str], None] = None , __SCREAMING_SNAKE_CASE : Union[str, List[str], None] = None , __SCREAMING_SNAKE_CASE : bool = True , ) -> List[str]: __UpperCAmelCase =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )] if identifier is not None: __UpperCAmelCase =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n_ in n_identifier: __UpperCAmelCase =[file for file in files if n_ not in file] else: __UpperCAmelCase =[file for file in files if n_identifier not in file] __UpperCAmelCase =ignore_files or [] ignore_files.append("""__init__.py""" ) __UpperCAmelCase =[file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , __SCREAMING_SNAKE_CASE ) if only_modules: __UpperCAmelCase =file.split(""".""" )[0] try: __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: __UpperCAmelCase =doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _a ( self : Optional[Any] ) -> List[str]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""modeling""" __UpperCAmelCase =[ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""tokenization""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] ) -> Optional[Any]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""configuration""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : List[Any] ) -> Tuple: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase =["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase =Path("""docs/source""" ) __UpperCAmelCase =["""favicon.ico"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
68
0
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __snake_case :Optional[int] =logging.get_logger(__name__) __snake_case :Tuple =[ ['attention', 'attn'], ['encoder_attention', 'encoder_attn'], ['q_lin', 'q_proj'], ['k_lin', 'k_proj'], ['v_lin', 'v_proj'], ['out_lin', 'out_proj'], ['norm_embeddings', 'layernorm_embedding'], ['position_embeddings', 'embed_positions'], ['embeddings', 'embed_tokens'], ['ffn.lin', 'fc'], ] def lowerCamelCase_ ( lowerCAmelCase__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: A = k.replace(A_ , A_ ) if k.startswith('encoder' ): A = k.replace('.attn' , '.self_attn' ) A = k.replace('norm1' , 'self_attn_layer_norm' ) A = k.replace('norm2' , 'final_layer_norm' ) elif k.startswith('decoder' ): A = k.replace('norm1' , 'self_attn_layer_norm' ) A = k.replace('norm2' , 'encoder_attn_layer_norm' ) A = k.replace('norm3' , 'final_layer_norm' ) return k def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> str: '''simple docstring''' A = [ 'model.encoder.layernorm_embedding.weight', 'model.encoder.layernorm_embedding.bias', 'model.decoder.layernorm_embedding.weight', 'model.decoder.layernorm_embedding.bias', ] for k in keys: A = sd.pop(A_ ) A = k.replace('layernorm_embedding' , 'layer_norm' ) assert new_k not in sd A = v __snake_case :List[str] =['START'] @torch.no_grad() def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> Optional[int]: '''simple docstring''' A = torch.load(A_ , map_location='cpu' ) A = model['model'] A = BlenderbotConfig.from_json_file(A_ ) A = BlenderbotForConditionalGeneration(A_ ) A = m.model.state_dict().keys() A = [] A = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue A = rename_state_dict_key(A_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: A = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(A_ ) m.model.load_state_dict(A_ , strict=A_ ) m.half() m.save_pretrained(A_ ) if __name__ == "__main__": __snake_case :int =argparse.ArgumentParser() # Required parameters parser.add_argument('--src_path', type=str, help='like blenderbot-model.bin') parser.add_argument('--save_dir', default='hf_blenderbot', type=str, help='Where to save converted model.') parser.add_argument( '--hf_config_json', default='blenderbot-3b-config.json', type=str, help='Path to config to use' ) __snake_case :List[Any] =parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
106
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __A = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def lowercase__ ( A_: int , A_: Optional[Any] , A_: List[str]=None ) -> List[str]: """simple docstring""" if rng is None: __UpperCAmelCase =random.Random() __UpperCAmelCase =1 for dim in shape: total_dims *= dim __UpperCAmelCase =[] for _ in range(A_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __UpperCAmelCase =np.array(A_ , dtype=jnp.intaa ).reshape(A_ ) return output def lowercase__ ( A_: List[str] , A_: List[str]=None ) -> Any: """simple docstring""" __UpperCAmelCase =ids_tensor(A_ , vocab_size=2 , rng=A_ ) # make sure that at least one token is attended to for each batch __UpperCAmelCase =1 return attn_mask @require_flax class _A : """simple docstring""" lowerCamelCase : Optional[Any] = None lowerCamelCase : int = () def _a ( self : str ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __UpperCAmelCase =2 __UpperCAmelCase =inputs["""input_ids"""].shape[-1] // 2 __UpperCAmelCase =inputs["""input_ids"""][:max_batch_size, :sequence_length] __UpperCAmelCase =jnp.ones_like(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __UpperCAmelCase =input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __UpperCAmelCase =config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _a ( self : Union[str, Any] ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =0 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model_class.__name__[4:] # Skip the "Flax" at the beginning __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =pt_model_class(__SCREAMING_SNAKE_CASE ).eval() __UpperCAmelCase =load_flax_weights_in_pytorch_model(__SCREAMING_SNAKE_CASE , flax_model.params ) __UpperCAmelCase =flax_model.generate(__SCREAMING_SNAKE_CASE ).sequences __UpperCAmelCase =pt_model.generate(torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __UpperCAmelCase =flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[Any] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _a ( self : Union[str, Any] ) -> List[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length __UpperCAmelCase =0.8 __UpperCAmelCase =10 __UpperCAmelCase =0.3 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[str] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =2 __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : int ) -> Any: __UpperCAmelCase =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) __UpperCAmelCase =FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) __UpperCAmelCase ="""Hello world""" __UpperCAmelCase =tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """do_samples""" ): model.generate(__SCREAMING_SNAKE_CASE , do_samples=__SCREAMING_SNAKE_CASE ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """foo""" ): __UpperCAmelCase ={"""foo""": """bar"""} model.generate(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
68
0
"""simple docstring""" import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowerCAmelCase_ = 16 lowerCAmelCase_ = 32 def __UpperCAmelCase ( __lowerCamelCase ) -> str: return int(x / 2**20 ) class __A : '''simple docstring''' def __enter__( self : Union[str, Any] ) -> List[str]: """simple docstring""" gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero lowercase__ : List[str] = torch.cuda.memory_allocated() return self def __exit__( self : List[Any] ,*_snake_case : str ) -> Tuple: """simple docstring""" gc.collect() torch.cuda.empty_cache() lowercase__ : int = torch.cuda.memory_allocated() lowercase__ : Any = torch.cuda.max_memory_allocated() lowercase__ : List[str] = bamb(self.end - self.begin ) lowercase__ : List[Any] = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase = 16 , __lowerCamelCase = "bert-base-cased" , __lowerCamelCase = 3_20 , __lowerCamelCase = 1_60 , ) -> Dict: lowercase__ : List[str] = AutoTokenizer.from_pretrained(A_ ) lowercase__ : int = load_dataset( '''glue''' , '''mrpc''' , split={'''train''': f"""train[:{n_train}]""", '''validation''': f"""validation[:{n_val}]"""} ) def tokenize_function(__lowerCamelCase ): # max_length=None => use the model max length (it's actually the default) lowercase__ : List[str] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=A_ , max_length=A_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowercase__ : Dict = datasets.map( A_ , batched=A_ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=A_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowercase__ : Any = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__lowerCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(A_ , padding='''max_length''' , max_length=1_28 , return_tensors='''pt''' ) return tokenizer.pad(A_ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. lowercase__ : Optional[int] = DataLoader( tokenized_datasets['''train'''] , shuffle=A_ , collate_fn=A_ , batch_size=A_ ) lowercase__ : Optional[Any] = DataLoader( tokenized_datasets['''validation'''] , shuffle=A_ , collate_fn=A_ , batch_size=A_ ) return train_dataloader, eval_dataloader def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: lowercase__ : int = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowercase__ : Optional[Any] = config['''lr'''] lowercase__ : Optional[int] = int(config['''num_epochs'''] ) lowercase__ : List[Any] = int(config['''seed'''] ) lowercase__ : List[Any] = int(config['''batch_size'''] ) lowercase__ : List[str] = args.model_name_or_path set_seed(A_ ) lowercase__ , lowercase__ : int = get_dataloaders(A_ , A_ , A_ , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowercase__ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(A_ , return_dict=A_ ) # Instantiate optimizer lowercase__ : Optional[int] = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowercase__ : Optional[int] = optimizer_cls(params=model.parameters() , lr=A_ ) if accelerator.state.deepspeed_plugin is not None: lowercase__ : Any = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: lowercase__ : Optional[Any] = 1 lowercase__ : Dict = (len(A_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowercase__ : Optional[Any] = get_linear_schedule_with_warmup( optimizer=A_ , num_warmup_steps=0 , num_training_steps=A_ , ) else: lowercase__ : Tuple = DummyScheduler(A_ , total_num_steps=A_ , warmup_num_steps=0 ) # 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. lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ : int = accelerator.prepare( A_ , A_ , A_ , A_ , A_ ) # We need to keep track of how many total steps we have iterated over lowercase__ : Optional[Any] = 0 # We also need to keep track of the stating epoch so files are named properly lowercase__ : Dict = 0 # Now we train the model lowercase__ : Dict = {} for epoch in range(A_ , A_ ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(A_ ): lowercase__ : Optional[int] = model(**A_ ) lowercase__ : List[Any] = outputs.loss lowercase__ : Dict = loss / gradient_accumulation_steps accelerator.backward(A_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print('''Memory before entering the train : {}'''.format(bamb(tracemalloc.begin ) ) ) accelerator.print('''Memory consumed at the end of the train (end-begin): {}'''.format(tracemalloc.used ) ) accelerator.print('''Peak Memory consumed during the train (max-begin): {}'''.format(tracemalloc.peaked ) ) accelerator.print( '''Total Peak Memory consumed during the train (max): {}'''.format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) lowercase__ : str = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[f"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , '''peak_memory_utilization.json''' ) , '''w''' ) as f: json.dump(A_ , A_ ) def __UpperCAmelCase ( ) -> Any: lowercase__ : List[str] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=A_ , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=A_ , ) parser.add_argument( '''--output_dir''' , type=A_ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--peak_memory_upper_bound''' , type=A_ , default=A_ , help='''The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.''' , ) parser.add_argument( '''--n_train''' , type=A_ , default=3_20 , help='''Number of training examples to use.''' , ) parser.add_argument( '''--n_val''' , type=A_ , default=1_60 , help='''Number of validation examples to use.''' , ) parser.add_argument( '''--num_epochs''' , type=A_ , default=1 , help='''Number of train epochs.''' , ) lowercase__ : Union[str, Any] = parser.parse_args() lowercase__ : List[Any] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(A_ , A_ ) if __name__ == "__main__": main()
560
from __future__ import annotations from collections.abc import Iterator class _A : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : int ) -> None: __UpperCAmelCase =value __UpperCAmelCase =None __UpperCAmelCase =None class _A : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Node ) -> None: __UpperCAmelCase =tree def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : int ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Optional[int] = logging.get_logger(__name__) a__ : Optional[Any] = { 'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ='vit_mae' def __init__( self : str , a__ : List[Any]=768 , a__ : Dict=12 , a__ : Union[str, Any]=12 , a__ : int=3072 , a__ : List[str]="gelu" , a__ : Union[str, Any]=0.0 , a__ : Dict=0.0 , a__ : Union[str, Any]=0.02 , a__ : List[str]=1e-1_2 , a__ : Any=224 , a__ : str=16 , a__ : Tuple=3 , a__ : str=True , a__ : List[str]=16 , a__ : Union[str, Any]=512 , a__ : Dict=8 , a__ : Dict=2048 , a__ : Optional[Any]=0.75 , a__ : Any=False , **a__ : Optional[Any] , ): super().__init__(**__SCREAMING_SNAKE_CASE ) UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = qkv_bias UpperCAmelCase = decoder_num_attention_heads UpperCAmelCase = decoder_hidden_size UpperCAmelCase = decoder_num_hidden_layers UpperCAmelCase = decoder_intermediate_size UpperCAmelCase = mask_ratio UpperCAmelCase = norm_pix_loss
51
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def lowercase__ ( A_: Union[str, Any] ) -> List[Any]: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=A_ , AssumeRolePolicyDocument=json.dumps(A_ , indent=2 ) ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=A_ , PolicyName=F'''{role_name}_policy_permission''' , PolicyDocument=json.dumps(A_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F'''role {role_name} already exists. Using existing one''' ) def lowercase__ ( A_: Dict ) -> Any: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) return iam_client.get_role(RoleName=A_ )["Role"]["Arn"] def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase =_ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , A_ , ) __UpperCAmelCase =None if credentials_configuration == 0: __UpperCAmelCase =_ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) __UpperCAmelCase =aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __UpperCAmelCase =_ask_field("""AWS Access Key ID: """ ) __UpperCAmelCase =aws_access_key_id __UpperCAmelCase =_ask_field("""AWS Secret Access Key: """ ) __UpperCAmelCase =aws_secret_access_key __UpperCAmelCase =_ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) __UpperCAmelCase =aws_region __UpperCAmelCase =_ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , A_ , ) if role_management == 0: __UpperCAmelCase =_ask_field("""Enter your IAM role name: """ ) else: __UpperCAmelCase ="""accelerate_sagemaker_execution_role""" print(F'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(A_ ) __UpperCAmelCase =_ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_custom_docker_image: __UpperCAmelCase =_ask_field("""Enter your Docker image: """ , lambda A_ : str(A_ ).lower() ) __UpperCAmelCase =_ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_inputs_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_metrics_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) __UpperCAmelCase ={} __UpperCAmelCase =_ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_dynamo: __UpperCAmelCase ="""dynamo_""" __UpperCAmelCase =_ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __UpperCAmelCase =_ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_custom_options: __UpperCAmelCase =_ask_options( """Which mode do you want to use?""" , A_ , lambda A_ : TORCH_DYNAMO_MODES[int(A_ )] , default="""default""" , ) __UpperCAmelCase =_ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =_ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase ="""Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __UpperCAmelCase =_ask_options( A_ , A_ , lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __UpperCAmelCase =_ask_field(A_ , lambda A_ : str(A_ ).lower() , default="""ml.p3.2xlarge""" ) __UpperCAmelCase =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __UpperCAmelCase =_ask_field( """How many machines do you want use? [1]: """ , A_ , default=1 , ) __UpperCAmelCase =_ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=A_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=A_ , use_cpu=A_ , dynamo_config=A_ , eca_instance_type=A_ , profile=A_ , region=A_ , iam_role_name=A_ , mixed_precision=A_ , num_machines=A_ , sagemaker_inputs_file=A_ , sagemaker_metrics_file=A_ , )
68
0
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __magic_name__ = re.compile(r'''\s+''') def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return {"hash": hashlib.mda(re.sub(A_ , "" , example["content"] ).encode("utf-8" ) ).hexdigest()} def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = [len(A_ ) for line in example["content"].splitlines()] return {"line_mean": np.mean(A_ ), "line_max": max(A_ )} def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = np.mean([c.isalnum() for c in example["content"]] ) return {"alpha_frac": alpha_frac} def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example["hash"] ) return True else: return False def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=5 ): """simple docstring""" _UpperCAmelCase = ["auto-generated", "autogenerated", "automatically generated"] _UpperCAmelCase = example["content"].splitlines() for _, line in zip(range(A_ ) , A_ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=5 , UpperCamelCase__=0.05 ): """simple docstring""" _UpperCAmelCase = ["unit tests", "test file", "configuration file"] _UpperCAmelCase = example["content"].splitlines() _UpperCAmelCase = 0 _UpperCAmelCase = 0 # first test for _, line in zip(range(A_ ) , A_ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _UpperCAmelCase = example["content"].count("\n" ) _UpperCAmelCase = int(coeff * nlines ) for line in lines: count_config += line.lower().count("config" ) count_test += line.lower().count("test" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = ["def ", "class ", "for ", "while "] _UpperCAmelCase = example["content"].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=4 ): """simple docstring""" _UpperCAmelCase = example["content"].splitlines() _UpperCAmelCase = 0 for line in lines: counter += line.lower().count("=" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = tokenizer(example["content"] , truncation=A_ )["input_ids"] _UpperCAmelCase = len(example["content"] ) / len(A_ ) return {"ratio": ratio} def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = {} results.update(get_hash(A_ ) ) results.update(line_stats(A_ ) ) results.update(alpha_stats(A_ ) ) results.update(char_token_ratio(A_ ) ) results.update(is_autogenerated(A_ ) ) results.update(is_config_or_test(A_ ) ) results.update(has_no_keywords(A_ ) ) results.update(has_few_assignments(A_ ) ) return results def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if not check_uniques(A_ , A_ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" with open(A_ , "rb" ) as f_in: with gzip.open(str(A_ ) + ".gz" , "wb" , compresslevel=6 ) as f_out: shutil.copyfileobj(A_ , A_ ) os.unlink(A_ ) # Settings __magic_name__ = HfArgumentParser(PreprocessingArguments) __magic_name__ = parser.parse_args() if args.num_workers is None: __magic_name__ = multiprocessing.cpu_count() __magic_name__ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __magic_name__ = time.time() __magic_name__ = load_dataset(args.dataset_name, split='''train''') print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing __magic_name__ = time.time() __magic_name__ = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes __magic_name__ = set(ds.unique('''hash''')) __magic_name__ = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics __magic_name__ = time.time() __magic_name__ = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __magic_name__ = time.time() __magic_name__ , __magic_name__ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file __magic_name__ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) __magic_name__ = output_dir / '''data''' data_dir.mkdir(exist_ok=True) __magic_name__ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __magic_name__ = str(data_dir / f'''file-{file_number+1:012}.json''') __magic_name__ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
657
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Tuple = 'ctrl' lowerCamelCase : Any = ['past_key_values'] lowerCamelCase : Optional[int] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=246534 , __SCREAMING_SNAKE_CASE : int=256 , __SCREAMING_SNAKE_CASE : Optional[Any]=1280 , __SCREAMING_SNAKE_CASE : Optional[Any]=8192 , __SCREAMING_SNAKE_CASE : int=48 , __SCREAMING_SNAKE_CASE : Union[str, Any]=16 , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : List[Any]=1e-6 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : Union[str, Any]=True , **__SCREAMING_SNAKE_CASE : int , ) -> Any: __UpperCAmelCase =vocab_size __UpperCAmelCase =n_positions __UpperCAmelCase =n_embd __UpperCAmelCase =n_layer __UpperCAmelCase =n_head __UpperCAmelCase =dff __UpperCAmelCase =resid_pdrop __UpperCAmelCase =embd_pdrop __UpperCAmelCase =layer_norm_epsilon __UpperCAmelCase =initializer_range __UpperCAmelCase =use_cache super().__init__(**__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = 'roberta-prelayernorm' def __init__( self : int , __lowercase : Optional[Any]=5_02_65 , __lowercase : Optional[int]=7_68 , __lowercase : Any=12 , __lowercase : List[str]=12 , __lowercase : Optional[Any]=30_72 , __lowercase : List[Any]="gelu" , __lowercase : List[str]=0.1 , __lowercase : Optional[Any]=0.1 , __lowercase : Tuple=5_12 , __lowercase : Any=2 , __lowercase : Dict=0.02 , __lowercase : List[Any]=1e-12 , __lowercase : Optional[int]=1 , __lowercase : Union[str, Any]=0 , __lowercase : str=2 , __lowercase : Union[str, Any]="absolute" , __lowercase : Optional[int]=True , __lowercase : Tuple=None , **__lowercase : str , ) -> Any: super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE__ : int =vocab_size SCREAMING_SNAKE_CASE__ : Tuple =hidden_size SCREAMING_SNAKE_CASE__ : str =num_hidden_layers SCREAMING_SNAKE_CASE__ : List[Any] =num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] =hidden_act SCREAMING_SNAKE_CASE__ : str =intermediate_size SCREAMING_SNAKE_CASE__ : Any =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : str =max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] =type_vocab_size SCREAMING_SNAKE_CASE__ : List[Any] =initializer_range SCREAMING_SNAKE_CASE__ : List[Any] =layer_norm_eps SCREAMING_SNAKE_CASE__ : str =position_embedding_type SCREAMING_SNAKE_CASE__ : Optional[int] =use_cache SCREAMING_SNAKE_CASE__ : int =classifier_dropout class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @property def __magic_name__ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Tuple ={0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE__ : Tuple ={0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
296
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = [ ["attention", "attn"], ["encoder_attention", "encoder_attn"], ["q_lin", "q_proj"], ["k_lin", "k_proj"], ["v_lin", "v_proj"], ["out_lin", "out_proj"], ["norm_embeddings", "layernorm_embedding"], ["position_embeddings", "embed_positions"], ["embeddings", "embed_tokens"], ["ffn.lin", "fc"], ] def lowercase__ ( A_: Optional[Any] ) -> Union[str, Any]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __UpperCAmelCase =k.replace(A_ , A_ ) if k.startswith("""encoder""" ): __UpperCAmelCase =k.replace(""".attn""" , """.self_attn""" ) __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """encoder_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm3""" , """final_layer_norm""" ) return k def lowercase__ ( A_: Tuple ) -> str: """simple docstring""" __UpperCAmelCase =[ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: __UpperCAmelCase =sd.pop(A_ ) __UpperCAmelCase =k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd __UpperCAmelCase =v __A = ["START"] @torch.no_grad() def lowercase__ ( A_: List[Any] , A_: str , A_: int ) -> Optional[int]: """simple docstring""" __UpperCAmelCase =torch.load(A_ , map_location="""cpu""" ) __UpperCAmelCase =model["""model"""] __UpperCAmelCase =BlenderbotConfig.from_json_file(A_ ) __UpperCAmelCase =BlenderbotForConditionalGeneration(A_ ) __UpperCAmelCase =m.model.state_dict().keys() __UpperCAmelCase =[] __UpperCAmelCase ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue __UpperCAmelCase =rename_state_dict_key(A_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __UpperCAmelCase =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(A_ ) m.model.load_state_dict(A_ , strict=A_ ) m.half() m.save_pretrained(A_ ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin") parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.") parser.add_argument( "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use" ) __A = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
68
0
"""simple docstring""" class _a : def __init__( self : Optional[Any] ) -> Optional[Any]: snake_case : List[str] = {} def __lowercase ( self : str ) -> None: print(self.vertex ) for i in self.vertex: print(__SCREAMING_SNAKE_CASE , " -> " , " -> ".join([str(__SCREAMING_SNAKE_CASE ) for j in self.vertex[i]] ) ) def __lowercase ( self : Optional[Any] , _lowercase : int , _lowercase : int ) -> None: # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(__SCREAMING_SNAKE_CASE ) else: # else make a new vertex snake_case : Optional[Any] = [to_vertex] def __lowercase ( self : Tuple ) -> None: # visited array for storing already visited nodes snake_case : Any = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __lowercase ( self : Any , _lowercase : int , _lowercase : list ) -> None: # mark start vertex as visited snake_case : Any = True print(__SCREAMING_SNAKE_CASE , end=" " ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": A = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
449
from itertools import permutations def lowercase__ ( A_: tuple ) -> bool: """simple docstring""" 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 =[7, 11, 13, 17] for i, test in enumerate(A_ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def lowercase__ ( A_: int = 10 ) -> int: """simple docstring""" return sum( int("""""".join(map(A_ , A_ ) ) ) for num in permutations(range(A_ ) ) if is_substring_divisible(A_ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
68
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 _lowercase ( __a , __a , __a , unittest.TestCase ): _UpperCAmelCase = StableUnCLIPImgaImgPipeline _UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS _UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _UpperCAmelCase = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _UpperCAmelCase = frozenset([] ) def UpperCamelCase ( self ) -> Optional[int]: snake_case = 32 snake_case = embedder_hidden_size # image encoding components snake_case = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) snake_case = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__SCREAMING_SNAKE_CASE , projection_dim=__SCREAMING_SNAKE_CASE , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) snake_case = StableUnCLIPImageNormalizer(embedding_dim=__SCREAMING_SNAKE_CASE ) snake_case = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) snake_case = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) snake_case = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__SCREAMING_SNAKE_CASE , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) snake_case = 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=__SCREAMING_SNAKE_CASE , layers_per_block=1 , upcast_attention=__SCREAMING_SNAKE_CASE , use_linear_projection=__SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) snake_case = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type='''v_prediction''' , set_alpha_to_one=__SCREAMING_SNAKE_CASE , steps_offset=1 , ) torch.manual_seed(0 ) snake_case = AutoencoderKL() snake_case = { # 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 UpperCamelCase ( self , A__ , A__=0 , A__=True ) -> Dict: if str(__SCREAMING_SNAKE_CASE ).startswith('''mps''' ): snake_case = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) if pil_image: snake_case = input_image * 0.5 + 0.5 snake_case = input_image.clamp(0 , 1 ) snake_case = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() snake_case = DiffusionPipeline.numpy_to_pil(__SCREAMING_SNAKE_CASE )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def UpperCamelCase ( self ) -> str: snake_case = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case = self.get_dummy_components() snake_case = StableUnCLIPImgaImgPipeline(**__SCREAMING_SNAKE_CASE ) snake_case = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) inputs.update({'''image_embeds''': None} ) snake_case = sd_pipe(**__SCREAMING_SNAKE_CASE ).images snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case = np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase ( self ) -> str: snake_case = torch_device in ['''cpu''', '''mps'''] self._test_attention_slicing_forward_pass(test_max_difference=__SCREAMING_SNAKE_CASE ) def UpperCamelCase ( self ) -> Any: snake_case = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=__SCREAMING_SNAKE_CASE ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCamelCase ( self ) -> Tuple: self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__SCREAMING_SNAKE_CASE ) @slow @require_torch_gpu class _lowercase ( unittest.TestCase ): def UpperCamelCase ( self ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self ) -> List[str]: snake_case = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''' ) snake_case = 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''' ) snake_case = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-l-img2img''' , torch_dtype=torch.floataa ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # 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() snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case = pipe(__SCREAMING_SNAKE_CASE , '''anime turle''' , generator=__SCREAMING_SNAKE_CASE , output_type='''np''' ) snake_case = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCamelCase ( self ) -> Optional[Any]: snake_case = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''' ) snake_case = 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''' ) snake_case = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # 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() snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case = pipe(__SCREAMING_SNAKE_CASE , '''anime turle''' , generator=__SCREAMING_SNAKE_CASE , output_type='''np''' ) snake_case = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCamelCase ( self ) -> Union[str, Any]: snake_case = 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() snake_case = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa ) snake_case = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() snake_case = pipe( __SCREAMING_SNAKE_CASE , '''anime turtle''' , num_inference_steps=2 , output_type='''np''' , ) snake_case = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
342
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __A = TypeVar("T") def lowercase__ ( A_: int ) -> int: """simple docstring""" return (position - 1) // 2 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 1 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 2 class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[str] ) -> None: __UpperCAmelCase =[] __UpperCAmelCase ={} __UpperCAmelCase =0 def __len__( self : str ) -> int: return self.elements def __repr__( self : Dict ) -> str: return str(self.heap ) def _a ( self : Optional[int] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __UpperCAmelCase =self.elements self.elements += 1 self._bubble_up(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __UpperCAmelCase , __UpperCAmelCase =self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __UpperCAmelCase , __UpperCAmelCase =self.heap[0] self._bubble_down(__SCREAMING_SNAKE_CASE ) return elem def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Update the weight of the given key __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase =(elem, weight) if position > 0: __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._bubble_up(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __UpperCAmelCase =self.position_map[elem] if curr_pos == 0: return None __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_up(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase =get_child_left_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =get_child_right_position(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements and child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) else: return None if child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ) -> None: # Swap the nodes at the given positions __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase , __UpperCAmelCase =( self.heap[nodea_pos], self.heap[nodea_pos], ) __UpperCAmelCase =nodea_pos __UpperCAmelCase =nodea_pos class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[Any] ) -> None: __UpperCAmelCase ={} __UpperCAmelCase =0 def __repr__( self : Tuple ) -> str: return str(self.connections ) def __len__( self : str ) -> int: return self.nodes def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __UpperCAmelCase ={} self.nodes += 1 def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(__SCREAMING_SNAKE_CASE ) self.add_node(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =weight __UpperCAmelCase =weight def lowercase__ ( A_: GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: """simple docstring""" __UpperCAmelCase ={node: maxsize for node in graph.connections} __UpperCAmelCase ={node: None for node in graph.connections} __UpperCAmelCase =MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(A_ , A_ ) if priority_queue.is_empty(): return dist, parent # initialization __UpperCAmelCase =priority_queue.extract_min() __UpperCAmelCase =0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node # running prim's algorithm while not priority_queue.is_empty(): __UpperCAmelCase =priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node return dist, parent
68
0
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def lowerCamelCase_(lowerCamelCase_ ) -> Dict[str, torch.Tensor]: UpperCAmelCase = [] UpperCAmelCase = [] UpperCAmelCase = [] for rt in rc.restypes: UpperCAmelCase = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) UpperCAmelCase = {name: i for i, name in enumerate(A_ )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) UpperCAmelCase = torch.tensor( A_ , dtype=torch.intaa , device=protein["aatype"].device , ) UpperCAmelCase = torch.tensor( A_ , dtype=torch.intaa , device=protein["aatype"].device , ) UpperCAmelCase = torch.tensor( A_ , dtype=torch.floataa , device=protein["aatype"].device , ) UpperCAmelCase = protein["aatype"].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein UpperCAmelCase = restype_atomaa_to_atomaa[protein_aatype] UpperCAmelCase = restype_atomaa_mask[protein_aatype] UpperCAmelCase = residx_atomaa_mask UpperCAmelCase = residx_atomaa_to_atomaa.long() # create the gather indices for mapping back UpperCAmelCase = restype_atomaa_to_atomaa[protein_aatype] UpperCAmelCase = residx_atomaa_to_atomaa.long() # create the corresponding mask UpperCAmelCase = torch.zeros([21, 37] , dtype=torch.floataa , device=protein["aatype"].device ) for restype, restype_letter in enumerate(rc.restypes ): UpperCAmelCase = rc.restype_atoa[restype_letter] UpperCAmelCase = rc.residue_atoms[restype_name] for atom_name in atom_names: UpperCAmelCase = rc.atom_order[atom_name] UpperCAmelCase = 1 UpperCAmelCase = restype_atomaa_mask[protein_aatype] UpperCAmelCase = residx_atomaa_mask return protein def lowerCamelCase_(lowerCamelCase_ ) -> Dict[str, np.ndarray]: UpperCAmelCase = tree_map(lambda lowerCamelCase_ : torch.tensor(A_ , device=batch["aatype"].device ) , A_ , np.ndarray ) UpperCAmelCase = tensor_tree_map(lambda lowerCamelCase_ : np.array(A_ ) , make_atomaa_masks(A_ ) ) return out
323
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 __A = logging.get_logger(__name__) @dataclass class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[int] = [ 'no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process', ] def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __UpperCAmelCase =deprecated_arg[3:] __UpperCAmelCase =not kwargs.pop(__SCREAMING_SNAKE_CASE ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) __UpperCAmelCase =kwargs.pop("""tpu_name""" , self.tpu_name ) __UpperCAmelCase =kwargs.pop("""device_idx""" , self.device_idx ) __UpperCAmelCase =kwargs.pop("""eager_mode""" , self.eager_mode ) __UpperCAmelCase =kwargs.pop("""use_xla""" , self.use_xla ) super().__init__(**__SCREAMING_SNAKE_CASE ) lowerCamelCase : str = field( default=UpperCamelCase , metadata={'help': 'Name of TPU'} , ) lowerCamelCase : int = field( default=0 , metadata={'help': 'CPU / GPU device index. Defaults to 0.'} , ) lowerCamelCase : bool = field(default=UpperCamelCase , metadata={'help': 'Benchmark models in eager model.'} ) lowerCamelCase : 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 _a ( self : List[str] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) __UpperCAmelCase =None if self.tpu: try: if self.tpu_name: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __UpperCAmelCase =None return tpu @cached_property def _a ( self : Tuple ) -> 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 ) __UpperCAmelCase =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""" ) __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , """GPU""" ) # disable GPU __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/cpu:{self.device_idx}''' ) return strategy @property def _a ( self : Optional[Any] ) -> bool: requires_backends(self , ["""tf"""] ) return self._setup_tpu is not None @property def _a ( self : str ) -> "tf.distribute.Strategy": requires_backends(self , ["""tf"""] ) return self._setup_strategy @property def _a ( self : Dict ) -> Optional[int]: requires_backends(self , ["""tf"""] ) return tf.config.list_physical_devices("""GPU""" ) @property def _a ( self : List[str] ) -> int: requires_backends(self , ["""tf"""] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _a ( self : List[str] ) -> bool: return self.n_gpu > 0
68
0
'''simple docstring''' def lowerCAmelCase ( UpperCamelCase__ : list[int] , UpperCamelCase__ : int ): """simple docstring""" __UpperCAmelCase = len(A_ ) __UpperCAmelCase = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __UpperCAmelCase = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): __UpperCAmelCase = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: __UpperCAmelCase = subset[i - 1][j] if arr[i - 1] <= j: __UpperCAmelCase = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
262
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 _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Dict: torch.manual_seed(0 ) __UpperCAmelCase =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 _a ( self : int ) -> Union[str, Any]: __UpperCAmelCase =self.dummy_uncond_unet __UpperCAmelCase =ScoreSdeVeScheduler() __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE )[ 0 ] __UpperCAmelCase =image[0, -3:, -3:, -1] __UpperCAmelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCAmelCase =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 _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Optional[int] ) -> int: __UpperCAmelCase ="""google/ncsnpp-church-256""" __UpperCAmelCase =UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVeScheduler.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=10 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCAmelCase =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
68
0
"""simple docstring""" from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) @add_end_docstrings(lowercase_ ) class UpperCamelCase ( lowercase_ ): def __init__( self ,*__UpperCamelCase ,**__UpperCamelCase ) -> Union[str, Any]: '''simple docstring''' super().__init__(*__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) requires_backends(self ,'vision' ) self.check_model_type(__SCREAMING_SNAKE_CASE ) def __call__( self ,__UpperCamelCase ,**__UpperCamelCase ) -> Tuple: '''simple docstring''' return super().__call__(__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self ,**__UpperCamelCase ) -> Any: '''simple docstring''' return {}, {}, {} def _UpperCAmelCase ( self ,__UpperCamelCase ) -> int: '''simple docstring''' lowercase_ : Tuple = load_image(__SCREAMING_SNAKE_CASE ) lowercase_ : int = image.size lowercase_ : str = self.image_processor(images=__SCREAMING_SNAKE_CASE ,return_tensors=self.framework ) return model_inputs def _UpperCAmelCase ( self ,__UpperCamelCase ) -> List[str]: '''simple docstring''' lowercase_ : Union[str, Any] = self.model(**__SCREAMING_SNAKE_CASE ) return model_outputs def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Tuple: '''simple docstring''' lowercase_ : Optional[int] = model_outputs.predicted_depth lowercase_ : Union[str, Any] = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) ,size=self.image_size[::-1] ,mode='bicubic' ,align_corners=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = prediction.squeeze().cpu().numpy() lowercase_ : Optional[int] = (output * 255 / np.max(__SCREAMING_SNAKE_CASE )).astype('uint8' ) lowercase_ : Optional[Any] = Image.fromarray(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = {} lowercase_ : int = predicted_depth lowercase_ : int = depth return output_dict
425
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __A = logging.get_logger(__name__) __A = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class _A ( UpperCamelCase ): """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : str=None , *__SCREAMING_SNAKE_CASE : Union[str, Any] , **__SCREAMING_SNAKE_CASE : List[Any] ) -> Any: super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if config is None: assert isinstance(self.model , __SCREAMING_SNAKE_CASE ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f''' {self.model.__class__}''' ) __UpperCAmelCase =self.model.config else: __UpperCAmelCase =config __UpperCAmelCase =data_args __UpperCAmelCase =self.config.tgt_vocab_size if isinstance(self.config , __SCREAMING_SNAKE_CASE ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' """ padding..""" ) if self.args.label_smoothing == 0: __UpperCAmelCase =torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __UpperCAmelCase =label_smoothed_nll_loss def _a ( self : Any , __SCREAMING_SNAKE_CASE : int ) -> Any: if self.optimizer is None: __UpperCAmelCase =["""bias""", """LayerNorm.weight"""] __UpperCAmelCase =[ { """params""": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], """weight_decay""": self.args.weight_decay, }, { """params""": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], """weight_decay""": 0.0, }, ] __UpperCAmelCase =Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __UpperCAmelCase =Adafactor __UpperCAmelCase ={"""scale_parameter""": False, """relative_step""": False} else: __UpperCAmelCase =AdamW __UpperCAmelCase ={ """betas""": (self.args.adam_betaa, self.args.adam_betaa), """eps""": self.args.adam_epsilon, } __UpperCAmelCase =self.args.learning_rate if self.sharded_ddp: __UpperCAmelCase =OSS( params=__SCREAMING_SNAKE_CASE , optim=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: __UpperCAmelCase =optimizer_cls(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if self.lr_scheduler is None: __UpperCAmelCase =self._get_lr_scheduler(__SCREAMING_SNAKE_CASE ) else: # ignoring --lr_scheduler logger.warning("""scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.""" ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Any: __UpperCAmelCase =arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __UpperCAmelCase =schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __UpperCAmelCase =schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __UpperCAmelCase =schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=__SCREAMING_SNAKE_CASE ) return scheduler def _a ( self : Optional[Any] ) -> Optional[torch.utils.data.Sampler]: if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Tuple: if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __UpperCAmelCase , __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[:2] else: # compute label smoothed loss __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =torch.nn.functional.log_softmax(__SCREAMING_SNAKE_CASE , dim=-1 ) __UpperCAmelCase , __UpperCAmelCase =self.loss_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: __UpperCAmelCase =inputs.pop("""labels""" ) __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return loss def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : nn.Module , __SCREAMING_SNAKE_CASE : Dict[str, Union[torch.Tensor, Any]] , __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : Optional[List[str]] = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: __UpperCAmelCase =self._prepare_inputs(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """max_length""": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, """num_beams""": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __UpperCAmelCase =self.model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , **__SCREAMING_SNAKE_CASE , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) __UpperCAmelCase =inputs.pop("""labels""" ) with torch.no_grad(): # compute loss on predict data __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __UpperCAmelCase =generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) return (loss, logits, labels) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: # If PAD token is not defined at least EOS token has to be defined __UpperCAmelCase =self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( """Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be""" f''' padded to `max_length`={max_length}''' ) __UpperCAmelCase =pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __UpperCAmelCase =tensor return padded_tensor
68
0
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: UpperCamelCase_ : Optional[Any] = None UpperCamelCase_ : List[Any] = logging.get_logger(__name__) UpperCamelCase_ : List[str] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase_ : str = { '''vocab_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json''' ), }, } UpperCamelCase_ : List[Any] = { '''moussaKam/mbarthez''': 1024, '''moussaKam/barthez''': 1024, '''moussaKam/barthez-orangesum-title''': 1024, } UpperCamelCase_ : str = '''▁''' class __lowerCAmelCase ( _lowercase ): """simple docstring""" snake_case = VOCAB_FILES_NAMES snake_case = PRETRAINED_VOCAB_FILES_MAP snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case = ['input_ids', 'attention_mask'] snake_case = BarthezTokenizer def __init__( self : Any , _snake_case : str=None , _snake_case : Any=None , _snake_case : Any="<s>" , _snake_case : str="</s>" , _snake_case : Union[str, Any]="</s>" , _snake_case : Any="<s>" , _snake_case : Union[str, Any]="<unk>" , _snake_case : List[str]="<pad>" , _snake_case : Optional[Any]="<mask>" , **_snake_case : Dict , ) -> List[str]: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it A_ = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token super().__init__( __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) A_ = vocab_file A_ = False if not self.vocab_file else True def lowerCamelCase__ ( self : List[str] , _snake_case : List[int] , _snake_case : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A_ = [self.cls_token_id] A_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase__ ( self : str , _snake_case : List[int] , _snake_case : Optional[List[int]] = 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] def lowerCamelCase__ ( self : int , _snake_case : str , _snake_case : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A_ = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
115
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : List[Any] = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str=0 ) -> Any: __UpperCAmelCase =floats_tensor((1, 3, 128, 128) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =np.random.RandomState(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """strength""": 0.75, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _a ( self : Optional[Any] ) -> int: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Union[str, Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Optional[Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # warmup pass to apply optimizations __UpperCAmelCase =pipe(**self.get_dummy_inputs() ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Optional[int]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _a ( self : Dict ) -> int: __UpperCAmelCase =ort.SessionOptions() __UpperCAmelCase =False return options def _a ( self : Dict ) -> Any: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) # using the PNDM scheduler by default __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _a ( self : List[str] ) -> str: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) __UpperCAmelCase =LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
68
0
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm __snake_case :Union[str, Any] =re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex __snake_case :int =10 __snake_case :Optional[int] =256 def lowerCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: '''simple docstring''' if len(A_ ) < MIN_NUM_TOKENS: return None A = MinHash(num_perm=A_ ) for token in set(A_ ): min_hash.update(token.encode() ) return min_hash def lowerCamelCase_ ( lowerCAmelCase__ : str ) -> Set[str]: '''simple docstring''' return {t for t in NON_ALPHA.split(A_ ) if len(t.strip() ) > 0} class lowerCAmelCase__ : def __init__( self : str , *, __UpperCamelCase : float = 0.8_5 , ) -> Any: A = duplication_jaccard_threshold A = NUM_PERM A = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) A = defaultdict(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : Tuple , __UpperCamelCase : MinHash ) -> None: A = self._index.query(__SCREAMING_SNAKE_CASE ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__SCREAMING_SNAKE_CASE ) break else: self._duplicate_clusters[close_duplicates[0]].add(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self : str ) -> List[List[Dict]]: A = [] for base, duplicates in self._duplicate_clusters.items(): A = [base] + list(__SCREAMING_SNAKE_CASE ) # reformat the cluster to be a list of dict A = [{'base_index': el[0], 'repo_name': el[1], 'path': el[2]} for el in cluster] duplicate_clusters.append(__SCREAMING_SNAKE_CASE ) return duplicate_clusters def __UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : Any ) -> None: A = self.get_duplicate_clusters() with open(__SCREAMING_SNAKE_CASE , 'w' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( lowerCAmelCase__ : Any ) -> Union[str, Any]: '''simple docstring''' A , A = element A = get_min_hash([t for t in NON_ALPHA.split(data['content'] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowerCamelCase_ ( lowerCAmelCase__ : Type[Dataset] ) -> Optional[Any]: '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(A_ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowerCamelCase_ ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Optional[Any]: '''simple docstring''' A = DuplicationIndex(duplication_jaccard_threshold=A_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(A_ ) ) , max_queue_size=100 ) ): di.add(A_ , A_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowerCamelCase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: '''simple docstring''' A = get_tokens(A_ ) A = get_tokens(A_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) __snake_case :Optional[int] =None def lowerCamelCase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : int ) -> Union[str, Any]: '''simple docstring''' A = [] for elementa in cluster: A = _shared_dataset[elementa['base_index']]['content'] for elementa in extremes: A = _shared_dataset[elementa['base_index']]['content'] if jaccard_similarity(A_ , A_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: A = 1 extremes.append(A_ ) return extremes def lowerCamelCase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : Any ) -> Tuple: '''simple docstring''' global _shared_dataset A = dataset A = [] A = partial(_find_cluster_extremes_shared , jaccard_threshold=A_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( A_ , A_ , ) , total=len(A_ ) , ): extremes_list.append(A_ ) return extremes_list def lowerCamelCase_ ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: '''simple docstring''' A = make_duplicate_clusters(A_ , A_ ) A = {x['base_index'] for cluster in duplicate_clusters for x in cluster} A = {} A = find_extremes(A_ , A_ , A_ ) for extremes in extremes_clusters: for element in extremes: A = element A = duplicate_indices - set(extreme_dict.keys() ) A = dataset.filter(lambda lowerCAmelCase__ , lowerCAmelCase__ : idx not in remove_indices , with_indices=A_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: A = element['base_index'] in extreme_dict if element["is_extreme"]: A = extreme_dict[element['base_index']]['copies'] print(F'''Original dataset size: {len(A_ )}''' ) print(F'''Number of duplicate clusters: {len(A_ )}''' ) print(F'''Files in duplicate cluster: {len(A_ )}''' ) print(F'''Unique files in duplicate cluster: {len(A_ )}''' ) print(F'''Filtered dataset size: {len(A_ )}''' ) return ds_filter, duplicate_clusters
106
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors __A = logging.getLogger(__name__) class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[Any] = 'sequence-classification' def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Tuple ) -> Optional[Any]: if type(__SCREAMING_SNAKE_CASE ) == dict: __UpperCAmelCase =Namespace(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =glue_output_modes[hparams.task] __UpperCAmelCase =glue_tasks_num_labels[hparams.task] super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.mode ) def _a ( self : str , **__SCREAMING_SNAKE_CASE : Dict ) -> List[str]: return self.model(**__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ) -> List[Any]: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =outputs[0] __UpperCAmelCase =self.trainer.lr_schedulers[0]["""scheduler"""] __UpperCAmelCase ={"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def _a ( self : Tuple ) -> List[Any]: __UpperCAmelCase =self.hparams __UpperCAmelCase =processors[args.task]() __UpperCAmelCase =processor.get_labels() for mode in ["train", "dev"]: __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) if os.path.exists(__SCREAMING_SNAKE_CASE ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) __UpperCAmelCase =( processor.get_dev_examples(args.data_dir ) if mode == """dev""" else processor.get_train_examples(args.data_dir ) ) __UpperCAmelCase =convert_examples_to_features( __SCREAMING_SNAKE_CASE , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("""Saving features into cached file %s""" , __SCREAMING_SNAKE_CASE ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ) -> DataLoader: __UpperCAmelCase ="""dev""" if mode == """test""" else mode __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.load(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , batch_size=__SCREAMING_SNAKE_CASE , shuffle=__SCREAMING_SNAKE_CASE , ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ) -> str: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =outputs[:2] __UpperCAmelCase =logits.detach().cpu().numpy() __UpperCAmelCase =inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Any ) -> tuple: __UpperCAmelCase =torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item() __UpperCAmelCase =np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =np.argmax(__SCREAMING_SNAKE_CASE , axis=1 ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =np.squeeze(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =np.concatenate([x["""target"""] for x in outputs] , axis=0 ) __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase ={**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} __UpperCAmelCase =dict(results.items() ) __UpperCAmelCase =results return ret, preds_list, out_label_list def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : list ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _a ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[Any]: BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) parser.add_argument( """--max_seq_length""" , default=128 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--task""" , default="""""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The GLUE task to run""" , ) parser.add_argument( """--gpus""" , default=0 , type=__SCREAMING_SNAKE_CASE , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser def lowercase__ ( ) -> str: """simple docstring""" __UpperCAmelCase =argparse.ArgumentParser() add_generic_args(A_ , os.getcwd() ) __UpperCAmelCase =GLUETransformer.add_model_specific_args(A_ , os.getcwd() ) __UpperCAmelCase =parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __UpperCAmelCase =os.path.join( """./results""" , F'''{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}''' , ) os.makedirs(args.output_dir ) __UpperCAmelCase =GLUETransformer(A_ ) __UpperCAmelCase =generic_train(A_ , A_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __UpperCAmelCase =sorted(glob.glob(os.path.join(args.output_dir , """checkpoint-epoch=*.ckpt""" ) , recursive=A_ ) ) __UpperCAmelCase =model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(A_ ) if __name__ == "__main__": main()
68
0
"""simple docstring""" import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __A ( A_ ): '''simple docstring''' def __init__( self : Optional[int] ,*_snake_case : int ,_snake_case : Optional[Any]=None ,_snake_case : Tuple=None ,**_snake_case : Tuple ) -> Any: """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) lowercase__ : Optional[Any] = eval_examples lowercase__ : Optional[Any] = post_process_function def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : Optional[Dataset] = None ,_snake_case : List[str]=None ,_snake_case : Optional[List[str]] = None ,_snake_case : str = "eval" ,**_snake_case : str ,) -> Dict[str, float]: """simple docstring""" lowercase__ : int = gen_kwargs.copy() lowercase__ : Tuple = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase__ : Optional[int] = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase__ : Optional[Any] = gen_kwargs lowercase__ : Optional[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase__ : Optional[int] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase__ : List[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase__ : Tuple = self.compute_metrics lowercase__ : Dict = None lowercase__ : Tuple = time.time() lowercase__ : List[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase__ : List[str] = eval_loop( __SCREAMING_SNAKE_CASE ,description='''Evaluation''' ,prediction_loss_only=True if compute_metrics is None else None ,ignore_keys=__SCREAMING_SNAKE_CASE ,metric_key_prefix=__SCREAMING_SNAKE_CASE ,) finally: lowercase__ : Optional[int] = compute_metrics lowercase__ : str = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,num_samples=output.num_samples ,num_steps=math.ceil(output.num_samples / total_batch_size ) ,) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase__ : Tuple = self.post_process_function(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase__ : Dict = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): lowercase__ : Optional[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase__ : Any = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase__ : int = self.callback_handler.on_evaluate(self.args ,self.state ,self.control ,__SCREAMING_SNAKE_CASE ) return metrics def UpperCAmelCase ( self : int ,_snake_case : Optional[Any] ,_snake_case : int ,_snake_case : int=None ,_snake_case : str = "test" ,**_snake_case : List[Any] ) -> Dict: """simple docstring""" lowercase__ : Optional[Any] = gen_kwargs.copy() lowercase__ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase__ : Dict = self.compute_metrics lowercase__ : Optional[int] = None lowercase__ : int = time.time() lowercase__ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase__ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE ,description='''Prediction''' ,prediction_loss_only=True if compute_metrics is None else None ,ignore_keys=__SCREAMING_SNAKE_CASE ,metric_key_prefix=__SCREAMING_SNAKE_CASE ,) finally: lowercase__ : Union[str, Any] = compute_metrics lowercase__ : Optional[int] = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,num_samples=output.num_samples ,num_steps=math.ceil(output.num_samples / total_batch_size ) ,) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase__ : List[str] = self.post_process_function(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,'''predict''' ) lowercase__ : List[str] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): lowercase__ : Dict = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions ,label_ids=predictions.label_ids ,metrics=__SCREAMING_SNAKE_CASE )
560
def lowercase__ ( A_: int , A_: int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def lowercase__ ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline 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_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =IFImgaImgSuperResolutionPipeline _lowerCamelCase =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'} _lowerCamelCase =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"original_image"} ) _lowerCamelCase =PipelineTesterMixin.required_optional_params - {'latents'} def __snake_case ( self : Any ): return self._get_superresolution_dummy_components() def __snake_case ( self : str , a__ : Union[str, Any] , a__ : Optional[Any]=0 ): if str(__SCREAMING_SNAKE_CASE ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: UpperCAmelCase = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = floats_tensor((1, 3, 16, 16) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''original_image''': original_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 __snake_case ( self : Optional[Any] ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __snake_case ( self : str ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __snake_case ( self : Optional[Any] ): # 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 __snake_case ( self : Any ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __snake_case ( self : List[Any] ): self._test_save_load_local() def __snake_case ( self : List[Any] ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
51
from __future__ import annotations import bisect def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] < item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_left(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_right(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =0 __UpperCAmelCase =len(A_ ) - 1 while left <= right: __UpperCAmelCase =left + (right - left) // 2 __UpperCAmelCase =sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __UpperCAmelCase =midpoint - 1 else: __UpperCAmelCase =midpoint + 1 return None def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =bisect.bisect_left(A_ , A_ ) if index != len(A_ ) and sorted_collection[index] == item: return index return None def lowercase__ ( A_: list[int] , A_: int , A_: int , A_: int ) -> int | None: """simple docstring""" if right < left: return None __UpperCAmelCase =left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(A_ , A_ , A_ , midpoint - 1 ) else: return binary_search_by_recursion(A_ , A_ , midpoint + 1 , A_ ) if __name__ == "__main__": __A = input("Enter numbers separated by comma:\n").strip() __A = sorted(int(item) for item in user_input.split(",")) __A = int(input("Enter a single number to be found in the list:\n")) __A = binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
68
0
"""simple docstring""" class _lowerCAmelCase : def __init__( self , a_ ) -> None: _UpperCAmelCase = set_counts _UpperCAmelCase = max(__SCREAMING_SNAKE_CASE ) _UpperCAmelCase = len(__SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [1] * num_sets _UpperCAmelCase = list(range(__SCREAMING_SNAKE_CASE ) ) def _a ( self , a_ , a_ ) -> bool: _UpperCAmelCase = self.get_parent(__SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.get_parent(__SCREAMING_SNAKE_CASE ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] _UpperCAmelCase = 0 _UpperCAmelCase = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 _UpperCAmelCase = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] _UpperCAmelCase = 0 _UpperCAmelCase = src_parent _UpperCAmelCase = self.set_counts[src_parent] _UpperCAmelCase = max(self.max_set , __SCREAMING_SNAKE_CASE ) return True def _a ( self , a_ ) -> int: if self.parents[disj_set] == disj_set: return disj_set _UpperCAmelCase = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
657
from typing import List from .keymap import KEYMAP, get_character def lowercase__ ( A_: str ) -> str: """simple docstring""" def decorator(A_: int ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += [key] setattr(A_ , """handle_key""" , A_ ) return func return decorator def lowercase__ ( *A_: List[str] ) -> Optional[int]: """simple docstring""" def decorator(A_: Tuple ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += keys setattr(A_ , """handle_key""" , A_ ) return func return decorator class _A ( UpperCamelCase ): """simple docstring""" def __new__( cls : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> int: __UpperCAmelCase =super().__new__(cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if not hasattr(__SCREAMING_SNAKE_CASE , """key_handler""" ): setattr(__SCREAMING_SNAKE_CASE , """key_handler""" , {} ) setattr(__SCREAMING_SNAKE_CASE , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , """handle_key""" , [] ) for key in handled_keys: __UpperCAmelCase =value return new_cls @staticmethod def _a ( cls : Dict ) -> List[Any]: __UpperCAmelCase =get_character() if char != KEYMAP["undefined"]: __UpperCAmelCase =ord(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =cls.key_handler.get(__SCREAMING_SNAKE_CASE ) if handler: __UpperCAmelCase =char return handler(cls ) else: return None def lowercase__ ( cls: str ) -> int: """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
68
0
'''simple docstring''' import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = 0 snake_case_ = False snake_case_ = 3.0 class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : Tuple ) -> Dict: # If no defaults are changed, `to_kwargs` returns an empty dict. self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {'''a''': 2} ) self.assertDictEqual(MockClass(a=2 , b=__SCREAMING_SNAKE_CASE ).to_kwargs() , {'''a''': 2, '''b''': True} ) self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {'''a''': 2, '''c''': 2.25} ) @require_cuda def __magic_name__ ( self : str ) -> Optional[Any]: # If no defaults are changed, `to_kwargs` returns an empty dict. SCREAMING_SNAKE_CASE__ : str =GradScalerKwargs(init_scale=10_24 , growth_factor=2 ) AcceleratorState._reset_state() SCREAMING_SNAKE_CASE__ : Tuple =Accelerator(mixed_precision='''fp16''' , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) SCREAMING_SNAKE_CASE__ : Tuple =accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 10_24.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 20_00 ) self.assertEqual(scaler._enabled , __SCREAMING_SNAKE_CASE ) @require_multi_gpu def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Tuple =['''torchrun''', F"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__ )] execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) if __name__ == "__main__": a_ = DistributedDataParallelKwargs(bucket_cap_mb=1_5, find_unused_parameters=True) a_ = Accelerator(kwargs_handlers=[ddp_scaler]) a_ = torch.nn.Linear(1_0_0, 2_0_0) a_ = accelerator.prepare(model) # Check the values changed in kwargs a_ = '' a_ = model.bucket_bytes_cap // (1_0_2_4 * 1_0_2_4) if observed_bucket_cap_map != 1_5: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
296
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
68
0
"""simple docstring""" import re import string import numpy as np import datasets A = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' A = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It\'s like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It\'s like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n' A = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _a ( datasets.Metric): def __lowercase ( self : List[str] ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowercase ( self : int , _lowercase : Dict , _lowercase : str , _lowercase : int=None , _lowercase : Optional[Any]=False , _lowercase : Any=False , _lowercase : str=False , ) -> Optional[Any]: if regexes_to_ignore is not None: for s in regexes_to_ignore: snake_case : Dict = np.array([re.sub(__SCREAMING_SNAKE_CASE , "" , __SCREAMING_SNAKE_CASE ) for x in predictions] ) snake_case : List[str] = np.array([re.sub(__SCREAMING_SNAKE_CASE , "" , __SCREAMING_SNAKE_CASE ) for x in references] ) else: snake_case : List[Any] = np.asarray(__SCREAMING_SNAKE_CASE ) snake_case : Dict = np.asarray(__SCREAMING_SNAKE_CASE ) if ignore_case: snake_case : str = np.char.lower(__SCREAMING_SNAKE_CASE ) snake_case : Union[str, Any] = np.char.lower(__SCREAMING_SNAKE_CASE ) if ignore_punctuation: snake_case : List[str] = string.punctuation.maketrans("" , "" , string.punctuation ) snake_case : int = np.char.translate(__SCREAMING_SNAKE_CASE , table=__SCREAMING_SNAKE_CASE ) snake_case : int = np.char.translate(__SCREAMING_SNAKE_CASE , table=__SCREAMING_SNAKE_CASE ) if ignore_numbers: snake_case : str = string.digits.maketrans("" , "" , string.digits ) snake_case : Optional[Any] = np.char.translate(__SCREAMING_SNAKE_CASE , table=__SCREAMING_SNAKE_CASE ) snake_case : Tuple = np.char.translate(__SCREAMING_SNAKE_CASE , table=__SCREAMING_SNAKE_CASE ) snake_case : int = predictions == references return {"exact_match": np.mean(__SCREAMING_SNAKE_CASE ) * 100}
449
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _A ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Optional[Any]=99 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : int=5 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : str=37 , __SCREAMING_SNAKE_CASE : Union[str, Any]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : str=512 , __SCREAMING_SNAKE_CASE : Dict=16 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : List[str]=4 , ) -> Optional[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =seq_length __UpperCAmelCase =is_training __UpperCAmelCase =use_attention_mask __UpperCAmelCase =use_token_type_ids __UpperCAmelCase =use_labels __UpperCAmelCase =vocab_size __UpperCAmelCase =hidden_size __UpperCAmelCase =num_hidden_layers __UpperCAmelCase =num_attention_heads __UpperCAmelCase =intermediate_size __UpperCAmelCase =hidden_act __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =max_position_embeddings __UpperCAmelCase =type_vocab_size __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =initializer_range __UpperCAmelCase =num_choices def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase =None if self.use_attention_mask: __UpperCAmelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase =None if self.use_token_type_ids: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase =RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def _a ( self : List[str] ) -> Dict: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase =True __UpperCAmelCase =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] = True lowerCamelCase : Union[str, Any] = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =FlaxRobertaModelTester(self ) @slow def _a ( self : Optional[Any] ) -> List[Any]: for model_class_name in self.all_model_classes: __UpperCAmelCase =model_class_name.from_pretrained("""roberta-base""" , from_pt=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model(np.ones((1, 1) ) ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class _lowercase ( unittest.TestCase ): @slow def UpperCamelCase ( self ) -> Optional[int]: snake_case = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) snake_case = AutoTokenizer.from_pretrained('''google/mt5-small''' ) snake_case = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids snake_case = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids snake_case = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss snake_case = -(labels.shape[-1] * loss.item()) snake_case = -8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
342
from __future__ import annotations def lowercase__ ( A_: list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(A_ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
68
0
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __lowerCamelCase : Optional[Any] = (720, 1_280) # Height, Width __lowerCamelCase : Dict = (0.4, 0.6) # if height or width lower than this scale, drop it. __lowerCamelCase : int = 1 / 100 __lowerCamelCase : Tuple = "" __lowerCamelCase : List[str] = "" __lowerCamelCase : List[Any] = "" __lowerCamelCase : Union[str, Any] = 250 def lowerCamelCase_() -> None: UpperCAmelCase , UpperCAmelCase = get_dataset(A_ , A_ ) for index in range(A_ ): UpperCAmelCase = random.sample(range(len(A_ ) ) , 4 ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = update_image_and_anno( A_ , A_ , A_ , A_ , A_ , filter_scale=A_ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' UpperCAmelCase = random_chars(32 ) UpperCAmelCase = path.split(os.sep )[-1].rsplit("." , 1 )[0] UpperCAmelCase = F'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(F'{file_root}.jpg' , A_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) UpperCAmelCase = [] for anno in new_annos: UpperCAmelCase = anno[3] - anno[1] UpperCAmelCase = anno[4] - anno[2] UpperCAmelCase = anno[1] + width / 2 UpperCAmelCase = anno[2] + height / 2 UpperCAmelCase = F'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(A_ ) with open(F'{file_root}.txt' , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def lowerCamelCase_(lowerCamelCase_ , lowerCamelCase_ ) -> tuple[list, list]: UpperCAmelCase = [] UpperCAmelCase = [] for label_file in glob.glob(os.path.join(A_ , "*.txt" ) ): UpperCAmelCase = label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(A_ ) as in_file: UpperCAmelCase = in_file.readlines() UpperCAmelCase = os.path.join(A_ , F'{label_name}.jpg' ) UpperCAmelCase = [] for obj_list in obj_lists: UpperCAmelCase = obj_list.rstrip("\n" ).split(" " ) UpperCAmelCase = float(obj[1] ) - float(obj[3] ) / 2 UpperCAmelCase = float(obj[2] ) - float(obj[4] ) / 2 UpperCAmelCase = float(obj[1] ) + float(obj[3] ) / 2 UpperCAmelCase = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(A_ ) labels.append(A_ ) return img_paths, labels def lowerCamelCase_(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 0.0 , ) -> tuple[list, list, str]: UpperCAmelCase = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) UpperCAmelCase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) UpperCAmelCase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) UpperCAmelCase = int(scale_x * output_size[1] ) UpperCAmelCase = int(scale_y * output_size[0] ) UpperCAmelCase = [] UpperCAmelCase = [] for i, index in enumerate(A_ ): UpperCAmelCase = all_img_list[index] path_list.append(A_ ) UpperCAmelCase = all_annos[index] UpperCAmelCase = cva.imread(A_ ) if i == 0: # top-left UpperCAmelCase = cva.resize(A_ , (divid_point_x, divid_point_y) ) UpperCAmelCase = img for bbox in img_annos: UpperCAmelCase = bbox[1] * scale_x UpperCAmelCase = bbox[2] * scale_y UpperCAmelCase = bbox[3] * scale_x UpperCAmelCase = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right UpperCAmelCase = cva.resize(A_ , (output_size[1] - divid_point_x, divid_point_y) ) UpperCAmelCase = img for bbox in img_annos: UpperCAmelCase = scale_x + bbox[1] * (1 - scale_x) UpperCAmelCase = bbox[2] * scale_y UpperCAmelCase = scale_x + bbox[3] * (1 - scale_x) UpperCAmelCase = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left UpperCAmelCase = cva.resize(A_ , (divid_point_x, output_size[0] - divid_point_y) ) UpperCAmelCase = img for bbox in img_annos: UpperCAmelCase = bbox[1] * scale_x UpperCAmelCase = scale_y + bbox[2] * (1 - scale_y) UpperCAmelCase = bbox[3] * scale_x UpperCAmelCase = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right UpperCAmelCase = cva.resize( A_ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) UpperCAmelCase = img for bbox in img_annos: UpperCAmelCase = scale_x + bbox[1] * (1 - scale_x) UpperCAmelCase = scale_y + bbox[2] * (1 - scale_y) UpperCAmelCase = scale_x + bbox[3] * (1 - scale_x) UpperCAmelCase = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: UpperCAmelCase = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def lowerCamelCase_(lowerCamelCase_ ) -> str: assert number_char > 1, "The number of character should greater than 1" UpperCAmelCase = ascii_lowercase + digits return "".join(random.choice(A_ ) for _ in range(A_ ) ) if __name__ == "__main__": main() print("DONE ✅")
323
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowercase__ ( A_: int , A_: int , A_: int , A_: int , A_: int , A_: int ) -> np.ndarray: """simple docstring""" if (ksize % 2) == 0: __UpperCAmelCase =ksize + 1 __UpperCAmelCase =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(A_ ): for x in range(A_ ): # distance from center __UpperCAmelCase =x - ksize // 2 __UpperCAmelCase =y - ksize // 2 # degree to radiant __UpperCAmelCase =theta / 180 * np.pi __UpperCAmelCase =np.cos(_theta ) __UpperCAmelCase =np.sin(_theta ) # get kernel x __UpperCAmelCase =cos_theta * px + sin_theta * py # get kernel y __UpperCAmelCase =-sin_theta * px + cos_theta * py # fill kernel __UpperCAmelCase =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __A = imread("../image_data/lena.jpg") # turn image in gray scale value __A = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __A = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 1_20, 1_50]: __A = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __A = out / out.max() * 2_55 __A = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
68
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 YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : int = logging.get_logger(__name__) def lowerCAmelCase ( UpperCamelCase__ : str ): """simple docstring""" __UpperCAmelCase = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: __UpperCAmelCase = 1_9_2 __UpperCAmelCase = 7_6_8 __UpperCAmelCase = 1_2 __UpperCAmelCase = 3 __UpperCAmelCase = [8_0_0, 1_3_3_3] __UpperCAmelCase = False elif yolos_name == "yolos_s_dWr": __UpperCAmelCase = 3_3_0 __UpperCAmelCase = 1_4 __UpperCAmelCase = 6 __UpperCAmelCase = 1_3_2_0 elif "yolos_s" in yolos_name: __UpperCAmelCase = 3_8_4 __UpperCAmelCase = 1_5_3_6 __UpperCAmelCase = 1_2 __UpperCAmelCase = 6 elif "yolos_b" in yolos_name: __UpperCAmelCase = [8_0_0, 1_3_4_4] __UpperCAmelCase = 9_1 __UpperCAmelCase = '''huggingface/label-files''' __UpperCAmelCase = '''coco-detection-id2label.json''' __UpperCAmelCase = json.load(open(hf_hub_download(A_ , A_ , repo_type='''dataset''' ) , '''r''' ) ) __UpperCAmelCase = {int(A_ ): v for k, v in idalabel.items()} __UpperCAmelCase = idalabel __UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase ( UpperCamelCase__ : dict , UpperCamelCase__ : YolosConfig , UpperCamelCase__ : bool = False ): """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __UpperCAmelCase = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) __UpperCAmelCase = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict __UpperCAmelCase = in_proj_weight[: config.hidden_size, :] __UpperCAmelCase = in_proj_bias[: config.hidden_size] __UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __UpperCAmelCase = in_proj_weight[-config.hidden_size :, :] __UpperCAmelCase = in_proj_bias[-config.hidden_size :] def lowerCAmelCase ( UpperCamelCase__ : str ): """simple docstring""" if "backbone" in name: __UpperCAmelCase = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: __UpperCAmelCase = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: __UpperCAmelCase = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: __UpperCAmelCase = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: __UpperCAmelCase = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: __UpperCAmelCase = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: __UpperCAmelCase = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: __UpperCAmelCase = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: __UpperCAmelCase = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: __UpperCAmelCase = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: __UpperCAmelCase = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: __UpperCAmelCase = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: __UpperCAmelCase = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: __UpperCAmelCase = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: __UpperCAmelCase = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: __UpperCAmelCase = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def lowerCAmelCase ( UpperCamelCase__ : dict , UpperCamelCase__ : YolosForObjectDetection ): """simple docstring""" for key in orig_state_dict.copy().keys(): __UpperCAmelCase = orig_state_dict.pop(A_ ) if "qkv" in key: __UpperCAmelCase = key.split('''.''' ) __UpperCAmelCase = int(key_split[2] ) __UpperCAmelCase = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: __UpperCAmelCase = val[:dim, :] __UpperCAmelCase = val[ dim : dim * 2, : ] __UpperCAmelCase = val[-dim:, :] else: __UpperCAmelCase = val[:dim] __UpperCAmelCase = val[dim : dim * 2] __UpperCAmelCase = val[-dim:] else: __UpperCAmelCase = val return orig_state_dict def lowerCAmelCase ( ): """simple docstring""" __UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __UpperCAmelCase = Image.open(requests.get(A_ , stream=A_ ).raw ) return im @torch.no_grad() def lowerCAmelCase ( UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : bool = False ): """simple docstring""" __UpperCAmelCase = get_yolos_config(A_ ) # load original state_dict __UpperCAmelCase = torch.load(A_ , map_location='''cpu''' )['''model'''] # load 🤗 model __UpperCAmelCase = YolosForObjectDetection(A_ ) model.eval() __UpperCAmelCase = convert_state_dict(A_ , A_ ) model.load_state_dict(A_ ) # Check outputs on an image, prepared by YolosImageProcessor __UpperCAmelCase = 8_0_0 if yolos_name != '''yolos_ti''' else 5_1_2 __UpperCAmelCase = YolosImageProcessor(format='''coco_detection''' , size=A_ ) __UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) __UpperCAmelCase = model(**A_ ) __UpperCAmelCase , __UpperCAmelCase = outputs.logits, outputs.pred_boxes __UpperCAmelCase , __UpperCAmelCase = None, None if yolos_name == "yolos_ti": __UpperCAmelCase = torch.tensor( [[-3_9.5_0_2_2, -1_1.9_8_2_0, -1_7.6_8_8_8], [-2_9.9_5_7_4, -9.97_69, -1_7.7_6_9_1], [-4_2.3_2_8_1, -2_0.7_2_0_0, -3_0.6_2_9_4]] ) __UpperCAmelCase = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": __UpperCAmelCase = torch.tensor( [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]] ) __UpperCAmelCase = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": __UpperCAmelCase = torch.tensor( [[-3_6.2_2_2_0, -1_4.4_3_8_5, -2_3.5_4_5_7], [-3_5.6_9_7_0, -1_4.7_5_8_3, -2_1.3_9_3_5], [-3_1.5_9_3_9, -1_3.6_0_4_2, -1_6.8_0_4_9]] ) __UpperCAmelCase = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": __UpperCAmelCase = torch.tensor( [[-4_2.8_6_6_8, -2_4.1_0_4_9, -4_1.1_6_9_0], [-3_4.7_4_5_6, -1_4.1_2_7_4, -2_4.9_1_9_4], [-3_3.7_8_9_8, -1_2.1_9_4_6, -2_5.6_4_9_5]] ) __UpperCAmelCase = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": __UpperCAmelCase = torch.tensor( [[-4_0.6_0_6_4, -2_4.3_0_8_4, -3_2.6_4_4_7], [-5_5.1_9_9_0, -3_0.7_7_1_9, -3_5.5_8_7_7], [-5_1.4_3_1_1, -3_3.3_5_0_7, -3_5.6_4_6_2]] ) __UpperCAmelCase = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(f"""Unknown yolos_name: {yolos_name}""" ) assert torch.allclose(logits[0, :3, :3] , A_ , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , A_ , atol=1E-4 ) Path(A_ ).mkdir(exist_ok=A_ ) print(f"""Saving model {yolos_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(A_ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(A_ ) if push_to_hub: __UpperCAmelCase = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print('''Pushing to the hub...''' ) __UpperCAmelCase = model_mapping[yolos_name] image_processor.push_to_hub(A_ , organization='''hustvl''' ) model.push_to_hub(A_ , organization='''hustvl''' ) if __name__ == "__main__": __lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--yolos_name", default="yolos_s_200_pre", type=str, help=( "Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre'," " 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'." ), ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original state dict (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) __lowerCAmelCase : Any = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
262
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : """simple docstring""" def __init__( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , __SCREAMING_SNAKE_CASE : List[str]=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=[1, 2, 1] , __SCREAMING_SNAKE_CASE : List[Any]=[2, 2, 4] , __SCREAMING_SNAKE_CASE : str=2 , __SCREAMING_SNAKE_CASE : Any=2.0 , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Dict=0.0 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : Any="gelu" , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : List[Any]=0.02 , __SCREAMING_SNAKE_CASE : Tuple=1e-5 , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Any=10 , __SCREAMING_SNAKE_CASE : Dict=8 , ) -> List[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =image_size __UpperCAmelCase =patch_size __UpperCAmelCase =num_channels __UpperCAmelCase =embed_dim __UpperCAmelCase =depths __UpperCAmelCase =num_heads __UpperCAmelCase =window_size __UpperCAmelCase =mlp_ratio __UpperCAmelCase =qkv_bias __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =drop_path_rate __UpperCAmelCase =hidden_act __UpperCAmelCase =use_absolute_embeddings __UpperCAmelCase =patch_norm __UpperCAmelCase =layer_norm_eps __UpperCAmelCase =initializer_range __UpperCAmelCase =is_training __UpperCAmelCase =scope __UpperCAmelCase =use_labels __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =encoder_stride def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase =None if self.use_labels: __UpperCAmelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase =self.get_config() return config, pixel_values, labels def _a ( self : List[Any] ) -> Optional[Any]: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: __UpperCAmelCase =SwinvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase =int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> Tuple: __UpperCAmelCase =SwinvaForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase =1 __UpperCAmelCase =SwinvaForMaskedImageModeling(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: __UpperCAmelCase =self.type_sequence_label_size __UpperCAmelCase =SwinvaForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self : List[str] ) -> Tuple: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[int] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCamelCase : Tuple = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowerCamelCase : Dict = False lowerCamelCase : Tuple = False lowerCamelCase : List[str] = False lowerCamelCase : Tuple = False def _a ( self : str ) -> str: __UpperCAmelCase =SwinvaModelTester(self ) __UpperCAmelCase =ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , embed_dim=37 ) def _a ( self : List[Any] ) -> Optional[int]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self : str ) -> str: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def _a ( self : Tuple ) -> Tuple: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def _a ( self : Optional[Any] ) -> int: pass def _a ( self : Tuple ) -> int: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def _a ( self : str ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase =[*signature.parameters.keys()] __UpperCAmelCase =["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =True for model_class in self.all_model_classes: __UpperCAmelCase =True __UpperCAmelCase =False __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions __UpperCAmelCase =len(self.model_tester.depths ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase =True __UpperCAmelCase =config.window_size**2 __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase =len(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __UpperCAmelCase =True __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase =self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase =2 self.assertEqual(out_len + added_hidden_states , len(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> int: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.hidden_states __UpperCAmelCase =getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # Swinv2 has a different seq_length __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase =outputs.reshaped_hidden_states self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =reshaped_hidden_states[0].shape __UpperCAmelCase =( reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self : str ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =3 __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Dict: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def _a ( self : int ) -> Dict: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase =SwinvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def _a ( self : Dict ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =_config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __UpperCAmelCase =model_class(config=__SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _A ( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self : Tuple ) -> Dict: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def _a ( self : int ) -> Optional[int]: __UpperCAmelCase =SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.default_image_processor __UpperCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase =image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE ) # verify the logits __UpperCAmelCase =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
68
0
"""simple docstring""" from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def lowercase__( __SCREAMING_SNAKE_CASE : Dict ): if isinstance(A_ , collections.abc.Iterable ): return x return (x, x) @require_tf class UpperCamelCase : def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> List[str]: '''simple docstring''' pass def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' pass def _UpperCAmelCase ( self ) -> str: '''simple docstring''' pass def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,**__UpperCamelCase ) -> List[Any]: '''simple docstring''' lowercase_ : List[Any] = VisionTextDualEncoderConfig.from_vision_text_configs(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase_ : str = TFVisionTextDualEncoderModel(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = model(input_ids=__SCREAMING_SNAKE_CASE ,pixel_values=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ) self.assertEqual(output['text_embeds'].shape ,(input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape ,(pixel_values.shape[0], config.projection_dim) ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,**__UpperCamelCase ) -> List[str]: '''simple docstring''' lowercase_ , lowercase_ : Dict = self.get_vision_text_model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = TFVisionTextDualEncoderModel(vision_model=__SCREAMING_SNAKE_CASE ,text_model=__SCREAMING_SNAKE_CASE ) lowercase_ : str = model(input_ids=__SCREAMING_SNAKE_CASE ,pixel_values=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ) self.assertEqual(output['text_embeds'].shape ,(input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape ,(pixel_values.shape[0], model.config.projection_dim) ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,**__UpperCamelCase ) -> Union[str, Any]: '''simple docstring''' lowercase_ , lowercase_ : List[str] = self.get_vision_text_model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = {'vision_model': vision_model, 'text_model': text_model} lowercase_ : str = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**__SCREAMING_SNAKE_CASE ) lowercase_ : int = model(input_ids=__SCREAMING_SNAKE_CASE ,pixel_values=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ) self.assertEqual(output['text_embeds'].shape ,(input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape ,(pixel_values.shape[0], model.config.projection_dim) ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,**__UpperCamelCase ) -> Tuple: '''simple docstring''' lowercase_ , lowercase_ : Tuple = self.get_vision_text_model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = TFVisionTextDualEncoderModel(vision_model=__SCREAMING_SNAKE_CASE ,text_model=__SCREAMING_SNAKE_CASE ) lowercase_ : str = model(input_ids=__SCREAMING_SNAKE_CASE ,pixel_values=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ) lowercase_ : str = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = TFVisionTextDualEncoderModel.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = model(input_ids=__SCREAMING_SNAKE_CASE ,pixel_values=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = after_output[0].numpy() lowercase_ : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__SCREAMING_SNAKE_CASE ,1e-5 ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,**__UpperCamelCase ) -> Optional[int]: '''simple docstring''' lowercase_ , lowercase_ : List[Any] = self.get_vision_text_model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = TFVisionTextDualEncoderModel(vision_model=__SCREAMING_SNAKE_CASE ,text_model=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = model( input_ids=__SCREAMING_SNAKE_CASE ,pixel_values=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,output_attentions=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = output.vision_model_output.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) ,vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) lowercase_ : List[Any] = to_atuple(vision_model.config.image_size ) lowercase_ : Optional[int] = to_atuple(vision_model.config.patch_size ) lowercase_ : List[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowercase_ : Union[str, Any] = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] ,(vision_config.num_attention_heads, seq_len, seq_len) ) lowercase_ : Tuple = output.text_model_output.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) ,text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] ,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) ,) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: '''simple docstring''' lowercase_ : Optional[int] = np.abs((a - b) ).max() self.assertLessEqual(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,f'''Difference between torch and flax is {diff} (>= {tol}).''' ) def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' lowercase_ : Dict = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self ) -> int: '''simple docstring''' lowercase_ : str = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' lowercase_ : Dict = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' lowercase_ : Union[str, Any] = self.prepare_config_and_inputs() self.check_save_load(**__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' lowercase_ : List[str] = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**__SCREAMING_SNAKE_CASE ) @slow def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ , lowercase_ : Any = self.get_pretrained_model_and_inputs() lowercase_ : List[str] = model_a(**__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = TFVisionTextDualEncoderModel.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = model_a(**__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = after_outputs[0].numpy() lowercase_ : List[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__SCREAMING_SNAKE_CASE ,1e-5 ) @require_tf class UpperCamelCase ( lowercase_ , unittest.TestCase ): def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ : str = TFVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' ,'hf-internal-testing/tiny-random-bert' ) lowercase_ : str = 13 lowercase_ : Dict = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowercase_ : str = ids_tensor([batch_size, 4] ,model.text_model.config.vocab_size ) lowercase_ : Dict = random_attention_mask([batch_size, 4] ) lowercase_ : Optional[Any] = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Optional[Any]: '''simple docstring''' lowercase_ : Any = TFViTModel(__SCREAMING_SNAKE_CASE ,name='vision_model' ) lowercase_ : Union[str, Any] = TFBertModel(__SCREAMING_SNAKE_CASE ,name='text_model' ) return vision_model, text_model def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' lowercase_ : str = TFViTModelTester(self ) lowercase_ : Tuple = TFBertModelTester(self ) lowercase_ : List[str] = vit_model_tester.prepare_config_and_inputs() lowercase_ : str = bert_model_tester.prepare_config_and_inputs() lowercase_ , lowercase_ , lowercase_ : Dict = vision_config_and_inputs ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : str = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class UpperCamelCase ( lowercase_ , unittest.TestCase ): def _UpperCAmelCase ( self ) -> int: '''simple docstring''' lowercase_ : Tuple = TFVisionTextDualEncoderModel.from_vision_text_pretrained( 'Rocketknight1/tiny-random-deit-tf' ,'hf-internal-testing/tiny-random-roberta' ) lowercase_ : Tuple = 13 lowercase_ : str = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowercase_ : List[Any] = ids_tensor([batch_size, 4] ,model.text_model.config.vocab_size ) lowercase_ : List[str] = random_attention_mask([batch_size, 4] ) lowercase_ : int = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,**__UpperCamelCase ) -> Dict: '''simple docstring''' lowercase_ , lowercase_ : Dict = self.get_vision_text_model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = TFVisionTextDualEncoderModel(vision_model=__SCREAMING_SNAKE_CASE ,text_model=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = model( input_ids=__SCREAMING_SNAKE_CASE ,pixel_values=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,output_attentions=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = output.vision_model_output.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) ,vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) lowercase_ : Tuple = to_atuple(vision_model.config.image_size ) lowercase_ : Optional[Any] = to_atuple(vision_model.config.patch_size ) lowercase_ : Optional[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowercase_ : Optional[Any] = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] ,(vision_config.num_attention_heads, seq_len, seq_len) ) lowercase_ : int = output.text_model_output.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) ,text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] ,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) ,) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Any: '''simple docstring''' lowercase_ : Any = TFDeiTModel(__SCREAMING_SNAKE_CASE ,name='vision_model' ) lowercase_ : Tuple = TFRobertaModel(__SCREAMING_SNAKE_CASE ,name='text_model' ) return vision_model, text_model def _UpperCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' lowercase_ : Optional[int] = TFDeiTModelTester(self ) lowercase_ : Any = TFRobertaModelTester(self ) lowercase_ : List[Any] = vit_model_tester.prepare_config_and_inputs() lowercase_ : List[Any] = bert_model_tester.prepare_config_and_inputs() lowercase_ , lowercase_ , lowercase_ : int = vision_config_and_inputs ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : List[str] = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class UpperCamelCase ( lowercase_ , unittest.TestCase ): def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ : Any = TFVisionTextDualEncoderModel.from_vision_text_pretrained( 'Rocketknight1/tiny-random-clip-tf' ,'hf-internal-testing/tiny-random-bert' ) lowercase_ : int = 13 lowercase_ : Tuple = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowercase_ : Optional[Any] = ids_tensor([batch_size, 4] ,model.text_model.config.vocab_size ) lowercase_ : List[str] = random_attention_mask([batch_size, 4] ) lowercase_ : Any = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: '''simple docstring''' lowercase_ : Any = TFCLIPVisionModel(__SCREAMING_SNAKE_CASE ,name='vision_model' ) lowercase_ : Any = TFBertModel(__SCREAMING_SNAKE_CASE ,name='text_model' ) return vision_model, text_model def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' lowercase_ : List[str] = TFCLIPVisionModelTester(self ) lowercase_ : List[Any] = TFBertModelTester(self ) lowercase_ : List[str] = clip_model_tester.prepare_config_and_inputs() lowercase_ : List[Any] = bert_model_tester.prepare_config_and_inputs() lowercase_ , lowercase_ : List[Any] = vision_config_and_inputs ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : Optional[int] = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class UpperCamelCase ( unittest.TestCase ): @slow def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' lowercase_ : Optional[Any] = TFVisionTextDualEncoderModel.from_pretrained( 'clip-italian/clip-italian' ,logit_scale_init_value=1.0 ,from_pt=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) lowercase_ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) lowercase_ : Any = processor( text=['una foto di un gatto', 'una foto di un cane'] ,images=__SCREAMING_SNAKE_CASE ,padding=__SCREAMING_SNAKE_CASE ,return_tensors='np' ) lowercase_ : Union[str, Any] = model(**__SCREAMING_SNAKE_CASE ) # verify the logits self.assertEqual(outputs.logits_per_image.shape ,(inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape ,(inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) ,) lowercase_ : List[Any] = np.array([[1.228_4727, 0.310_4122]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() ,__SCREAMING_SNAKE_CASE ,atol=1e-3 ) )
425
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A = logging.get_logger(__name__) __A = {"vocab_file": "spiece.model"} __A = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } __A = { "AI-Sweden/gpt-sw3-126m": 20_48, "AI-Sweden/gpt-sw3-350m": 20_48, "AI-Sweden/gpt-sw3-1.6b": 20_48, "AI-Sweden/gpt-sw3-6.7b": 20_48, "AI-Sweden/gpt-sw3-20b": 20_48, } class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : int = VOCAB_FILES_NAMES lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : List[str]=False , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Optional[Dict[str, Any]] = None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> None: __UpperCAmelCase ={} if sp_model_kwargs is None else sp_model_kwargs __UpperCAmelCase =kwargs.get("""name_or_path""" ) if name_or_path is None: logger.warning( """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,""" """ you are testing the model, this can safely be ignored""" ) __UpperCAmelCase ="""None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __UpperCAmelCase ="""<|endoftext|>""" if eos_token is None else eos_token __UpperCAmelCase ="""<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __UpperCAmelCase =unk_token if pad_token is None else pad_token __UpperCAmelCase =eos_token if bos_token is None else bos_token else: __UpperCAmelCase ="""<pad>""" if pad_token is None else pad_token __UpperCAmelCase ="""<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=__SCREAMING_SNAKE_CASE , remove_space=__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) __UpperCAmelCase =do_lower_case __UpperCAmelCase =remove_space __UpperCAmelCase =keep_accents __UpperCAmelCase =vocab_file __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) # Used for whitespace normalization in input texts # fmt : off __UpperCAmelCase ={""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __UpperCAmelCase =re.compile( f'''[{"".join(map(__SCREAMING_SNAKE_CASE , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self : Any ) -> str: __UpperCAmelCase =self.__dict__.copy() __UpperCAmelCase =None return state def __setstate__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: __UpperCAmelCase =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __UpperCAmelCase ={} __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def _a ( self : Union[str, Any] ) -> int: return len(self.sp_model ) def _a ( self : Dict , __SCREAMING_SNAKE_CASE : str ) -> str: __UpperCAmelCase =self.non_printing_characters_re.sub("""""" , __SCREAMING_SNAKE_CASE ) # Normalize whitespaces __UpperCAmelCase ="""""".join([char if char not in self.whitespaces else """ """ for char in text] ) # NFC Unicode normalization __UpperCAmelCase =unicodedata.normalize("""NFC""" , __SCREAMING_SNAKE_CASE ) return text def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str ) -> int: return self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : int ) -> str: return self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) @staticmethod def _a ( __SCREAMING_SNAKE_CASE : str ) -> str: return out_string def _a ( self : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> str: __UpperCAmelCase =[] __UpperCAmelCase ="""""" __UpperCAmelCase =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token __UpperCAmelCase =True __UpperCAmelCase =[] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =False out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string def _a ( self : Any ) -> Dict[str, int]: __UpperCAmelCase ={self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __UpperCAmelCase =os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , """wb""" ) as fi: __UpperCAmelCase =self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, List[str]] , __SCREAMING_SNAKE_CASE : Union[str, bool] = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) else: __UpperCAmelCase =[self.preprocess_text(__SCREAMING_SNAKE_CASE ) for t in text] __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) if return_tensors is True or return_tensors == "pt": __UpperCAmelCase =torch.tensor(__SCREAMING_SNAKE_CASE ) return token_ids def _a ( self : str , __SCREAMING_SNAKE_CASE : Union[int, List[int]] ) -> str: return self.sp_model.decode(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : "Conversation" ) -> List[int]: __UpperCAmelCase =[f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __UpperCAmelCase =( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(__SCREAMING_SNAKE_CASE ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=__SCREAMING_SNAKE_CASE )
68
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCamelCase_ : Tuple = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : List[Any] = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : Tuple = ['''CLIPFeatureExtractor'''] UpperCamelCase_ : Dict = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : Optional[int] = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : str = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : Any = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys UpperCamelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
115
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __A = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : Union[str, None] = None , __SCREAMING_SNAKE_CASE : Union[List[str], None] = None , __SCREAMING_SNAKE_CASE : Union[str, List[str], None] = None , __SCREAMING_SNAKE_CASE : bool = True , ) -> List[str]: __UpperCAmelCase =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )] if identifier is not None: __UpperCAmelCase =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n_ in n_identifier: __UpperCAmelCase =[file for file in files if n_ not in file] else: __UpperCAmelCase =[file for file in files if n_identifier not in file] __UpperCAmelCase =ignore_files or [] ignore_files.append("""__init__.py""" ) __UpperCAmelCase =[file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , __SCREAMING_SNAKE_CASE ) if only_modules: __UpperCAmelCase =file.split(""".""" )[0] try: __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: __UpperCAmelCase =doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _a ( self : Optional[Any] ) -> List[str]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""modeling""" __UpperCAmelCase =[ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""tokenization""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] ) -> Optional[Any]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""configuration""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : List[Any] ) -> Tuple: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase =["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase =Path("""docs/source""" ) __UpperCAmelCase =["""favicon.ico"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
68
0
__snake_case :Optional[int] ={ 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'datasets': 'datasets!=2.5.0', 'decord': 'decord==0.6.0', 'deepspeed': 'deepspeed>=0.9.3', 'diffusers': 'diffusers', 'dill': 'dill<0.3.5', 'evaluate': 'evaluate>=0.2.0', 'fairscale': 'fairscale>0.3', 'faiss-cpu': 'faiss-cpu', 'fastapi': 'fastapi', 'filelock': 'filelock', 'flax': 'flax>=0.4.1,<=0.7.0', 'ftfy': 'ftfy', 'fugashi': 'fugashi>=1.0', 'GitPython': 'GitPython<3.1.19', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0', 'importlib_metadata': 'importlib_metadata', 'ipadic': 'ipadic>=1.0.0,<2.0', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13', 'jaxlib': 'jaxlib>=0.1.65,<=0.4.13', 'jieba': 'jieba', 'kenlm': 'kenlm', 'keras-nlp': 'keras-nlp>=0.3.1', 'librosa': 'librosa', 'nltk': 'nltk', 'natten': 'natten>=0.14.6', 'numpy': 'numpy>=1.17', 'onnxconverter-common': 'onnxconverter-common', 'onnxruntime-tools': 'onnxruntime-tools>=1.4.2', 'onnxruntime': 'onnxruntime>=1.4.0', 'opencv-python': 'opencv-python', 'optuna': 'optuna', 'optax': 'optax>=0.0.8,<=0.1.4', 'packaging': 'packaging>=20.0', 'parameterized': 'parameterized', 'phonemizer': 'phonemizer', 'protobuf': 'protobuf', 'psutil': 'psutil', 'pyyaml': 'pyyaml>=5.1', 'pydantic': 'pydantic<2', 'pytest': 'pytest>=7.2.0', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'python': 'python>=3.8.0', 'ray[tune]': 'ray[tune]', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'rhoknp': 'rhoknp>=1.1.0,<1.3.1', 'rjieba': 'rjieba', 'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1', 'ruff': 'ruff>=0.0.241,<=0.0.259', 'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0', 'sacremoses': 'sacremoses', 'safetensors': 'safetensors>=0.3.1', 'sagemaker': 'sagemaker>=2.31.0', 'scikit-learn': 'scikit-learn', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'sigopt': 'sigopt', 'starlette': 'starlette', 'sudachipy': 'sudachipy>=0.6.6', 'sudachidict_core': 'sudachidict_core>=20220729', 'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14', 'tensorflow': 'tensorflow>=2.6,<2.14', 'tensorflow-text': 'tensorflow-text<2.14', 'tf2onnx': 'tf2onnx', 'timeout-decorator': 'timeout-decorator', 'timm': 'timm', 'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14', 'torch': 'torch>=1.9,!=1.12.0', 'torchaudio': 'torchaudio', 'torchvision': 'torchvision', 'pyctcdecode': 'pyctcdecode>=0.4.0', 'tqdm': 'tqdm>=4.27', 'unidic': 'unidic>=1.0.2', 'unidic_lite': 'unidic_lite>=1.0.7', 'urllib3': 'urllib3<2.0.0', 'uvicorn': 'uvicorn', }
106
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __A = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def lowercase__ ( A_: int , A_: Optional[Any] , A_: List[str]=None ) -> List[str]: """simple docstring""" if rng is None: __UpperCAmelCase =random.Random() __UpperCAmelCase =1 for dim in shape: total_dims *= dim __UpperCAmelCase =[] for _ in range(A_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __UpperCAmelCase =np.array(A_ , dtype=jnp.intaa ).reshape(A_ ) return output def lowercase__ ( A_: List[str] , A_: List[str]=None ) -> Any: """simple docstring""" __UpperCAmelCase =ids_tensor(A_ , vocab_size=2 , rng=A_ ) # make sure that at least one token is attended to for each batch __UpperCAmelCase =1 return attn_mask @require_flax class _A : """simple docstring""" lowerCamelCase : Optional[Any] = None lowerCamelCase : int = () def _a ( self : str ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __UpperCAmelCase =2 __UpperCAmelCase =inputs["""input_ids"""].shape[-1] // 2 __UpperCAmelCase =inputs["""input_ids"""][:max_batch_size, :sequence_length] __UpperCAmelCase =jnp.ones_like(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __UpperCAmelCase =input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __UpperCAmelCase =config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _a ( self : Union[str, Any] ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =0 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model_class.__name__[4:] # Skip the "Flax" at the beginning __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =pt_model_class(__SCREAMING_SNAKE_CASE ).eval() __UpperCAmelCase =load_flax_weights_in_pytorch_model(__SCREAMING_SNAKE_CASE , flax_model.params ) __UpperCAmelCase =flax_model.generate(__SCREAMING_SNAKE_CASE ).sequences __UpperCAmelCase =pt_model.generate(torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __UpperCAmelCase =flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[Any] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _a ( self : Union[str, Any] ) -> List[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length __UpperCAmelCase =0.8 __UpperCAmelCase =10 __UpperCAmelCase =0.3 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[str] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =2 __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : int ) -> Any: __UpperCAmelCase =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) __UpperCAmelCase =FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) __UpperCAmelCase ="""Hello world""" __UpperCAmelCase =tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """do_samples""" ): model.generate(__SCREAMING_SNAKE_CASE , do_samples=__SCREAMING_SNAKE_CASE ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """foo""" ): __UpperCAmelCase ={"""foo""": """bar"""} model.generate(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
68
0
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch lowerCAmelCase_ = logging.get_logger(__name__) class __A ( A_ ): '''simple docstring''' lowerCAmelCase : Optional[int] = ['pixel_values'] def __init__( self : Optional[Any] ,_snake_case : bool = True ,_snake_case : Dict[str, int] = None ,_snake_case : PILImageResampling = PILImageResampling.BILINEAR ,_snake_case : bool = True ,_snake_case : Union[int, float] = 1 / 255 ,_snake_case : bool = True ,_snake_case : Dict[str, int] = None ,_snake_case : bool = True ,**_snake_case : List[Any] ,) -> None: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase__ : List[Any] = size if size is not None else {'''shortest_edge''': 224} lowercase__ : Optional[int] = get_size_dict(__SCREAMING_SNAKE_CASE ,default_to_square=__SCREAMING_SNAKE_CASE ) lowercase__ : Any = crop_size if crop_size is not None else {'''height''': 256, '''width''': 256} lowercase__ : str = get_size_dict(__SCREAMING_SNAKE_CASE ,param_name='''crop_size''' ) lowercase__ : Dict = do_resize lowercase__ : str = size lowercase__ : Any = resample lowercase__ : Optional[int] = do_rescale lowercase__ : List[str] = rescale_factor lowercase__ : Union[str, Any] = do_center_crop lowercase__ : Optional[int] = crop_size lowercase__ : List[str] = do_flip_channel_order def UpperCAmelCase ( self : str ,_snake_case : np.ndarray ,_snake_case : Dict[str, int] ,_snake_case : PILImageResampling = PIL.Image.BILINEAR ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : Optional[Any] ,) -> np.ndarray: """simple docstring""" lowercase__ : Union[str, Any] = get_size_dict(__SCREAMING_SNAKE_CASE ,default_to_square=__SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) lowercase__ : List[Any] = get_resize_output_image_size(__SCREAMING_SNAKE_CASE ,size=size['''shortest_edge'''] ,default_to_square=__SCREAMING_SNAKE_CASE ) return resize(__SCREAMING_SNAKE_CASE ,size=__SCREAMING_SNAKE_CASE ,resample=__SCREAMING_SNAKE_CASE ,data_format=__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Optional[Any] ,_snake_case : np.ndarray ,_snake_case : Dict[str, int] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : List[str] ,) -> np.ndarray: """simple docstring""" lowercase__ : int = get_size_dict(__SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) return center_crop(__SCREAMING_SNAKE_CASE ,size=(size['''height'''], size['''width''']) ,data_format=__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Tuple ,_snake_case : np.ndarray ,_snake_case : Union[int, float] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : Tuple ,) -> Any: """simple docstring""" return rescale(__SCREAMING_SNAKE_CASE ,scale=__SCREAMING_SNAKE_CASE ,data_format=__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : List[str] ,_snake_case : np.ndarray ,_snake_case : Optional[Union[str, ChannelDimension]] = None ) -> np.ndarray: """simple docstring""" return flip_channel_order(__SCREAMING_SNAKE_CASE ,data_format=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Dict ,_snake_case : ImageInput ,_snake_case : bool = None ,_snake_case : Dict[str, int] = None ,_snake_case : PILImageResampling = None ,_snake_case : bool = None ,_snake_case : float = None ,_snake_case : bool = None ,_snake_case : Dict[str, int] = None ,_snake_case : bool = None ,_snake_case : Optional[Union[str, TensorType]] = None ,_snake_case : ChannelDimension = ChannelDimension.FIRST ,**_snake_case : Optional[Any] ,) -> PIL.Image.Image: """simple docstring""" lowercase__ : Optional[int] = do_resize if do_resize is not None else self.do_resize lowercase__ : Tuple = resample if resample is not None else self.resample lowercase__ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale lowercase__ : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase__ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase__ : Optional[Any] = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) lowercase__ : Union[str, Any] = size if size is not None else self.size lowercase__ : int = get_size_dict(__SCREAMING_SNAKE_CASE ,default_to_square=__SCREAMING_SNAKE_CASE ) lowercase__ : Dict = crop_size if crop_size is not None else self.crop_size lowercase__ : List[str] = get_size_dict(__SCREAMING_SNAKE_CASE ,param_name='''crop_size''' ) lowercase__ : Union[str, Any] = make_list_of_images(__SCREAMING_SNAKE_CASE ) if not valid_images(__SCREAMING_SNAKE_CASE ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) # All transformations expect numpy arrays. lowercase__ : str = [to_numpy_array(__SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowercase__ : Optional[int] = [self.resize(image=__SCREAMING_SNAKE_CASE ,size=__SCREAMING_SNAKE_CASE ,resample=__SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowercase__ : Tuple = [self.center_crop(image=__SCREAMING_SNAKE_CASE ,size=__SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowercase__ : Union[str, Any] = [self.rescale(image=__SCREAMING_SNAKE_CASE ,scale=__SCREAMING_SNAKE_CASE ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: lowercase__ : Dict = [self.flip_channel_order(image=__SCREAMING_SNAKE_CASE ) for image in images] lowercase__ : Any = [to_channel_dimension_format(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) for image in images] lowercase__ : Union[str, Any] = {'''pixel_values''': images} return BatchFeature(data=__SCREAMING_SNAKE_CASE ,tensor_type=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Any ,_snake_case : Dict ,_snake_case : List[Tuple] = None ) -> Union[str, Any]: """simple docstring""" lowercase__ : Optional[Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(__SCREAMING_SNAKE_CASE ): lowercase__ : Dict = target_sizes.numpy() lowercase__ : List[Any] = [] for idx in range(len(__SCREAMING_SNAKE_CASE ) ): lowercase__ : Any = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) ,size=target_sizes[idx] ,mode='''bilinear''' ,align_corners=__SCREAMING_SNAKE_CASE ) lowercase__ : Any = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__SCREAMING_SNAKE_CASE ) else: lowercase__ : Tuple = logits.argmax(dim=1 ) lowercase__ : Any = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
560
from __future__ import annotations from collections.abc import Iterator class _A : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : int ) -> None: __UpperCAmelCase =value __UpperCAmelCase =None __UpperCAmelCase =None class _A : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Node ) -> None: __UpperCAmelCase =tree def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : int ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors a__ : Optional[int] = logging.getLogger(__name__) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ='sequence-classification' def __init__( self : Dict , a__ : Tuple ): if type(__SCREAMING_SNAKE_CASE ) == dict: UpperCAmelCase = Namespace(**__SCREAMING_SNAKE_CASE ) UpperCAmelCase = glue_output_modes[hparams.task] UpperCAmelCase = glue_tasks_num_labels[hparams.task] super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.mode ) def __snake_case ( self : str , **a__ : Dict ): return self.model(**__SCREAMING_SNAKE_CASE ) def __snake_case ( self : Tuple , a__ : Union[str, Any] , a__ : Dict ): UpperCAmelCase = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]} if self.config.model_type not in ["distilbert", "bart"]: UpperCAmelCase = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None UpperCAmelCase = self(**__SCREAMING_SNAKE_CASE ) UpperCAmelCase = outputs[0] UpperCAmelCase = self.trainer.lr_schedulers[0]['''scheduler'''] UpperCAmelCase = {'''loss''': loss, '''rate''': lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def __snake_case ( self : Tuple ): UpperCAmelCase = self.hparams UpperCAmelCase = processors[args.task]() UpperCAmelCase = processor.get_labels() for mode in ["train", "dev"]: UpperCAmelCase = self._feature_file(__SCREAMING_SNAKE_CASE ) if os.path.exists(__SCREAMING_SNAKE_CASE ) and not args.overwrite_cache: logger.info('''Loading features from cached file %s''' , __SCREAMING_SNAKE_CASE ) else: logger.info('''Creating features from dataset file at %s''' , args.data_dir ) UpperCAmelCase = ( processor.get_dev_examples(args.data_dir ) if mode == '''dev''' else processor.get_train_examples(args.data_dir ) ) UpperCAmelCase = convert_examples_to_features( __SCREAMING_SNAKE_CASE , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info('''Saving features into cached file %s''' , __SCREAMING_SNAKE_CASE ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __snake_case ( self : List[str] , a__ : str , a__ : int , a__ : bool = False ): UpperCAmelCase = '''dev''' if mode == '''test''' else mode UpperCAmelCase = self._feature_file(__SCREAMING_SNAKE_CASE ) logger.info('''Loading features from cached file %s''' , __SCREAMING_SNAKE_CASE ) UpperCAmelCase = torch.load(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) UpperCAmelCase = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) UpperCAmelCase = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": UpperCAmelCase = torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": UpperCAmelCase = torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , batch_size=__SCREAMING_SNAKE_CASE , shuffle=__SCREAMING_SNAKE_CASE , ) def __snake_case ( self : Any , a__ : Optional[Any] , a__ : int ): UpperCAmelCase = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]} if self.config.model_type not in ["distilbert", "bart"]: UpperCAmelCase = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None UpperCAmelCase = self(**__SCREAMING_SNAKE_CASE ) UpperCAmelCase, UpperCAmelCase = outputs[:2] UpperCAmelCase = logits.detach().cpu().numpy() UpperCAmelCase = inputs['''labels'''].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def __snake_case ( self : Tuple , a__ : Any ): UpperCAmelCase = torch.stack([x['''val_loss'''] for x in outputs] ).mean().detach().cpu().item() UpperCAmelCase = np.concatenate([x['''pred'''] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": UpperCAmelCase = np.argmax(__SCREAMING_SNAKE_CASE , axis=1 ) elif self.hparams.glue_output_mode == "regression": UpperCAmelCase = np.squeeze(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = np.concatenate([x['''target'''] for x in outputs] , axis=0 ) UpperCAmelCase = [[] for _ in range(out_label_ids.shape[0] )] UpperCAmelCase = [[] for _ in range(out_label_ids.shape[0] )] UpperCAmelCase = {**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} UpperCAmelCase = dict(results.items() ) UpperCAmelCase = results return ret, preds_list, out_label_list def __snake_case ( self : Tuple , a__ : list ): UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = self._eval_end(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = ret['''log'''] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def __snake_case ( self : Tuple , a__ : List[str] ): UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = self._eval_end(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = ret['''log'''] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def __snake_case ( a__ : List[Any] , a__ : Dict ): BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) parser.add_argument( '''--max_seq_length''' , default=128 , type=__SCREAMING_SNAKE_CASE , help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) , ) parser.add_argument( '''--task''' , default='''''' , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help='''The GLUE task to run''' , ) parser.add_argument( '''--gpus''' , default=0 , type=__SCREAMING_SNAKE_CASE , help='''The number of GPUs allocated for this, it is by default 0 meaning none''' , ) parser.add_argument( '''--overwrite_cache''' , action='''store_true''' , help='''Overwrite the cached training and evaluation sets''' ) return parser def __snake_case ( ) -> str: """simple docstring""" UpperCAmelCase = argparse.ArgumentParser() add_generic_args(A_ , os.getcwd() ) UpperCAmelCase = GLUETransformer.add_model_specific_args(A_ , os.getcwd() ) UpperCAmelCase = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: UpperCAmelCase = os.path.join( '''./results''' , f"{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}" , ) os.makedirs(args.output_dir ) UpperCAmelCase = GLUETransformer(A_ ) UpperCAmelCase = generic_train(A_ , A_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: UpperCAmelCase = sorted(glob.glob(os.path.join(args.output_dir , '''checkpoint-epoch=*.ckpt''' ) , recursive=A_ ) ) UpperCAmelCase = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(A_ ) if __name__ == "__main__": main()
51
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def lowercase__ ( A_: Union[str, Any] ) -> List[Any]: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=A_ , AssumeRolePolicyDocument=json.dumps(A_ , indent=2 ) ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=A_ , PolicyName=F'''{role_name}_policy_permission''' , PolicyDocument=json.dumps(A_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F'''role {role_name} already exists. Using existing one''' ) def lowercase__ ( A_: Dict ) -> Any: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) return iam_client.get_role(RoleName=A_ )["Role"]["Arn"] def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase =_ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , A_ , ) __UpperCAmelCase =None if credentials_configuration == 0: __UpperCAmelCase =_ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) __UpperCAmelCase =aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __UpperCAmelCase =_ask_field("""AWS Access Key ID: """ ) __UpperCAmelCase =aws_access_key_id __UpperCAmelCase =_ask_field("""AWS Secret Access Key: """ ) __UpperCAmelCase =aws_secret_access_key __UpperCAmelCase =_ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) __UpperCAmelCase =aws_region __UpperCAmelCase =_ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , A_ , ) if role_management == 0: __UpperCAmelCase =_ask_field("""Enter your IAM role name: """ ) else: __UpperCAmelCase ="""accelerate_sagemaker_execution_role""" print(F'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(A_ ) __UpperCAmelCase =_ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_custom_docker_image: __UpperCAmelCase =_ask_field("""Enter your Docker image: """ , lambda A_ : str(A_ ).lower() ) __UpperCAmelCase =_ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_inputs_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_metrics_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) __UpperCAmelCase ={} __UpperCAmelCase =_ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_dynamo: __UpperCAmelCase ="""dynamo_""" __UpperCAmelCase =_ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __UpperCAmelCase =_ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_custom_options: __UpperCAmelCase =_ask_options( """Which mode do you want to use?""" , A_ , lambda A_ : TORCH_DYNAMO_MODES[int(A_ )] , default="""default""" , ) __UpperCAmelCase =_ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =_ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase ="""Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __UpperCAmelCase =_ask_options( A_ , A_ , lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __UpperCAmelCase =_ask_field(A_ , lambda A_ : str(A_ ).lower() , default="""ml.p3.2xlarge""" ) __UpperCAmelCase =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __UpperCAmelCase =_ask_field( """How many machines do you want use? [1]: """ , A_ , default=1 , ) __UpperCAmelCase =_ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=A_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=A_ , use_cpu=A_ , dynamo_config=A_ , eca_instance_type=A_ , profile=A_ , region=A_ , iam_role_name=A_ , mixed_precision=A_ , num_machines=A_ , sagemaker_inputs_file=A_ , sagemaker_metrics_file=A_ , )
68
0
"""simple docstring""" import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _lowerCAmelCase : def __init__( self , a_ , a_=13 , a_=32 , a_=2 , a_=3 , a_=16 , a_=[1, 2, 1] , a_=[2, 2, 4] , a_=2 , a_=2.0 , a_=True , a_=0.0 , a_=0.0 , a_=0.1 , a_="gelu" , a_=False , a_=True , a_=0.02 , a_=1e-5 , a_=True , a_=None , a_=True , a_=10 , a_=8 , ) -> List[Any]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = embed_dim _UpperCAmelCase = depths _UpperCAmelCase = num_heads _UpperCAmelCase = window_size _UpperCAmelCase = mlp_ratio _UpperCAmelCase = qkv_bias _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = drop_path_rate _UpperCAmelCase = hidden_act _UpperCAmelCase = use_absolute_embeddings _UpperCAmelCase = patch_norm _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = initializer_range _UpperCAmelCase = is_training _UpperCAmelCase = scope _UpperCAmelCase = use_labels _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = encoder_stride def _a ( self ) -> Optional[int]: _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def _a ( self ) -> Optional[Any]: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self , a_ , a_ , a_ ) -> Optional[int]: _UpperCAmelCase = SwinvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _UpperCAmelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self , a_ , a_ , a_ ) -> Tuple: _UpperCAmelCase = SwinvaForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _UpperCAmelCase = 1 _UpperCAmelCase = SwinvaForMaskedImageModeling(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self , a_ , a_ , a_ ) -> Tuple: _UpperCAmelCase = self.type_sequence_label_size _UpperCAmelCase = SwinvaForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ) -> Tuple: _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Optional[int] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowercase_ : Tuple = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowercase_ : Dict = False lowercase_ : Tuple = False lowercase_ : List[str] = False lowercase_ : Tuple = False def _a ( self ) -> str: _UpperCAmelCase = SwinvaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , embed_dim=37 ) def _a ( self ) -> Optional[int]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ) -> str: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0." ) def _a ( self ) -> Tuple: pass @unittest.skip(reason="Swinv2 does not use inputs_embeds" ) def _a ( self ) -> int: pass def _a ( self ) -> int: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def _a ( self ) -> List[str]: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(__SCREAMING_SNAKE_CASE ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def _a ( self ) -> Tuple: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = True for model_class in self.all_model_classes: _UpperCAmelCase = True _UpperCAmelCase = False _UpperCAmelCase = True _UpperCAmelCase = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.attentions _UpperCAmelCase = len(self.model_tester.depths ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _UpperCAmelCase = True _UpperCAmelCase = config.window_size**2 _UpperCAmelCase = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) _UpperCAmelCase = len(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine _UpperCAmelCase = True _UpperCAmelCase = True _UpperCAmelCase = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if hasattr(self.model_tester , "num_hidden_states_types" ): _UpperCAmelCase = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states _UpperCAmelCase = 2 self.assertEqual(out_len + added_hidden_states , len(__SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def _a ( self , a_ , a_ , a_ , a_ ) -> int: _UpperCAmelCase = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # Swinv2 has a different seq_length _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) _UpperCAmelCase = outputs.reshaped_hidden_states self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = reshaped_hidden_states[0].shape _UpperCAmelCase = ( reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self ) -> Tuple: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = 3 _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _UpperCAmelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) def _a ( self ) -> Tuple: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE ) def _a ( self ) -> Dict: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def _a ( self ) -> Dict: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = SwinvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = _config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: _UpperCAmelCase = model_class(config=__SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @require_vision @require_torch class _lowerCAmelCase ( unittest.TestCase ): @cached_property def _a ( self ) -> Dict: return ( AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ) if is_vision_available() else None ) @slow def _a ( self ) -> Optional[int]: _UpperCAmelCase = SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ).to( __SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) _UpperCAmelCase = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="pt" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _UpperCAmelCase = model(**__SCREAMING_SNAKE_CASE ) # verify the logits _UpperCAmelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
657
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Tuple = 'ctrl' lowerCamelCase : Any = ['past_key_values'] lowerCamelCase : Optional[int] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=246534 , __SCREAMING_SNAKE_CASE : int=256 , __SCREAMING_SNAKE_CASE : Optional[Any]=1280 , __SCREAMING_SNAKE_CASE : Optional[Any]=8192 , __SCREAMING_SNAKE_CASE : int=48 , __SCREAMING_SNAKE_CASE : Union[str, Any]=16 , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : List[Any]=1e-6 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : Union[str, Any]=True , **__SCREAMING_SNAKE_CASE : int , ) -> Any: __UpperCAmelCase =vocab_size __UpperCAmelCase =n_positions __UpperCAmelCase =n_embd __UpperCAmelCase =n_layer __UpperCAmelCase =n_head __UpperCAmelCase =dff __UpperCAmelCase =resid_pdrop __UpperCAmelCase =embd_pdrop __UpperCAmelCase =layer_norm_epsilon __UpperCAmelCase =initializer_range __UpperCAmelCase =use_cache super().__init__(**__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _a( UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : NDArray[floataa], UpperCamelCase__ : list[int], UpperCamelCase__ : int, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : int =f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(A_ ) if colsa != 1: SCREAMING_SNAKE_CASE__ : Tuple =f"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(A_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] =( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' f"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(A_ ) if len(A_ ) != rowsa: SCREAMING_SNAKE_CASE__ : List[str] =( '''Number of initial values must be equal to number of rows in coefficient ''' f"matrix but received {len(A_ )} and {rowsa}" ) raise ValueError(A_ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple =table.shape strictly_diagonally_dominant(A_ ) # Iterates the whole matrix for given number of times for _ in range(A_ ): SCREAMING_SNAKE_CASE__ : List[str] =[] for row in range(A_ ): SCREAMING_SNAKE_CASE__ : int =0 for col in range(A_ ): if col == row: SCREAMING_SNAKE_CASE__ : int =table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Any =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Optional[int] =(temp + val) / denom new_val.append(A_ ) SCREAMING_SNAKE_CASE__ : Any =new_val return [float(A_ ) for i in new_val] def _a( UpperCamelCase__ : NDArray[floataa] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =table.shape SCREAMING_SNAKE_CASE__ : Optional[int] =True for i in range(0, A_ ): SCREAMING_SNAKE_CASE__ : int =0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
296
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = [ ["attention", "attn"], ["encoder_attention", "encoder_attn"], ["q_lin", "q_proj"], ["k_lin", "k_proj"], ["v_lin", "v_proj"], ["out_lin", "out_proj"], ["norm_embeddings", "layernorm_embedding"], ["position_embeddings", "embed_positions"], ["embeddings", "embed_tokens"], ["ffn.lin", "fc"], ] def lowercase__ ( A_: Optional[Any] ) -> Union[str, Any]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __UpperCAmelCase =k.replace(A_ , A_ ) if k.startswith("""encoder""" ): __UpperCAmelCase =k.replace(""".attn""" , """.self_attn""" ) __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """encoder_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm3""" , """final_layer_norm""" ) return k def lowercase__ ( A_: Tuple ) -> str: """simple docstring""" __UpperCAmelCase =[ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: __UpperCAmelCase =sd.pop(A_ ) __UpperCAmelCase =k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd __UpperCAmelCase =v __A = ["START"] @torch.no_grad() def lowercase__ ( A_: List[Any] , A_: str , A_: int ) -> Optional[int]: """simple docstring""" __UpperCAmelCase =torch.load(A_ , map_location="""cpu""" ) __UpperCAmelCase =model["""model"""] __UpperCAmelCase =BlenderbotConfig.from_json_file(A_ ) __UpperCAmelCase =BlenderbotForConditionalGeneration(A_ ) __UpperCAmelCase =m.model.state_dict().keys() __UpperCAmelCase =[] __UpperCAmelCase ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue __UpperCAmelCase =rename_state_dict_key(A_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __UpperCAmelCase =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(A_ ) m.model.load_state_dict(A_ , strict=A_ ) m.half() m.save_pretrained(A_ ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin") parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.") parser.add_argument( "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use" ) __A = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
68
0
"""simple docstring""" from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline A = logging.get_logger(__name__) class _a ( SCREAMING_SNAKE_CASE__): def __lowercase ( self : List[Any] , _lowercase : Union[str, Any] ) -> Tuple: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case : Union[str, Any] = [label.strip() for label in labels.split("," ) if label.strip()] return labels def __call__( self : Any , _lowercase : int , _lowercase : Tuple , _lowercase : List[Any] ) -> Dict: if len(__SCREAMING_SNAKE_CASE ) == 0 or len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError("You must include at least one label and at least one sequence." ) if hypothesis_template.format(labels[0] ) == hypothesis_template: raise ValueError( ( "The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. " "Make sure the passed template includes formatting syntax such as {{}} where the label should go." ).format(__SCREAMING_SNAKE_CASE ) ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case : List[Any] = [sequences] snake_case : Dict = [] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(__SCREAMING_SNAKE_CASE )] for label in labels] ) return sequence_pairs, sequences @add_end_docstrings(SCREAMING_SNAKE_CASE__) class _a ( SCREAMING_SNAKE_CASE__): def __init__( self : Optional[int] , _lowercase : Tuple=ZeroShotClassificationArgumentHandler() , *_lowercase : str , **_lowercase : Any ) -> List[str]: snake_case : Tuple = args_parser super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if self.entailment_id == -1: logger.warning( "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to " "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs." ) @property def __lowercase ( self : Any ) -> Optional[int]: for label, ind in self.model.config.labelaid.items(): if label.lower().startswith("entail" ): return ind return -1 def __lowercase ( self : int , _lowercase : str , _lowercase : Union[str, Any]=True , _lowercase : List[Any]=True , _lowercase : Optional[int]=TruncationStrategy.ONLY_FIRST , **_lowercase : Optional[Any] ) -> Tuple: snake_case : int = self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( "Tokenizer was not supporting padding necessary for zero-shot, attempting to use " " `pad_token=eos_token`" ) snake_case : Optional[Any] = self.tokenizer.eos_token try: snake_case : str = self.tokenizer( __SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , ) except Exception as e: if "too short" in str(__SCREAMING_SNAKE_CASE ): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. snake_case : Optional[int] = self.tokenizer( __SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=TruncationStrategy.DO_NOT_TRUNCATE , ) else: raise e return inputs def __lowercase ( self : Tuple , **_lowercase : Dict ) -> Optional[int]: if kwargs.get("multi_class" , __SCREAMING_SNAKE_CASE ) is not None: snake_case : Any = kwargs["multi_class"] logger.warning( "The `multi_class` argument has been deprecated and renamed to `multi_label`. " "`multi_class` will be removed in a future version of Transformers." ) snake_case : List[Any] = {} if "candidate_labels" in kwargs: snake_case : Tuple = self._args_parser._parse_labels(kwargs["candidate_labels"] ) if "hypothesis_template" in kwargs: snake_case : Any = kwargs["hypothesis_template"] snake_case : Any = {} if "multi_label" in kwargs: snake_case : Optional[Any] = kwargs["multi_label"] return preprocess_params, {}, postprocess_params def __call__( self : int , _lowercase : Union[str, List[str]] , *_lowercase : List[str] , **_lowercase : Optional[int] , ) -> List[Any]: if len(__SCREAMING_SNAKE_CASE ) == 0: pass elif len(__SCREAMING_SNAKE_CASE ) == 1 and "candidate_labels" not in kwargs: snake_case : List[str] = args[0] else: raise ValueError(F'''Unable to understand extra arguments {args}''' ) return super().__call__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def __lowercase ( self : Tuple , _lowercase : Dict , _lowercase : Dict=None , _lowercase : Optional[int]="This example is {}." ) -> Optional[Any]: snake_case , snake_case : List[str] = self._args_parser(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i, (candidate_label, sequence_pair) in enumerate(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ): snake_case : Dict = self._parse_and_tokenize([sequence_pair] ) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(__SCREAMING_SNAKE_CASE ) - 1, **model_input, } def __lowercase ( self : Optional[Any] , _lowercase : List[Any] ) -> str: snake_case : int = inputs["candidate_label"] snake_case : Dict = inputs["sequence"] snake_case : Optional[Any] = {k: inputs[k] for k in self.tokenizer.model_input_names} snake_case : Union[str, Any] = self.model(**__SCREAMING_SNAKE_CASE ) snake_case : Dict = { "candidate_label": candidate_label, "sequence": sequence, "is_last": inputs["is_last"], **outputs, } return model_outputs def __lowercase ( self : Optional[int] , _lowercase : int , _lowercase : Any=False ) -> List[Any]: snake_case : List[Any] = [outputs["candidate_label"] for outputs in model_outputs] snake_case : Dict = [outputs["sequence"] for outputs in model_outputs] snake_case : List[str] = np.concatenate([output["logits"].numpy() for output in model_outputs] ) snake_case : Optional[int] = logits.shape[0] snake_case : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) snake_case : int = N // n snake_case : str = logits.reshape((num_sequences, n, -1) ) if multi_label or len(__SCREAMING_SNAKE_CASE ) == 1: # softmax over the entailment vs. contradiction dim for each label independently snake_case : str = self.entailment_id snake_case : Optional[int] = -1 if entailment_id == 0 else 0 snake_case : Union[str, Any] = reshaped_outputs[..., [contradiction_id, entailment_id]] snake_case : List[str] = np.exp(__SCREAMING_SNAKE_CASE ) / np.exp(__SCREAMING_SNAKE_CASE ).sum(-1 , keepdims=__SCREAMING_SNAKE_CASE ) snake_case : Union[str, Any] = scores[..., 1] else: # softmax the "entailment" logits over all candidate labels snake_case : Any = reshaped_outputs[..., self.entailment_id] snake_case : Optional[Any] = np.exp(__SCREAMING_SNAKE_CASE ) / np.exp(__SCREAMING_SNAKE_CASE ).sum(-1 , keepdims=__SCREAMING_SNAKE_CASE ) snake_case : Tuple = list(reversed(scores[0].argsort() ) ) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
449
from itertools import permutations def lowercase__ ( A_: tuple ) -> bool: """simple docstring""" 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 =[7, 11, 13, 17] for i, test in enumerate(A_ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def lowercase__ ( A_: int = 10 ) -> int: """simple docstring""" return sum( int("""""".join(map(A_ , A_ ) ) ) for num in permutations(range(A_ ) ) if is_substring_divisible(A_ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _lowercase = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '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 _lowercase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
342
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __A = TypeVar("T") def lowercase__ ( A_: int ) -> int: """simple docstring""" return (position - 1) // 2 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 1 def lowercase__ ( A_: int ) -> int: """simple docstring""" return (2 * position) + 2 class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[str] ) -> None: __UpperCAmelCase =[] __UpperCAmelCase ={} __UpperCAmelCase =0 def __len__( self : str ) -> int: return self.elements def __repr__( self : Dict ) -> str: return str(self.heap ) def _a ( self : Optional[int] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __UpperCAmelCase =self.elements self.elements += 1 self._bubble_up(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __UpperCAmelCase , __UpperCAmelCase =self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __UpperCAmelCase , __UpperCAmelCase =self.heap[0] self._bubble_down(__SCREAMING_SNAKE_CASE ) return elem def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Update the weight of the given key __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase =(elem, weight) if position > 0: __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._bubble_up(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __UpperCAmelCase =self.position_map[elem] if curr_pos == 0: return None __UpperCAmelCase =get_parent_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase , __UpperCAmelCase =self.heap[parent_position] if parent_weight > weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_up(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __UpperCAmelCase =self.position_map[elem] __UpperCAmelCase , __UpperCAmelCase =self.heap[curr_pos] __UpperCAmelCase =get_child_left_position(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =get_child_right_position(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements and child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) else: return None if child_right_position < self.elements: __UpperCAmelCase , __UpperCAmelCase =self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) return None def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ) -> None: # Swap the nodes at the given positions __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase =self.heap[nodea_pos][0] __UpperCAmelCase , __UpperCAmelCase =( self.heap[nodea_pos], self.heap[nodea_pos], ) __UpperCAmelCase =nodea_pos __UpperCAmelCase =nodea_pos class _A ( Generic[T] ): """simple docstring""" def __init__( self : List[Any] ) -> None: __UpperCAmelCase ={} __UpperCAmelCase =0 def __repr__( self : Tuple ) -> str: return str(self.connections ) def __len__( self : str ) -> int: return self.nodes def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __UpperCAmelCase ={} self.nodes += 1 def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(__SCREAMING_SNAKE_CASE ) self.add_node(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =weight __UpperCAmelCase =weight def lowercase__ ( A_: GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: """simple docstring""" __UpperCAmelCase ={node: maxsize for node in graph.connections} __UpperCAmelCase ={node: None for node in graph.connections} __UpperCAmelCase =MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(A_ , A_ ) if priority_queue.is_empty(): return dist, parent # initialization __UpperCAmelCase =priority_queue.extract_min() __UpperCAmelCase =0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node # running prim's algorithm while not priority_queue.is_empty(): __UpperCAmelCase =priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __UpperCAmelCase =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A_ , dist[neighbour] ) __UpperCAmelCase =node return dist, parent
68
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __lowerCamelCase : Tuple = False class __magic_name__ ( unittest.TestCase ): pass @nightly @require_torch_gpu class __magic_name__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Dict: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: '''simple docstring''' UpperCAmelCase = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pipe.dual_guided( prompt="first prompt" , image=__SCREAMING_SNAKE_CASE , text_to_image_strength=0.75 , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = VersatileDiffusionPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = generator.manual_seed(0 ) UpperCAmelCase = pipe.dual_guided( prompt="first prompt" , image=__SCREAMING_SNAKE_CASE , text_to_image_strength=0.75 , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: '''simple docstring''' UpperCAmelCase = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = "cyberpunk 2077" UpperCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pipe.dual_guided( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , text_to_image_strength=0.75 , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" , ).images UpperCAmelCase = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase = np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 UpperCAmelCase = "A painting of a squirrel eating a burger " UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pipe.text_to_image( prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" ).images UpperCAmelCase = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 UpperCAmelCase = pipe.image_variation(__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="numpy" ).images UpperCAmelCase = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase = np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
323
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 __A = logging.get_logger(__name__) @dataclass class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[int] = [ 'no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process', ] def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __UpperCAmelCase =deprecated_arg[3:] __UpperCAmelCase =not kwargs.pop(__SCREAMING_SNAKE_CASE ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) __UpperCAmelCase =kwargs.pop("""tpu_name""" , self.tpu_name ) __UpperCAmelCase =kwargs.pop("""device_idx""" , self.device_idx ) __UpperCAmelCase =kwargs.pop("""eager_mode""" , self.eager_mode ) __UpperCAmelCase =kwargs.pop("""use_xla""" , self.use_xla ) super().__init__(**__SCREAMING_SNAKE_CASE ) lowerCamelCase : str = field( default=UpperCamelCase , metadata={'help': 'Name of TPU'} , ) lowerCamelCase : int = field( default=0 , metadata={'help': 'CPU / GPU device index. Defaults to 0.'} , ) lowerCamelCase : bool = field(default=UpperCamelCase , metadata={'help': 'Benchmark models in eager model.'} ) lowerCamelCase : 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 _a ( self : List[str] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) __UpperCAmelCase =None if self.tpu: try: if self.tpu_name: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __UpperCAmelCase =None return tpu @cached_property def _a ( self : Tuple ) -> 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 ) __UpperCAmelCase =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""" ) __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , """GPU""" ) # disable GPU __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/cpu:{self.device_idx}''' ) return strategy @property def _a ( self : Optional[Any] ) -> bool: requires_backends(self , ["""tf"""] ) return self._setup_tpu is not None @property def _a ( self : str ) -> "tf.distribute.Strategy": requires_backends(self , ["""tf"""] ) return self._setup_strategy @property def _a ( self : Dict ) -> Optional[int]: requires_backends(self , ["""tf"""] ) return tf.config.list_physical_devices("""GPU""" ) @property def _a ( self : List[str] ) -> int: requires_backends(self , ["""tf"""] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _a ( self : List[str] ) -> bool: return self.n_gpu > 0
68
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __lowerCAmelCase : Optional[int] = logging.getLogger(__name__) def lowerCAmelCase ( UpperCamelCase__ : int , UpperCamelCase__ : Optional[Any] ): """simple docstring""" return (preds == labels).mean() @dataclass class A : 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'''} , ) @dataclass class A : a_ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) a_ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) a_ = field( default=1_2_8 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) a_ = field( default=UpperCAmelCase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def lowerCAmelCase ( ): """simple docstring""" __UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO 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.local_rank != -1 ) , training_args.fpaa , ) # 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() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , A_ ) # Set seed set_seed(training_args.seed ) try: __UpperCAmelCase = processors[data_args.task_name]() __UpperCAmelCase = processor.get_labels() __UpperCAmelCase = len(A_ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # 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 , num_labels=A_ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) __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 , ) __UpperCAmelCase = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=A_ , cache_dir=model_args.cache_dir , ) # Get datasets __UpperCAmelCase = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=A_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __UpperCAmelCase = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=A_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(UpperCamelCase__ : EvalPrediction ) -> Dict: __UpperCAmelCase = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(A_ , p.label_ids )} # Data collator __UpperCAmelCase = DataCollatorWithPadding(A_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __UpperCAmelCase = Trainer( model=A_ , args=A_ , train_dataset=A_ , eval_dataset=A_ , compute_metrics=A_ , data_collator=A_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __UpperCAmelCase = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __UpperCAmelCase = trainer.evaluate() __UpperCAmelCase = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(A_ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , A_ , A_ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(A_ ) return results def lowerCAmelCase ( UpperCamelCase__ : Union[str, Any] ): """simple docstring""" main() if __name__ == "__main__": main()
262
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 _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Dict: torch.manual_seed(0 ) __UpperCAmelCase =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 _a ( self : int ) -> Union[str, Any]: __UpperCAmelCase =self.dummy_uncond_unet __UpperCAmelCase =ScoreSdeVeScheduler() __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE )[ 0 ] __UpperCAmelCase =image[0, -3:, -3:, -1] __UpperCAmelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCAmelCase =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 _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Optional[int] ) -> int: __UpperCAmelCase ="""google/ncsnpp-church-256""" __UpperCAmelCase =UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVeScheduler.from_pretrained(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ScoreSdeVePipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) sde_ve.to(__SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.manual_seed(0 ) __UpperCAmelCase =sde_ve(num_inference_steps=10 , output_type="""numpy""" , generator=__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCAmelCase =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
68
0
"""simple docstring""" import math import os import sys def lowercase__( __SCREAMING_SNAKE_CASE : str ): lowercase_ : Optional[Any] = '' try: with open(A_ , 'rb' ) as binary_file: lowercase_ : Any = binary_file.read() for dat in data: lowercase_ : Any = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def lowercase__( __SCREAMING_SNAKE_CASE : dict[str, str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str ): lexicon.pop(A_ ) lowercase_ : Optional[int] = last_match_id if math.loga(A_ ).is_integer(): for curr_key in lexicon: lowercase_ : Optional[Any] = '0' + lexicon[curr_key] lowercase_ : List[str] = bin(A_ )[2:] def lowercase__( __SCREAMING_SNAKE_CASE : str ): lowercase_ : str = {'0': '0', '1': '1'} lowercase_ , lowercase_ : Optional[int] = '', '' lowercase_ : Dict = len(A_ ) for i in range(len(A_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue lowercase_ : Dict = lexicon[curr_string] result += last_match_id add_key_to_lexicon(A_ , A_ , A_ , A_ ) index += 1 lowercase_ : List[Any] = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": lowercase_ : Any = lexicon[curr_string] result += last_match_id return result def lowercase__( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): lowercase_ : Tuple = os.path.getsize(A_ ) lowercase_ : str = bin(A_ )[2:] lowercase_ : int = len(A_ ) return "0" * (length_length - 1) + file_length_binary + compressed def lowercase__( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): lowercase_ : Dict = 8 try: with open(A_ , 'wb' ) as opened_file: lowercase_ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(A_ ) , A_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(A_ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def lowercase__( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): lowercase_ : int = read_file_binary(A_ ) lowercase_ : Union[str, Any] = compress_data(A_ ) lowercase_ : Tuple = add_file_length(A_ , A_ ) write_file_binary(A_ , A_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
425
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __A = logging.get_logger(__name__) __A = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class _A ( UpperCamelCase ): """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : str=None , *__SCREAMING_SNAKE_CASE : Union[str, Any] , **__SCREAMING_SNAKE_CASE : List[Any] ) -> Any: super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if config is None: assert isinstance(self.model , __SCREAMING_SNAKE_CASE ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f''' {self.model.__class__}''' ) __UpperCAmelCase =self.model.config else: __UpperCAmelCase =config __UpperCAmelCase =data_args __UpperCAmelCase =self.config.tgt_vocab_size if isinstance(self.config , __SCREAMING_SNAKE_CASE ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' """ padding..""" ) if self.args.label_smoothing == 0: __UpperCAmelCase =torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __UpperCAmelCase =label_smoothed_nll_loss def _a ( self : Any , __SCREAMING_SNAKE_CASE : int ) -> Any: if self.optimizer is None: __UpperCAmelCase =["""bias""", """LayerNorm.weight"""] __UpperCAmelCase =[ { """params""": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], """weight_decay""": self.args.weight_decay, }, { """params""": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], """weight_decay""": 0.0, }, ] __UpperCAmelCase =Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __UpperCAmelCase =Adafactor __UpperCAmelCase ={"""scale_parameter""": False, """relative_step""": False} else: __UpperCAmelCase =AdamW __UpperCAmelCase ={ """betas""": (self.args.adam_betaa, self.args.adam_betaa), """eps""": self.args.adam_epsilon, } __UpperCAmelCase =self.args.learning_rate if self.sharded_ddp: __UpperCAmelCase =OSS( params=__SCREAMING_SNAKE_CASE , optim=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: __UpperCAmelCase =optimizer_cls(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if self.lr_scheduler is None: __UpperCAmelCase =self._get_lr_scheduler(__SCREAMING_SNAKE_CASE ) else: # ignoring --lr_scheduler logger.warning("""scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.""" ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Any: __UpperCAmelCase =arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __UpperCAmelCase =schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __UpperCAmelCase =schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __UpperCAmelCase =schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=__SCREAMING_SNAKE_CASE ) return scheduler def _a ( self : Optional[Any] ) -> Optional[torch.utils.data.Sampler]: if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Tuple: if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __UpperCAmelCase , __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[:2] else: # compute label smoothed loss __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )[0] __UpperCAmelCase =torch.nn.functional.log_softmax(__SCREAMING_SNAKE_CASE , dim=-1 ) __UpperCAmelCase , __UpperCAmelCase =self.loss_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: __UpperCAmelCase =inputs.pop("""labels""" ) __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return loss def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : nn.Module , __SCREAMING_SNAKE_CASE : Dict[str, Union[torch.Tensor, Any]] , __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : Optional[List[str]] = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: __UpperCAmelCase =self._prepare_inputs(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """max_length""": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, """num_beams""": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __UpperCAmelCase =self.model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , **__SCREAMING_SNAKE_CASE , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) __UpperCAmelCase =inputs.pop("""labels""" ) with torch.no_grad(): # compute loss on predict data __UpperCAmelCase , __UpperCAmelCase =self._compute_loss(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __UpperCAmelCase =generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __UpperCAmelCase =self._pad_tensors_to_max_len(__SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""] ) return (loss, logits, labels) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: # If PAD token is not defined at least EOS token has to be defined __UpperCAmelCase =self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( """Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be""" f''' padded to `max_length`={max_length}''' ) __UpperCAmelCase =pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __UpperCAmelCase =tensor return padded_tensor
68
0
"""simple docstring""" from PIL import Image def A_ (__a , __a ): '''simple docstring''' A_ = (259 * (level + 255)) / (255 * (259 - level)) def contrast(__a ) -> int: return int(128 + factor * (c - 128) ) return img.point(A_ ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change contrast to 170 UpperCamelCase_ : List[str] = change_contrast(img, 170) cont_img.save('''image_data/lena_high_contrast.png''', format='''png''')
115
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : List[Any] = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str=0 ) -> Any: __UpperCAmelCase =floats_tensor((1, 3, 128, 128) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =np.random.RandomState(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """strength""": 0.75, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _a ( self : Optional[Any] ) -> int: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Union[str, Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Optional[Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # warmup pass to apply optimizations __UpperCAmelCase =pipe(**self.get_dummy_inputs() ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _a ( self : Union[str, Any] ) -> Dict: __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.get_dummy_inputs() __UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images __UpperCAmelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __UpperCAmelCase =np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class _A ( unittest.TestCase ): """simple docstring""" @property def _a ( self : List[str] ) -> Optional[int]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _a ( self : Dict ) -> int: __UpperCAmelCase =ort.SessionOptions() __UpperCAmelCase =False return options def _a ( self : Dict ) -> Any: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) # using the PNDM scheduler by default __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _a ( self : List[str] ) -> str: __UpperCAmelCase =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase =init_image.resize((768, 512) ) __UpperCAmelCase =LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) __UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ="""A fantasy landscape, trending on artstation""" __UpperCAmelCase =np.random.RandomState(0 ) __UpperCAmelCase =pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __UpperCAmelCase =output.images __UpperCAmelCase =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __UpperCAmelCase =np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
68
0
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake __snake_case :str =numpy.array([0, 0]) __snake_case :List[Any] =numpy.array([0.5, 0.866_0254]) __snake_case :Optional[int] =numpy.array([1, 0]) __snake_case :str =[VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def lowerCamelCase_ ( lowerCAmelCase__ : list[numpy.ndarray] , lowerCAmelCase__ : int ) -> list[numpy.ndarray]: '''simple docstring''' A = initial_vectors for _ in range(A_ ): A = iteration_step(A_ ) return vectors def lowerCamelCase_ ( lowerCAmelCase__ : list[numpy.ndarray] ) -> list[numpy.ndarray]: '''simple docstring''' A = [] for i, start_vector in enumerate(vectors[:-1] ): A = vectors[i + 1] new_vectors.append(A_ ) A = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def lowerCamelCase_ ( lowerCAmelCase__ : numpy.ndarray , lowerCAmelCase__ : float ) -> numpy.ndarray: '''simple docstring''' A = numpy.radians(A_ ) A , A = numpy.cos(A_ ), numpy.sin(A_ ) A = numpy.array(((c, -s), (s, c)) ) return numpy.dot(A_ , A_ ) def lowerCamelCase_ ( lowerCAmelCase__ : list[numpy.ndarray] ) -> None: '''simple docstring''' A = plt.gca() axes.set_aspect('equal' ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() A , A = zip(*A_ ) plt.plot(A_ , A_ ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() __snake_case :Optional[int] =iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
106
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors __A = logging.getLogger(__name__) class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[Any] = 'sequence-classification' def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Tuple ) -> Optional[Any]: if type(__SCREAMING_SNAKE_CASE ) == dict: __UpperCAmelCase =Namespace(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =glue_output_modes[hparams.task] __UpperCAmelCase =glue_tasks_num_labels[hparams.task] super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.mode ) def _a ( self : str , **__SCREAMING_SNAKE_CASE : Dict ) -> List[str]: return self.model(**__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ) -> List[Any]: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =outputs[0] __UpperCAmelCase =self.trainer.lr_schedulers[0]["""scheduler"""] __UpperCAmelCase ={"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def _a ( self : Tuple ) -> List[Any]: __UpperCAmelCase =self.hparams __UpperCAmelCase =processors[args.task]() __UpperCAmelCase =processor.get_labels() for mode in ["train", "dev"]: __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) if os.path.exists(__SCREAMING_SNAKE_CASE ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) __UpperCAmelCase =( processor.get_dev_examples(args.data_dir ) if mode == """dev""" else processor.get_train_examples(args.data_dir ) ) __UpperCAmelCase =convert_examples_to_features( __SCREAMING_SNAKE_CASE , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("""Saving features into cached file %s""" , __SCREAMING_SNAKE_CASE ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ) -> DataLoader: __UpperCAmelCase ="""dev""" if mode == """test""" else mode __UpperCAmelCase =self._feature_file(__SCREAMING_SNAKE_CASE ) logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.load(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __UpperCAmelCase =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , batch_size=__SCREAMING_SNAKE_CASE , shuffle=__SCREAMING_SNAKE_CASE , ) def _a ( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ) -> str: __UpperCAmelCase ={"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase =batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCAmelCase =self(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase =outputs[:2] __UpperCAmelCase =logits.detach().cpu().numpy() __UpperCAmelCase =inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Any ) -> tuple: __UpperCAmelCase =torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item() __UpperCAmelCase =np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase =np.argmax(__SCREAMING_SNAKE_CASE , axis=1 ) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase =np.squeeze(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =np.concatenate([x["""target"""] for x in outputs] , axis=0 ) __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] __UpperCAmelCase ={**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} __UpperCAmelCase =dict(results.items() ) __UpperCAmelCase =results return ret, preds_list, out_label_list def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : list ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._eval_end(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _a ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[Any]: BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) parser.add_argument( """--max_seq_length""" , default=128 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--task""" , default="""""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The GLUE task to run""" , ) parser.add_argument( """--gpus""" , default=0 , type=__SCREAMING_SNAKE_CASE , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser def lowercase__ ( ) -> str: """simple docstring""" __UpperCAmelCase =argparse.ArgumentParser() add_generic_args(A_ , os.getcwd() ) __UpperCAmelCase =GLUETransformer.add_model_specific_args(A_ , os.getcwd() ) __UpperCAmelCase =parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __UpperCAmelCase =os.path.join( """./results""" , F'''{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}''' , ) os.makedirs(args.output_dir ) __UpperCAmelCase =GLUETransformer(A_ ) __UpperCAmelCase =generic_train(A_ , A_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __UpperCAmelCase =sorted(glob.glob(os.path.join(args.output_dir , """checkpoint-epoch=*.ckpt""" ) , recursive=A_ ) ) __UpperCAmelCase =model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(A_ ) if __name__ == "__main__": main()
68
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = '▁' lowerCAmelCase_ = {'vocab_file': 'sentencepiece.bpe.model'} lowerCAmelCase_ = { 'vocab_file': { 'facebook/nllb-200-distilled-600M': ( 'https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model' ), } } lowerCAmelCase_ = { 'facebook/nllb-200-distilled-600M': 1_024, } # fmt: off lowerCAmelCase_ = ['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn'] class __A ( A_ ): '''simple docstring''' lowerCAmelCase : Tuple = VOCAB_FILES_NAMES lowerCAmelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase : List[Any] = ['input_ids', 'attention_mask'] lowerCAmelCase : List[int] = [] lowerCAmelCase : List[int] = [] def __init__( self : Any ,_snake_case : int ,_snake_case : Any="<s>" ,_snake_case : Tuple="</s>" ,_snake_case : List[Any]="</s>" ,_snake_case : Optional[int]="<s>" ,_snake_case : Dict="<unk>" ,_snake_case : Optional[int]="<pad>" ,_snake_case : Any="<mask>" ,_snake_case : int=None ,_snake_case : Union[str, Any]=None ,_snake_case : Optional[Any]=None ,_snake_case : Optional[Dict[str, Any]] = None ,_snake_case : Tuple=None ,_snake_case : Optional[int]=False ,**_snake_case : Any ,) -> Optional[Any]: """simple docstring""" lowercase__ : Dict = AddedToken(__SCREAMING_SNAKE_CASE ,lstrip=__SCREAMING_SNAKE_CASE ,rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) else mask_token lowercase__ : int = {} if sp_model_kwargs is None else sp_model_kwargs lowercase__ : Dict = legacy_behaviour super().__init__( bos_token=__SCREAMING_SNAKE_CASE ,eos_token=__SCREAMING_SNAKE_CASE ,unk_token=__SCREAMING_SNAKE_CASE ,sep_token=__SCREAMING_SNAKE_CASE ,cls_token=__SCREAMING_SNAKE_CASE ,pad_token=__SCREAMING_SNAKE_CASE ,mask_token=__SCREAMING_SNAKE_CASE ,tokenizer_file=__SCREAMING_SNAKE_CASE ,src_lang=__SCREAMING_SNAKE_CASE ,tgt_lang=__SCREAMING_SNAKE_CASE ,additional_special_tokens=__SCREAMING_SNAKE_CASE ,sp_model_kwargs=self.sp_model_kwargs ,legacy_behaviour=__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ,) lowercase__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase__ : Tuple = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' # spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s' # Mimic fairseq token-to-id alignment for the first 4 token lowercase__ : int = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase__ : str = 1 lowercase__ : Optional[int] = len(self.sp_model ) lowercase__ : int = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase__ : Dict = {v: k for k, v in self.lang_code_to_id.items()} lowercase__ : str = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase__ : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase__ : Union[str, Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase__ : Union[str, Any] = src_lang if src_lang is not None else '''eng_Latn''' lowercase__ : Optional[Any] = self.lang_code_to_id[self._src_lang] lowercase__ : Any = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Tuple ) -> Optional[Any]: """simple docstring""" lowercase__ : Optional[int] = self.__dict__.copy() lowercase__ : Optional[Any] = None lowercase__ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self : Dict ,_snake_case : Dict ) -> Tuple: """simple docstring""" lowercase__ : Dict = d # for backward compatibility if not hasattr(self ,'''sp_model_kwargs''' ): lowercase__ : List[str] = {} lowercase__ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def UpperCAmelCase ( self : Any ) -> int: """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def UpperCAmelCase ( self : str ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def UpperCAmelCase ( self : Any ,_snake_case : str ) -> None: """simple docstring""" lowercase__ : Dict = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def UpperCAmelCase ( self : Any ,_snake_case : List[int] ,_snake_case : Optional[List[int]] = None ,_snake_case : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE ,token_ids_a=__SCREAMING_SNAKE_CASE ,already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase__ : int = [1] * len(self.prefix_tokens ) lowercase__ : int = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def UpperCAmelCase ( self : Tuple ,_snake_case : List[int] ,_snake_case : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCAmelCase ( self : List[str] ,_snake_case : List[int] ,_snake_case : Optional[List[int]] = None ) -> List[int]: """simple docstring""" lowercase__ : str = [self.sep_token_id] lowercase__ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase ( self : Tuple ,_snake_case : Optional[int] ,_snake_case : str ,_snake_case : Optional[str] ,_snake_case : Optional[str] ,**_snake_case : Tuple ) -> Dict: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase__ : Dict = src_lang lowercase__ : str = self(__SCREAMING_SNAKE_CASE ,add_special_tokens=__SCREAMING_SNAKE_CASE ,return_tensors=__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) lowercase__ : Union[str, Any] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase__ : List[str] = tgt_lang_id return inputs def UpperCAmelCase ( self : Any ) -> List[Any]: """simple docstring""" lowercase__ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCAmelCase ( self : List[str] ,_snake_case : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE ,out_type=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Dict ,_snake_case : str ) -> int: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase__ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def UpperCAmelCase ( self : List[str] ,_snake_case : Union[str, Any] ) -> Dict: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCAmelCase ( self : str ,_snake_case : Tuple ) -> int: """simple docstring""" lowercase__ : Any = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE ,''' ''' ).strip() return out_string def UpperCAmelCase ( self : int ,_snake_case : str ,_snake_case : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowercase__ : str = os.path.join( __SCREAMING_SNAKE_CASE ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,__SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE ,'''wb''' ) as fi: lowercase__ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def UpperCAmelCase ( self : Optional[Any] ,_snake_case : List[str] ,_snake_case : str = "eng_Latn" ,_snake_case : Optional[List[str]] = None ,_snake_case : str = "fra_Latn" ,**_snake_case : Dict ,) -> BatchEncoding: """simple docstring""" lowercase__ : Tuple = src_lang lowercase__ : List[str] = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Optional[int] ) -> Any: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def UpperCAmelCase ( self : Any ) -> Any: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCAmelCase ( self : Any ,_snake_case : List[str] ) -> None: """simple docstring""" lowercase__ : int = self.lang_code_to_id[src_lang] if self.legacy_behaviour: lowercase__ : Tuple = [] lowercase__ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code] else: lowercase__ : Optional[int] = [self.cur_lang_code] lowercase__ : List[Any] = [self.eos_token_id] def UpperCAmelCase ( self : Optional[int] ,_snake_case : str ) -> None: """simple docstring""" lowercase__ : int = self.lang_code_to_id[lang] if self.legacy_behaviour: lowercase__ : Optional[Any] = [] lowercase__ : str = [self.eos_token_id, self.cur_lang_code] else: lowercase__ : Optional[int] = [self.cur_lang_code] lowercase__ : List[str] = [self.eos_token_id]
560
def lowercase__ ( A_: int , A_: int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def lowercase__ ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
'''simple docstring''' import numpy as np class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any ): UpperCAmelCase = (0, 0) UpperCAmelCase = None UpperCAmelCase = 0 UpperCAmelCase = 0 UpperCAmelCase = 0 def __eq__( self : str , a__ : List[Any] ): return self.position == cell.position def __snake_case ( self : str ): print(self.position ) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int] , a__ : Tuple=(5, 5) ): UpperCAmelCase = np.zeros(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = world_size[0] UpperCAmelCase = world_size[1] def __snake_case ( self : Optional[Any] ): print(self.w ) def __snake_case ( self : int , a__ : Tuple ): UpperCAmelCase = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] UpperCAmelCase = cell.position[0] UpperCAmelCase = cell.position[1] UpperCAmelCase = [] for n in neughbour_cord: UpperCAmelCase = current_x + n[0] UpperCAmelCase = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: UpperCAmelCase = Cell() UpperCAmelCase = (x, y) UpperCAmelCase = cell neighbours.append(__SCREAMING_SNAKE_CASE ) return neighbours def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple ) -> str: """simple docstring""" UpperCAmelCase = [] UpperCAmelCase = [] _open.append(A_ ) while _open: UpperCAmelCase = np.argmin([n.f for n in _open] ) UpperCAmelCase = _open[min_f] _closed.append(_open.pop(A_ ) ) if current == goal: break for n in world.get_neigbours(A_ ): for c in _closed: if c == n: continue UpperCAmelCase = current.g + 1 UpperCAmelCase, UpperCAmelCase = n.position UpperCAmelCase, UpperCAmelCase = goal.position UpperCAmelCase = (ya - ya) ** 2 + (xa - xa) ** 2 UpperCAmelCase = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(A_ ) UpperCAmelCase = [] while current.parent is not None: path.append(current.position ) UpperCAmelCase = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": a__ : int = Gridworld() # Start position and goal a__ : Any = Cell() a__ : str = (0, 0) a__ : str = Cell() a__ : str = (4, 4) print(F"""path from {start.position} to {goal.position}""") a__ : int = astar(world, start, goal) # Just for visual reasons. for i in s: a__ : Union[str, Any] = 1 print(world.w)
51
from __future__ import annotations import bisect def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] < item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> int: """simple docstring""" if hi < 0: __UpperCAmelCase =len(A_ ) while lo < hi: __UpperCAmelCase =lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __UpperCAmelCase =mid + 1 else: __UpperCAmelCase =mid return lo def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_left(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int , A_: int = 0 , A_: int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_right(A_ , A_ , A_ , A_ ) , A_ ) def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =0 __UpperCAmelCase =len(A_ ) - 1 while left <= right: __UpperCAmelCase =left + (right - left) // 2 __UpperCAmelCase =sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __UpperCAmelCase =midpoint - 1 else: __UpperCAmelCase =midpoint + 1 return None def lowercase__ ( A_: list[int] , A_: int ) -> int | None: """simple docstring""" __UpperCAmelCase =bisect.bisect_left(A_ , A_ ) if index != len(A_ ) and sorted_collection[index] == item: return index return None def lowercase__ ( A_: list[int] , A_: int , A_: int , A_: int ) -> int | None: """simple docstring""" if right < left: return None __UpperCAmelCase =left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(A_ , A_ , A_ , midpoint - 1 ) else: return binary_search_by_recursion(A_ , A_ , midpoint + 1 , A_ ) if __name__ == "__main__": __A = input("Enter numbers separated by comma:\n").strip() __A = sorted(int(item) for item in user_input.split(",")) __A = int(input("Enter a single number to be found in the list:\n")) __A = binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
68
0
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __magic_name__ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--original_config_file''', type=str, required=True, 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( '''--image_size''', default=5_12, 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( '''--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.)''') def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(f"could not parse string as bool {string}" ) parser.add_argument( '''--use_linear_projection''', help='''Override for use linear projection''', required=False, type=parse_bool ) parser.add_argument('''--cross_attention_dim''', help='''Override for cross attention_dim''', required=False, type=int) __magic_name__ = parser.parse_args() __magic_name__ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
657
from typing import List from .keymap import KEYMAP, get_character def lowercase__ ( A_: str ) -> str: """simple docstring""" def decorator(A_: int ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += [key] setattr(A_ , """handle_key""" , A_ ) return func return decorator def lowercase__ ( *A_: List[str] ) -> Optional[int]: """simple docstring""" def decorator(A_: Tuple ): __UpperCAmelCase =getattr(A_ , """handle_key""" , [] ) handle += keys setattr(A_ , """handle_key""" , A_ ) return func return decorator class _A ( UpperCamelCase ): """simple docstring""" def __new__( cls : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> int: __UpperCAmelCase =super().__new__(cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if not hasattr(__SCREAMING_SNAKE_CASE , """key_handler""" ): setattr(__SCREAMING_SNAKE_CASE , """key_handler""" , {} ) setattr(__SCREAMING_SNAKE_CASE , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , """handle_key""" , [] ) for key in handled_keys: __UpperCAmelCase =value return new_cls @staticmethod def _a ( cls : Dict ) -> List[Any]: __UpperCAmelCase =get_character() if char != KEYMAP["undefined"]: __UpperCAmelCase =ord(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =cls.key_handler.get(__SCREAMING_SNAKE_CASE ) if handler: __UpperCAmelCase =char return handler(cls ) else: return None def lowercase__ ( cls: str ) -> int: """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
68
0
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a_ = logging.getLogger() @unittest.skip("""Temporarily disable the doc tests.""" ) @require_torch @require_tf @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __magic_name__ ( self : Union[str, Any] , __lowercase : Path , __lowercase : Union[str, None] = None , __lowercase : Union[List[str], None] = None , __lowercase : Union[str, List[str], None] = None , __lowercase : bool = True , ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )] if identifier is not None: SCREAMING_SNAKE_CASE__ : int =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n_ in n_identifier: SCREAMING_SNAKE_CASE__ : int =[file for file in files if n_ not in file] else: SCREAMING_SNAKE_CASE__ : Optional[int] =[file for file in files if n_identifier not in file] SCREAMING_SNAKE_CASE__ : Union[str, Any] =ignore_files or [] ignore_files.append('''__init__.py''' ) SCREAMING_SNAKE_CASE__ : List[Any] =[file for file in files if file not in ignore_files] for file in files: # Open all files print('''Testing''' , __SCREAMING_SNAKE_CASE ) if only_modules: SCREAMING_SNAKE_CASE__ : Any =file.split('''.''' )[0] try: SCREAMING_SNAKE_CASE__ : Any =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE__ : Optional[Any] =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE__ : Optional[Any] =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F"{module_identifier} is not a module." ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =doctest.testfile(str('''..''' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def __magic_name__ ( self : Optional[Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any =Path('''src/transformers''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''modeling''' SCREAMING_SNAKE_CASE__ : int =[ '''modeling_ctrl.py''', '''modeling_tf_ctrl.py''', ] self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE ) def __magic_name__ ( self : Tuple ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] =Path('''src/transformers''' ) SCREAMING_SNAKE_CASE__ : int ='''tokenization''' self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =Path('''src/transformers''' ) SCREAMING_SNAKE_CASE__ : str ='''configuration''' self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def __magic_name__ ( self : List[Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =Path('''src/transformers''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =['''configuration''', '''modeling''', '''tokenization'''] self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE ) def __magic_name__ ( self : Any ) -> Tuple: SCREAMING_SNAKE_CASE__ : Union[str, Any] =Path('''docs/source''' ) SCREAMING_SNAKE_CASE__ : Dict =['''favicon.ico'''] self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
296
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
68
0
"""simple docstring""" import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: str ): """simple docstring""" snake_case : List[Any] = tmp_path / "file.csv" snake_case : Dict = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20\n " ) with open(A_ , "w" ) as f: f.write(A_ ) return str(A_ ) @pytest.fixture def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Union[str, Any] ): """simple docstring""" snake_case : Any = tmp_path / "malformed_file.csv" snake_case : str = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20,\n " ) with open(A_ , "w" ) as f: f.write(A_ ) return str(A_ ) @pytest.fixture def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Union[str, Any] , lowerCamelCase_: List[Any] ): """simple docstring""" snake_case : Optional[int] = tmp_path / "csv_with_image.csv" snake_case : Optional[Any] = textwrap.dedent( f'''\ image {image_file} ''' ) with open(A_ , "w" ) as f: f.write(A_ ) return str(A_ ) @pytest.fixture def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Optional[int] ): """simple docstring""" snake_case : int = tmp_path / "csv_with_label.csv" snake_case : List[Any] = textwrap.dedent( "\\n label\n good\n bad\n good\n " ) with open(A_ , "w" ) as f: f.write(A_ ) return str(A_ ) @pytest.fixture def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[str] ): """simple docstring""" snake_case : int = tmp_path / "csv_with_int_list.csv" snake_case : List[Any] = textwrap.dedent( "\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n " ) with open(A_ , "w" ) as f: f.write(A_ ) return str(A_ ) def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Dict , lowerCamelCase_: Optional[Any] , lowerCamelCase_: Union[str, Any] ): """simple docstring""" snake_case : List[Any] = Csv() snake_case : List[Any] = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(A_ , match="Error tokenizing data" ): for _ in generator: pass assert any( record.levelname == "ERROR" and "Failed to read file" in record.message and os.path.basename(A_ ) in record.message for record in caplog.records ) @require_pil def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Tuple ): """simple docstring""" with open(A_ , encoding="utf-8" ) as f: snake_case : Optional[Any] = f.read().splitlines()[1] snake_case : Optional[int] = Csv(encoding="utf-8" , features=Features({"image": Image()} ) ) snake_case : List[Any] = csv._generate_tables([[csv_file_with_image]] ) snake_case : List[Any] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("image" ).type == Image()() snake_case : int = pa_table.to_pydict()["image"] assert generated_content == [{"path": image_file, "bytes": None}] def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[str] ): """simple docstring""" with open(A_ , encoding="utf-8" ) as f: snake_case : List[str] = f.read().splitlines()[1:] snake_case : Optional[Any] = Csv(encoding="utf-8" , features=Features({"label": ClassLabel(names=["good", "bad"] )} ) ) snake_case : Dict = csv._generate_tables([[csv_file_with_label]] ) snake_case : Optional[Any] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("label" ).type == ClassLabel(names=["good", "bad"] )() snake_case : List[str] = pa_table.to_pydict()["label"] assert generated_content == [ClassLabel(names=["good", "bad"] ).straint(A_ ) for label in labels] def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[str] ): """simple docstring""" snake_case : List[str] = Csv(encoding="utf-8" , sep="," , converters={"int_list": lambda lowerCamelCase_ : [int(A_ ) for i in x.split()]} ) snake_case : Optional[Any] = csv._generate_tables([[csv_file_with_int_list]] ) snake_case : List[str] = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("int_list" ).type ) snake_case : str = pa_table.to_pydict()["int_list"] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
449
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _A ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Optional[Any]=99 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : int=5 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : str=37 , __SCREAMING_SNAKE_CASE : Union[str, Any]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : str=512 , __SCREAMING_SNAKE_CASE : Dict=16 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : List[str]=4 , ) -> Optional[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =seq_length __UpperCAmelCase =is_training __UpperCAmelCase =use_attention_mask __UpperCAmelCase =use_token_type_ids __UpperCAmelCase =use_labels __UpperCAmelCase =vocab_size __UpperCAmelCase =hidden_size __UpperCAmelCase =num_hidden_layers __UpperCAmelCase =num_attention_heads __UpperCAmelCase =intermediate_size __UpperCAmelCase =hidden_act __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =max_position_embeddings __UpperCAmelCase =type_vocab_size __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =initializer_range __UpperCAmelCase =num_choices def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase =None if self.use_attention_mask: __UpperCAmelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase =None if self.use_token_type_ids: __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase =RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def _a ( self : List[str] ) -> Dict: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase =True __UpperCAmelCase =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _A ( UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] = True lowerCamelCase : Union[str, Any] = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self : List[Any] ) -> List[str]: __UpperCAmelCase =FlaxRobertaModelTester(self ) @slow def _a ( self : Optional[Any] ) -> List[Any]: for model_class_name in self.all_model_classes: __UpperCAmelCase =model_class_name.from_pretrained("""roberta-base""" , from_pt=__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model(np.ones((1, 1) ) ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class _lowercase : @staticmethod def UpperCamelCase ( *A__ , **A__ ) -> int: pass def __UpperCamelCase ( a : Image ) ->str: snake_case = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class _lowercase ( unittest.TestCase ): _UpperCAmelCase = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def UpperCamelCase ( self , A__ , A__ , A__ ) -> int: snake_case = DepthEstimationPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCamelCase ( self , A__ , A__ ) -> Tuple: snake_case = depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} , __SCREAMING_SNAKE_CASE ) import datasets snake_case = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) snake_case = depth_estimator( [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] ) self.assertEqual( [ {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, ] , __SCREAMING_SNAKE_CASE , ) @require_tf @unittest.skip('''Depth estimation is not implemented in TF''' ) def UpperCamelCase ( self ) -> Union[str, Any]: pass @slow @require_torch def UpperCamelCase ( self ) -> int: snake_case = '''Intel/dpt-large''' snake_case = pipeline('''depth-estimation''' , model=__SCREAMING_SNAKE_CASE ) snake_case = depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) snake_case = hashimage(outputs['''depth'''] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) , 2_9.3_0_4 ) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) , 2.6_6_2 ) @require_torch def UpperCamelCase ( self ) -> Any: # This is highly irregular to have no small tests. self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
342
from __future__ import annotations def lowercase__ ( A_: list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(A_ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
68
0
from __future__ import annotations def lowerCamelCase_(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) -> None: UpperCAmelCase = len(A_ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(A_ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , A_ , A_ , ) def lowerCamelCase_(lowerCamelCase_ ) -> None: UpperCAmelCase = [] depth_first_search([] , [] , [] , A_ , A_ ) # Print all the boards for board in boards: for column in board: print(A_ ) print("" ) print(len(A_ ) , "solutions were found." ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
323
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowercase__ ( A_: int , A_: int , A_: int , A_: int , A_: int , A_: int ) -> np.ndarray: """simple docstring""" if (ksize % 2) == 0: __UpperCAmelCase =ksize + 1 __UpperCAmelCase =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(A_ ): for x in range(A_ ): # distance from center __UpperCAmelCase =x - ksize // 2 __UpperCAmelCase =y - ksize // 2 # degree to radiant __UpperCAmelCase =theta / 180 * np.pi __UpperCAmelCase =np.cos(_theta ) __UpperCAmelCase =np.sin(_theta ) # get kernel x __UpperCAmelCase =cos_theta * px + sin_theta * py # get kernel y __UpperCAmelCase =-sin_theta * px + cos_theta * py # fill kernel __UpperCAmelCase =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __A = imread("../image_data/lena.jpg") # turn image in gray scale value __A = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __A = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 1_20, 1_50]: __A = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __A = out / out.max() * 2_55 __A = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
68
0
'''simple docstring''' from __future__ import annotations __lowerCAmelCase : str = [True] * 1_000_001 __lowerCAmelCase : Tuple = 2 while i * i <= 1_000_000: if seive[i]: for j in range(i * i, 1_000_001, i): __lowerCAmelCase : List[str] = False i += 1 def lowerCAmelCase ( UpperCamelCase__ : int ): """simple docstring""" return seive[n] def lowerCAmelCase ( UpperCamelCase__ : int ): """simple docstring""" return any(digit in '''02468''' for digit in str(A_ ) ) def lowerCAmelCase ( UpperCamelCase__ : int = 1_0_0_0_0_0_0 ): """simple docstring""" __UpperCAmelCase = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(A_ ) and not contains_an_even_digit(A_ ): __UpperCAmelCase = str(A_ ) __UpperCAmelCase = [int(str_num[j:] + str_num[:j] ) for j in range(len(A_ ) )] if all(is_prime(A_ ) for i in list_nums ): result.append(A_ ) return result def lowerCAmelCase ( ): """simple docstring""" return len(find_circular_primes() ) if __name__ == "__main__": print(F"""{len(find_circular_primes()) = }""")
262
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : """simple docstring""" def __init__( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , __SCREAMING_SNAKE_CASE : List[str]=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=[1, 2, 1] , __SCREAMING_SNAKE_CASE : List[Any]=[2, 2, 4] , __SCREAMING_SNAKE_CASE : str=2 , __SCREAMING_SNAKE_CASE : Any=2.0 , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Dict=0.0 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : Any="gelu" , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : List[Any]=0.02 , __SCREAMING_SNAKE_CASE : Tuple=1e-5 , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Any=10 , __SCREAMING_SNAKE_CASE : Dict=8 , ) -> List[Any]: __UpperCAmelCase =parent __UpperCAmelCase =batch_size __UpperCAmelCase =image_size __UpperCAmelCase =patch_size __UpperCAmelCase =num_channels __UpperCAmelCase =embed_dim __UpperCAmelCase =depths __UpperCAmelCase =num_heads __UpperCAmelCase =window_size __UpperCAmelCase =mlp_ratio __UpperCAmelCase =qkv_bias __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =drop_path_rate __UpperCAmelCase =hidden_act __UpperCAmelCase =use_absolute_embeddings __UpperCAmelCase =patch_norm __UpperCAmelCase =layer_norm_eps __UpperCAmelCase =initializer_range __UpperCAmelCase =is_training __UpperCAmelCase =scope __UpperCAmelCase =use_labels __UpperCAmelCase =type_sequence_label_size __UpperCAmelCase =encoder_stride def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase =None if self.use_labels: __UpperCAmelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase =self.get_config() return config, pixel_values, labels def _a ( self : List[Any] ) -> Optional[Any]: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: __UpperCAmelCase =SwinvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase =int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> Tuple: __UpperCAmelCase =SwinvaForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase =1 __UpperCAmelCase =SwinvaForMaskedImageModeling(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: __UpperCAmelCase =self.type_sequence_label_size __UpperCAmelCase =SwinvaForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self : List[str] ) -> Tuple: __UpperCAmelCase =self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs __UpperCAmelCase ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[int] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCamelCase : Tuple = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowerCamelCase : Dict = False lowerCamelCase : Tuple = False lowerCamelCase : List[str] = False lowerCamelCase : Tuple = False def _a ( self : str ) -> str: __UpperCAmelCase =SwinvaModelTester(self ) __UpperCAmelCase =ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , embed_dim=37 ) def _a ( self : List[Any] ) -> Optional[int]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self : str ) -> str: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def _a ( self : Tuple ) -> Tuple: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def _a ( self : Optional[Any] ) -> int: pass def _a ( self : Tuple ) -> int: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase =model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def _a ( self : str ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase =[*signature.parameters.keys()] __UpperCAmelCase =["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =True for model_class in self.all_model_classes: __UpperCAmelCase =True __UpperCAmelCase =False __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions __UpperCAmelCase =len(self.model_tester.depths ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase =True __UpperCAmelCase =config.window_size**2 __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase =len(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __UpperCAmelCase =True __UpperCAmelCase =True __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase =self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase =2 self.assertEqual(out_len + added_hidden_states , len(__SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> int: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __UpperCAmelCase =model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __UpperCAmelCase =outputs.hidden_states __UpperCAmelCase =getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # Swinv2 has a different seq_length __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase =outputs.reshaped_hidden_states self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =reshaped_hidden_states[0].shape __UpperCAmelCase =( reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self : str ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =3 __UpperCAmelCase =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase =True self.check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) def _a ( self : Optional[int] ) -> Tuple: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Dict: __UpperCAmelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def _a ( self : int ) -> Dict: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase =SwinvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def _a ( self : Dict ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase =_config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __UpperCAmelCase =model_class(config=__SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _A ( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self : Tuple ) -> Dict: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def _a ( self : int ) -> Optional[int]: __UpperCAmelCase =SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.default_image_processor __UpperCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase =image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): __UpperCAmelCase =model(**__SCREAMING_SNAKE_CASE ) # verify the logits __UpperCAmelCase =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
68
0
"""simple docstring""" def lowercase__( __SCREAMING_SNAKE_CASE : list[list[int | float]] ): lowercase_ : Dict = len(A_ ) lowercase_ : int = len(matrix[0] ) lowercase_ : Dict = min(A_ , A_ ) for row in range(A_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , A_ ): lowercase_ : int = matrix[col][row] / matrix[row][row] for i in range(A_ , A_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows lowercase_ : Optional[Any] = True for i in range(row + 1 , A_ ): if matrix[i][row] != 0: lowercase_ , lowercase_ : List[str] = matrix[i], matrix[row] lowercase_ : List[Any] = False break if reduce: rank -= 1 for i in range(A_ ): lowercase_ : Tuple = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
425
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A = logging.get_logger(__name__) __A = {"vocab_file": "spiece.model"} __A = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } __A = { "AI-Sweden/gpt-sw3-126m": 20_48, "AI-Sweden/gpt-sw3-350m": 20_48, "AI-Sweden/gpt-sw3-1.6b": 20_48, "AI-Sweden/gpt-sw3-6.7b": 20_48, "AI-Sweden/gpt-sw3-20b": 20_48, } class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : int = VOCAB_FILES_NAMES lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : List[str]=False , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Optional[Dict[str, Any]] = None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> None: __UpperCAmelCase ={} if sp_model_kwargs is None else sp_model_kwargs __UpperCAmelCase =kwargs.get("""name_or_path""" ) if name_or_path is None: logger.warning( """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,""" """ you are testing the model, this can safely be ignored""" ) __UpperCAmelCase ="""None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __UpperCAmelCase ="""<|endoftext|>""" if eos_token is None else eos_token __UpperCAmelCase ="""<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __UpperCAmelCase =unk_token if pad_token is None else pad_token __UpperCAmelCase =eos_token if bos_token is None else bos_token else: __UpperCAmelCase ="""<pad>""" if pad_token is None else pad_token __UpperCAmelCase ="""<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=__SCREAMING_SNAKE_CASE , remove_space=__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) __UpperCAmelCase =do_lower_case __UpperCAmelCase =remove_space __UpperCAmelCase =keep_accents __UpperCAmelCase =vocab_file __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) # Used for whitespace normalization in input texts # fmt : off __UpperCAmelCase ={""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __UpperCAmelCase =re.compile( f'''[{"".join(map(__SCREAMING_SNAKE_CASE , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self : Any ) -> str: __UpperCAmelCase =self.__dict__.copy() __UpperCAmelCase =None return state def __setstate__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: __UpperCAmelCase =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __UpperCAmelCase ={} __UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def _a ( self : Union[str, Any] ) -> int: return len(self.sp_model ) def _a ( self : Dict , __SCREAMING_SNAKE_CASE : str ) -> str: __UpperCAmelCase =self.non_printing_characters_re.sub("""""" , __SCREAMING_SNAKE_CASE ) # Normalize whitespaces __UpperCAmelCase ="""""".join([char if char not in self.whitespaces else """ """ for char in text] ) # NFC Unicode normalization __UpperCAmelCase =unicodedata.normalize("""NFC""" , __SCREAMING_SNAKE_CASE ) return text def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _a ( self : List[str] , __SCREAMING_SNAKE_CASE : str ) -> int: return self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : int ) -> str: return self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) @staticmethod def _a ( __SCREAMING_SNAKE_CASE : str ) -> str: return out_string def _a ( self : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> str: __UpperCAmelCase =[] __UpperCAmelCase ="""""" __UpperCAmelCase =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token __UpperCAmelCase =True __UpperCAmelCase =[] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =False out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string def _a ( self : Any ) -> Dict[str, int]: __UpperCAmelCase ={self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __UpperCAmelCase =os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , """wb""" ) as fi: __UpperCAmelCase =self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, List[str]] , __SCREAMING_SNAKE_CASE : Union[str, bool] = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __UpperCAmelCase =self.preprocess_text(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) else: __UpperCAmelCase =[self.preprocess_text(__SCREAMING_SNAKE_CASE ) for t in text] __UpperCAmelCase =self.sp_model.encode(__SCREAMING_SNAKE_CASE ) if return_tensors is True or return_tensors == "pt": __UpperCAmelCase =torch.tensor(__SCREAMING_SNAKE_CASE ) return token_ids def _a ( self : str , __SCREAMING_SNAKE_CASE : Union[int, List[int]] ) -> str: return self.sp_model.decode(__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : "Conversation" ) -> List[int]: __UpperCAmelCase =[f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __UpperCAmelCase =( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(__SCREAMING_SNAKE_CASE ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=__SCREAMING_SNAKE_CASE )
68
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase_ : Tuple = { '''configuration_clap''': [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapAudioConfig''', '''ClapConfig''', '''ClapTextConfig''', ], '''processing_clap''': ['''ClapProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : Any = [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapModel''', '''ClapPreTrainedModel''', '''ClapTextModel''', '''ClapTextModelWithProjection''', '''ClapAudioModel''', '''ClapAudioModelWithProjection''', ] UpperCamelCase_ : Optional[int] = ['''ClapFeatureExtractor'''] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys UpperCamelCase_ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
115
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __A = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : Union[str, None] = None , __SCREAMING_SNAKE_CASE : Union[List[str], None] = None , __SCREAMING_SNAKE_CASE : Union[str, List[str], None] = None , __SCREAMING_SNAKE_CASE : bool = True , ) -> List[str]: __UpperCAmelCase =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )] if identifier is not None: __UpperCAmelCase =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n_ in n_identifier: __UpperCAmelCase =[file for file in files if n_ not in file] else: __UpperCAmelCase =[file for file in files if n_identifier not in file] __UpperCAmelCase =ignore_files or [] ignore_files.append("""__init__.py""" ) __UpperCAmelCase =[file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , __SCREAMING_SNAKE_CASE ) if only_modules: __UpperCAmelCase =file.split(""".""" )[0] try: __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: __UpperCAmelCase =doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _a ( self : Optional[Any] ) -> List[str]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""modeling""" __UpperCAmelCase =[ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""tokenization""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] ) -> Optional[Any]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""configuration""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : List[Any] ) -> Tuple: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase =["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase =Path("""docs/source""" ) __UpperCAmelCase =["""favicon.ico"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
68
0
import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) __snake_case :Optional[Any] =logging.getLogger() def lowerCamelCase_ ( lowerCAmelCase__ : Path , lowerCAmelCase__ : list ) -> Union[str, Any]: '''simple docstring''' A = '\n'.join(A_ ) Path(A_ ).open('w' ).writelines(A_ ) __snake_case :str ='patrickvonplaten/t5-tiny-random' __snake_case :Optional[int] ='sshleifer/bart-tiny-random' __snake_case :Tuple ='sshleifer/tiny-mbart' __snake_case :Optional[Any] =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class lowerCAmelCase__ ( _lowerCamelCase ): def __UpperCamelCase ( self : Tuple , __UpperCamelCase : List[str] ) -> Optional[Any]: A = Path(self.get_auto_remove_tmp_dir() ) / 'utest_input.source' A = input_file_name.parent / 'utest_output.txt' assert not output_file_name.exists() A = [' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County.'] _dump_articles(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) A = str(Path(self.get_auto_remove_tmp_dir() ) / 'scores.json' ) A = 'translation_en_to_de' if model == T5_TINY else 'summarization' A = f''' run_eval_search.py {model} {input_file_name} {output_file_name} --score_path {score_path} --task {task} --num_beams 2 --length_penalty 2.0 '''.split() with patch.object(__SCREAMING_SNAKE_CASE , 'argv' , __SCREAMING_SNAKE_CASE ): run_generate() assert Path(__SCREAMING_SNAKE_CASE ).exists() # os.remove(Path(output_file_name)) def __UpperCamelCase ( self : Dict ) -> Optional[Any]: self.run_eval_tester(__SCREAMING_SNAKE_CASE ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __UpperCamelCase ( self : Optional[Any] , __UpperCamelCase : Union[str, Any] ) -> Dict: self.run_eval_tester(__SCREAMING_SNAKE_CASE ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __UpperCamelCase ( self : Tuple , __UpperCamelCase : List[Any] ) -> Any: A = Path(self.get_auto_remove_tmp_dir() ) / 'utest_input.source' A = input_file_name.parent / 'utest_output.txt' assert not output_file_name.exists() A = { 'en': ['Machine learning is great, isn\'t it?', 'I like to eat bananas', 'Tomorrow is another great day!'], 'de': [ 'Maschinelles Lernen ist großartig, oder?', 'Ich esse gerne Bananen', 'Morgen ist wieder ein toller Tag!', ], } A = Path(self.get_auto_remove_tmp_dir() ) A = str(tmp_dir / 'scores.json' ) A = str(tmp_dir / 'val.target' ) _dump_articles(__SCREAMING_SNAKE_CASE , text['en'] ) _dump_articles(__SCREAMING_SNAKE_CASE , text['de'] ) A = 'translation_en_to_de' if model == T5_TINY else 'summarization' A = f''' run_eval_search.py {model} {str(__SCREAMING_SNAKE_CASE )} {str(__SCREAMING_SNAKE_CASE )} --score_path {score_path} --reference_path {reference_path} --task {task} '''.split() testargs.extend(['--search', 'num_beams=1:2 length_penalty=0.9:1.0'] ) with patch.object(__SCREAMING_SNAKE_CASE , 'argv' , __SCREAMING_SNAKE_CASE ): with CaptureStdout() as cs: run_search() A = [' num_beams | length_penalty', model, 'Best score args'] A = ['Info'] if "translation" in task: expected_strings.append('bleu' ) else: expected_strings.extend(__SCREAMING_SNAKE_CASE ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(__SCREAMING_SNAKE_CASE ).exists() os.remove(Path(__SCREAMING_SNAKE_CASE ) )
106
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __A = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def lowercase__ ( A_: int , A_: Optional[Any] , A_: List[str]=None ) -> List[str]: """simple docstring""" if rng is None: __UpperCAmelCase =random.Random() __UpperCAmelCase =1 for dim in shape: total_dims *= dim __UpperCAmelCase =[] for _ in range(A_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __UpperCAmelCase =np.array(A_ , dtype=jnp.intaa ).reshape(A_ ) return output def lowercase__ ( A_: List[str] , A_: List[str]=None ) -> Any: """simple docstring""" __UpperCAmelCase =ids_tensor(A_ , vocab_size=2 , rng=A_ ) # make sure that at least one token is attended to for each batch __UpperCAmelCase =1 return attn_mask @require_flax class _A : """simple docstring""" lowerCamelCase : Optional[Any] = None lowerCamelCase : int = () def _a ( self : str ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __UpperCAmelCase =2 __UpperCAmelCase =inputs["""input_ids"""].shape[-1] // 2 __UpperCAmelCase =inputs["""input_ids"""][:max_batch_size, :sequence_length] __UpperCAmelCase =jnp.ones_like(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __UpperCAmelCase =input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __UpperCAmelCase =config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _a ( self : Union[str, Any] ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =0 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model_class.__name__[4:] # Skip the "Flax" at the beginning __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =pt_model_class(__SCREAMING_SNAKE_CASE ).eval() __UpperCAmelCase =load_flax_weights_in_pytorch_model(__SCREAMING_SNAKE_CASE , flax_model.params ) __UpperCAmelCase =flax_model.generate(__SCREAMING_SNAKE_CASE ).sequences __UpperCAmelCase =pt_model.generate(torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __UpperCAmelCase =flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> List[str]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[Any] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =False __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =2 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _a ( self : Union[str, Any] ) -> List[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =True __UpperCAmelCase =max_length __UpperCAmelCase =0.8 __UpperCAmelCase =10 __UpperCAmelCase =0.3 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Optional[int] ) -> Any: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() __UpperCAmelCase =max_length __UpperCAmelCase =2 __UpperCAmelCase =1 __UpperCAmelCase =8 __UpperCAmelCase =9 for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : List[str] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =False __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =True __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self : Dict ) -> Tuple: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCAmelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCAmelCase =2 __UpperCAmelCase =max_length for model_class in self.all_generative_model_classes: __UpperCAmelCase =model_class(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model.generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertEqual(generation_outputs.shape[-1] , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =jit(model.generate ) __UpperCAmelCase =jit_generate(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : int ) -> Any: __UpperCAmelCase =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) __UpperCAmelCase =FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) __UpperCAmelCase ="""Hello world""" __UpperCAmelCase =tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """do_samples""" ): model.generate(__SCREAMING_SNAKE_CASE , do_samples=__SCREAMING_SNAKE_CASE ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , """foo""" ): __UpperCAmelCase ={"""foo""": """bar"""} model.generate(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
68
0
"""simple docstring""" def __UpperCAmelCase ( __lowerCamelCase ) -> str: lowercase__ : Tuple = len(A_ ) lowercase__ : int = sum(A_ ) lowercase__ : Union[str, Any] = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): lowercase__ : int = True for i in range(1 , s + 1 ): lowercase__ : Tuple = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): lowercase__ : List[str] = dp[i][j - 1] if arr[i - 1] <= j: lowercase__ : Union[str, Any] = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: lowercase__ : List[str] = s - 2 * j break return diff
560
from __future__ import annotations from collections.abc import Iterator class _A : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : int ) -> None: __UpperCAmelCase =value __UpperCAmelCase =None __UpperCAmelCase =None class _A : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Node ) -> None: __UpperCAmelCase =tree def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : int ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def __snake_case ( ) -> Union[str, Any]: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(A_ ): requests.request('''GET''' , '''https://huggingface.co''' ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request('''GET''' , '''https://huggingface.co''' , timeout=1.0 ) @pytest.mark.integration def __snake_case ( ) -> int: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request('''GET''' , '''https://huggingface.co''' ) def __snake_case ( ) -> Optional[int]: """simple docstring""" with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(A_ ): http_head('''https://huggingface.co''' )
51
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def lowercase__ ( A_: Union[str, Any] ) -> List[Any]: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=A_ , AssumeRolePolicyDocument=json.dumps(A_ , indent=2 ) ) __UpperCAmelCase ={ """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=A_ , PolicyName=F'''{role_name}_policy_permission''' , PolicyDocument=json.dumps(A_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F'''role {role_name} already exists. Using existing one''' ) def lowercase__ ( A_: Dict ) -> Any: """simple docstring""" __UpperCAmelCase =botoa.client("""iam""" ) return iam_client.get_role(RoleName=A_ )["Role"]["Arn"] def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase =_ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , A_ , ) __UpperCAmelCase =None if credentials_configuration == 0: __UpperCAmelCase =_ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) __UpperCAmelCase =aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __UpperCAmelCase =_ask_field("""AWS Access Key ID: """ ) __UpperCAmelCase =aws_access_key_id __UpperCAmelCase =_ask_field("""AWS Secret Access Key: """ ) __UpperCAmelCase =aws_secret_access_key __UpperCAmelCase =_ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) __UpperCAmelCase =aws_region __UpperCAmelCase =_ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , A_ , ) if role_management == 0: __UpperCAmelCase =_ask_field("""Enter your IAM role name: """ ) else: __UpperCAmelCase ="""accelerate_sagemaker_execution_role""" print(F'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(A_ ) __UpperCAmelCase =_ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_custom_docker_image: __UpperCAmelCase =_ask_field("""Enter your Docker image: """ , lambda A_ : str(A_ ).lower() ) __UpperCAmelCase =_ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_inputs_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =None if is_sagemaker_metrics_enabled: __UpperCAmelCase =_ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda A_ : str(A_ ).lower() , ) __UpperCAmelCase =_ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) __UpperCAmelCase ={} __UpperCAmelCase =_ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_dynamo: __UpperCAmelCase ="""dynamo_""" __UpperCAmelCase =_ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __UpperCAmelCase =_ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) if use_custom_options: __UpperCAmelCase =_ask_options( """Which mode do you want to use?""" , A_ , lambda A_ : TORCH_DYNAMO_MODES[int(A_ )] , default="""default""" , ) __UpperCAmelCase =_ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase =_ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=A_ , error_message="""Please enter yes or no.""" , ) __UpperCAmelCase ="""Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __UpperCAmelCase =_ask_options( A_ , A_ , lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __UpperCAmelCase =_ask_field(A_ , lambda A_ : str(A_ ).lower() , default="""ml.p3.2xlarge""" ) __UpperCAmelCase =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __UpperCAmelCase =_ask_field( """How many machines do you want use? [1]: """ , A_ , default=1 , ) __UpperCAmelCase =_ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=A_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=A_ , use_cpu=A_ , dynamo_config=A_ , eca_instance_type=A_ , profile=A_ , region=A_ , iam_role_name=A_ , mixed_precision=A_ , num_machines=A_ , sagemaker_inputs_file=A_ , sagemaker_metrics_file=A_ , )
68
0
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __magic_name__ = TypeVar('''T''') class _lowerCAmelCase ( Generic[T] ): lowercase_ : deque[T] # Cache store of keys lowercase_ : set[T] # References of the keys in cache lowercase_ : int = 10 # Maximum capacity of cache def __init__( self , a_ ) -> None: _UpperCAmelCase = deque() _UpperCAmelCase = set() if not n: _UpperCAmelCase = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0." ) else: _UpperCAmelCase = n def _a ( self , a_ ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: _UpperCAmelCase = self.dq_store.pop() self.key_reference.remove(__SCREAMING_SNAKE_CASE ) else: self.dq_store.remove(__SCREAMING_SNAKE_CASE ) self.dq_store.appendleft(__SCREAMING_SNAKE_CASE ) self.key_reference.add(__SCREAMING_SNAKE_CASE ) def _a ( self ) -> None: for k in self.dq_store: print(__SCREAMING_SNAKE_CASE ) def __repr__( self ) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ = LRUCache(4) lru_cache.refer('''A''') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('''A''') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
657
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Tuple = 'ctrl' lowerCamelCase : Any = ['past_key_values'] lowerCamelCase : Optional[int] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=246534 , __SCREAMING_SNAKE_CASE : int=256 , __SCREAMING_SNAKE_CASE : Optional[Any]=1280 , __SCREAMING_SNAKE_CASE : Optional[Any]=8192 , __SCREAMING_SNAKE_CASE : int=48 , __SCREAMING_SNAKE_CASE : Union[str, Any]=16 , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : List[Any]=1e-6 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : Union[str, Any]=True , **__SCREAMING_SNAKE_CASE : int , ) -> Any: __UpperCAmelCase =vocab_size __UpperCAmelCase =n_positions __UpperCAmelCase =n_embd __UpperCAmelCase =n_layer __UpperCAmelCase =n_head __UpperCAmelCase =dff __UpperCAmelCase =resid_pdrop __UpperCAmelCase =embd_pdrop __UpperCAmelCase =layer_norm_epsilon __UpperCAmelCase =initializer_range __UpperCAmelCase =use_cache super().__init__(**__SCREAMING_SNAKE_CASE )
68
0
'''simple docstring''' import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging a_ = logging.get_logger(__name__) def _a( UpperCamelCase__ : Any, UpperCamelCase__ : Tuple, UpperCamelCase__ : Tuple, UpperCamelCase__ : Dict=False ): '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise if not is_sharded: SCREAMING_SNAKE_CASE__ : str =os.path.abspath(A_ ) logger.info(f"Loading PyTorch weights from {pt_path}" ) SCREAMING_SNAKE_CASE__ : Any =torch.load(A_, map_location='''cpu''' ) logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters." ) SCREAMING_SNAKE_CASE__ : List[str] =convert_pytorch_state_dict_to_flax(A_, A_ ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files SCREAMING_SNAKE_CASE__ : int =convert_pytorch_sharded_state_dict_to_flax(A_, A_ ) return flax_state_dict def _a( UpperCamelCase__ : Tuple[str], UpperCamelCase__ : np.ndarray, UpperCamelCase__ : Dict[str, jnp.ndarray], UpperCamelCase__ : str, ): '''simple docstring''' def is_key_or_prefix_key_in_dict(UpperCamelCase__ : Tuple[str] ) -> bool: return len(set(A_ ) & {key, (model_prefix,) + key} ) > 0 # layer norm SCREAMING_SNAKE_CASE__ : Union[str, Any] =pt_tuple_key[:-1] + ('''scale''',) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(A_ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean SCREAMING_SNAKE_CASE__ : int =pt_tuple_key[:-1] + ('''mean''',) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(A_ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var SCREAMING_SNAKE_CASE__ : Tuple =pt_tuple_key[:-1] + ('''var''',) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(A_ ): return renamed_pt_tuple_key, pt_tensor # embedding SCREAMING_SNAKE_CASE__ : Optional[int] =pt_tuple_key[:-1] + ('''embedding''',) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(A_ ): return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE__ : Optional[int] =pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(A_ ): SCREAMING_SNAKE_CASE__ : int =pt_tensor.transpose(2, 3, 1, 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE__ : Tuple =pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(A_ ): SCREAMING_SNAKE_CASE__ : Optional[Any] =pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE__ : Any =pt_tuple_key[:-1] + ('''weight''',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE__ : Tuple =pt_tuple_key[:-1] + ('''bias''',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 SCREAMING_SNAKE_CASE__ : Any =None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): SCREAMING_SNAKE_CASE__ : Union[str, Any] =pt_tuple_key[-2] + '''_g''' elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): SCREAMING_SNAKE_CASE__ : Dict =pt_tuple_key[-2] + '''_v''' if name is not None: SCREAMING_SNAKE_CASE__ : List[Any] =pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def _a( UpperCamelCase__ : str, UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] ={k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE__ : Tuple =flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: SCREAMING_SNAKE_CASE__ : Optional[Any] =flax_model.params['''params'''] else: SCREAMING_SNAKE_CASE__ : Tuple =flax_model.params SCREAMING_SNAKE_CASE__ : Tuple =flatten_dict(A_ ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE__ : Dict =flatten_dict(flax_model.params['''batch_stats'''] ) random_flax_state_dict.update(A_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ={} SCREAMING_SNAKE_CASE__ : List[str] =(model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =(model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE__ : Any =tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary SCREAMING_SNAKE_CASE__ : Optional[Any] =pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE__ : Any =pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =rename_key_and_reshape_tensor( A_, A_, A_, A_ ) # add model prefix if necessary SCREAMING_SNAKE_CASE__ : Dict =(model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE__ : Dict =(model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =jnp.asarray(A_ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(A_, A_ ) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : Union[str, Any] =jnp.asarray(A_ ) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : Dict =jnp.asarray(A_ ) return unflatten_dict(A_ ) def _a( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : List[str] ): '''simple docstring''' import torch # Load the index SCREAMING_SNAKE_CASE__ : List[Any] ={} for shard_file in shard_filenames: # load using msgpack utils SCREAMING_SNAKE_CASE__ : int =torch.load(A_ ) SCREAMING_SNAKE_CASE__ : Tuple ={k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE__ : Optional[int] =flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE__ : Optional[int] =flax_model.params['''params'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] =flatten_dict(A_ ) random_flax_state_dict.update(flatten_dict(flax_model.params['''batch_stats'''] ) ) else: SCREAMING_SNAKE_CASE__ : str =flax_model.params SCREAMING_SNAKE_CASE__ : Optional[Any] =flatten_dict(A_ ) SCREAMING_SNAKE_CASE__ : List[str] =(model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE__ : Optional[int] =(model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE__ : str =tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary SCREAMING_SNAKE_CASE__ : List[str] =pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE__ : List[str] =pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str =rename_key_and_reshape_tensor( A_, A_, A_, A_ ) # add model prefix if necessary SCREAMING_SNAKE_CASE__ : Union[str, Any] =(model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE__ : Optional[Any] =(model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: SCREAMING_SNAKE_CASE__ : Tuple =jnp.asarray(A_ ) continue if "var" in flax_key[-1]: SCREAMING_SNAKE_CASE__ : str =jnp.asarray(A_ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(A_, A_ ) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : int =jnp.asarray(A_ ) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : Any =jnp.asarray(A_ ) return unflatten_dict(A_ ) def _a( UpperCamelCase__ : int, UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =os.path.abspath(A_ ) logger.info(f"Loading Flax weights from {flax_checkpoint_path}" ) # import correct flax class SCREAMING_SNAKE_CASE__ : Optional[Any] =getattr(A_, '''Flax''' + model.__class__.__name__ ) # load flax weight dict with open(A_, '''rb''' ) as state_f: try: SCREAMING_SNAKE_CASE__ : Any =from_bytes(A_, state_f.read() ) except UnpicklingError: raise EnvironmentError(f"Unable to convert {flax_checkpoint_path} to Flax deserializable object. " ) return load_flax_weights_in_pytorch_model(A_, A_ ) def _a( UpperCamelCase__ : List[Any], UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE__ : List[str] =flatten_dict(jax.tree_util.tree_map(lambda UpperCamelCase__ : x.dtype == jnp.bfloataa, A_ ) ).values() if any(A_ ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE__ : int =jax.tree_util.tree_map( lambda UpperCamelCase__ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params, A_ ) SCREAMING_SNAKE_CASE__ : str =flatten_dict(A_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =pt_model.state_dict() SCREAMING_SNAKE_CASE__ : Optional[int] =(pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) SCREAMING_SNAKE_CASE__ : Optional[int] =(pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE__ : Union[str, Any] =[] SCREAMING_SNAKE_CASE__ : Tuple =set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[int] =flax_key_tuple[0] == pt_model.base_model_prefix SCREAMING_SNAKE_CASE__ : Tuple ='''.'''.join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE__ : str =flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE__ : List[Any] =(pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(A_ ) not in pt_model_dict: # conv layer SCREAMING_SNAKE_CASE__ : Tuple =flax_key_tuple[:-1] + ('''weight''',) SCREAMING_SNAKE_CASE__ : Union[str, Any] =jnp.transpose(A_, (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(A_ ) not in pt_model_dict: # linear layer SCREAMING_SNAKE_CASE__ : Optional[Any] =flax_key_tuple[:-1] + ('''weight''',) SCREAMING_SNAKE_CASE__ : Any =flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: SCREAMING_SNAKE_CASE__ : Optional[int] =flax_key_tuple[:-1] + ('''weight''',) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE__ : Optional[int] =flax_key_tuple[:-1] + ('''running_mean''',) elif "var" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE__ : Optional[Any] =flax_key_tuple[:-1] + ('''running_var''',) if "batch_stats" in flax_state: SCREAMING_SNAKE_CASE__ : Dict ='''.'''.join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: SCREAMING_SNAKE_CASE__ : int ='''.'''.join(A_ ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. SCREAMING_SNAKE_CASE__ : Dict ={} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: SCREAMING_SNAKE_CASE__ : str =key.split('''.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =None if key_components[-3::2] == ["parametrizations", "original0"]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =key_components[-2] + '''_g''' elif key_components[-3::2] == ["parametrizations", "original1"]: SCREAMING_SNAKE_CASE__ : Dict =key_components[-2] + '''_v''' if name is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] =key_components[:-3] + [name] SCREAMING_SNAKE_CASE__ : Tuple ='''.'''.join(A_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =key if flax_key in special_pt_names: SCREAMING_SNAKE_CASE__ : Optional[int] =special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.asarray(A_ ) if not isinstance(A_, np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE__ : List[str] =torch.from_numpy(A_ ) # remove from missing keys missing_keys.remove(A_ ) else: # weight is not expected by PyTorch model unexpected_keys.append(A_ ) pt_model.load_state_dict(A_ ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE__ : int =list(A_ ) if len(A_ ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) else: logger.warning(f"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n" ) if len(A_ ) > 0: logger.warning( f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" ''' use it for predictions and inference.''' ) else: logger.warning( f"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n" '''If your task is similar to the task the model of the checkpoint was trained on, ''' f"you can already use {pt_model.__class__.__name__} for predictions without further training." ) return pt_model
296
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = [ ["attention", "attn"], ["encoder_attention", "encoder_attn"], ["q_lin", "q_proj"], ["k_lin", "k_proj"], ["v_lin", "v_proj"], ["out_lin", "out_proj"], ["norm_embeddings", "layernorm_embedding"], ["position_embeddings", "embed_positions"], ["embeddings", "embed_tokens"], ["ffn.lin", "fc"], ] def lowercase__ ( A_: Optional[Any] ) -> Union[str, Any]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __UpperCAmelCase =k.replace(A_ , A_ ) if k.startswith("""encoder""" ): __UpperCAmelCase =k.replace(""".attn""" , """.self_attn""" ) __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): __UpperCAmelCase =k.replace("""norm1""" , """self_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm2""" , """encoder_attn_layer_norm""" ) __UpperCAmelCase =k.replace("""norm3""" , """final_layer_norm""" ) return k def lowercase__ ( A_: Tuple ) -> str: """simple docstring""" __UpperCAmelCase =[ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: __UpperCAmelCase =sd.pop(A_ ) __UpperCAmelCase =k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd __UpperCAmelCase =v __A = ["START"] @torch.no_grad() def lowercase__ ( A_: List[Any] , A_: str , A_: int ) -> Optional[int]: """simple docstring""" __UpperCAmelCase =torch.load(A_ , map_location="""cpu""" ) __UpperCAmelCase =model["""model"""] __UpperCAmelCase =BlenderbotConfig.from_json_file(A_ ) __UpperCAmelCase =BlenderbotForConditionalGeneration(A_ ) __UpperCAmelCase =m.model.state_dict().keys() __UpperCAmelCase =[] __UpperCAmelCase ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue __UpperCAmelCase =rename_state_dict_key(A_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __UpperCAmelCase =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(A_ ) m.model.load_state_dict(A_ , strict=A_ ) m.half() m.save_pretrained(A_ ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin") parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.") parser.add_argument( "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use" ) __A = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
68
0