code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase_ ( __snake_case , unittest.TestCase ): _UpperCamelCase : str = ShapEPipeline _UpperCamelCase : Any = ["prompt"] _UpperCamelCase : int = ["prompt"] _UpperCamelCase : Union[str, Any] = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] _UpperCamelCase : Optional[Any] = False @property def __a ( self ): return 3_2 @property def __a ( self ): return 3_2 @property def __a ( self ): return self.time_input_dim * 4 @property def __a ( self ): return 8 @property def __a ( self ): _lowercase : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def __a ( self ): torch.manual_seed(0 ) _lowercase : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModelWithProjection(_lowerCAmelCase ) @property def __a ( self ): torch.manual_seed(0 ) _lowercase : Optional[int] = { 'num_attention_heads': 2, 'attention_head_dim': 1_6, 'embedding_dim': self.time_input_dim, 'num_embeddings': 3_2, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } _lowercase : Optional[Any] = PriorTransformer(**_lowerCAmelCase ) return model @property def __a ( self ): torch.manual_seed(0 ) _lowercase : Optional[int] = { 'param_shapes': ( (self.renderer_dim, 9_3), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 1_2, 'background': ( 0.1, 0.1, 0.1, ), } _lowercase : List[Any] = ShapERenderer(**_lowerCAmelCase ) return model def __a ( self ): _lowercase : Optional[Any] = self.dummy_prior _lowercase : Dict = self.dummy_text_encoder _lowercase : List[str] = self.dummy_tokenizer _lowercase : Union[str, Any] = self.dummy_renderer _lowercase : List[str] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1_0_2_4 , prediction_type='sample' , use_karras_sigmas=_lowerCAmelCase , clip_sample=_lowerCAmelCase , clip_sample_range=1.0 , ) _lowercase : List[str] = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def __a ( self , _lowerCAmelCase , _lowerCAmelCase=0 ): if str(_lowerCAmelCase ).startswith('mps' ): _lowercase : Optional[Any] = torch.manual_seed(_lowerCAmelCase ) else: _lowercase : Optional[int] = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) _lowercase : List[Any] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 3_2, 'output_type': 'np', } return inputs def __a ( self ): _lowercase : Optional[int] = 'cpu' _lowercase : List[Any] = self.get_dummy_components() _lowercase : Tuple = self.pipeline_class(**_lowerCAmelCase ) _lowercase : Union[str, Any] = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _lowercase : Union[str, Any] = pipe(**self.get_dummy_inputs(_lowerCAmelCase ) ) _lowercase : str = output.images[0] _lowercase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (2_0, 3_2, 3_2, 3) _lowercase : str = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __a ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __a ( self ): _lowercase : List[Any] = torch_device == 'cpu' _lowercase : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_lowerCAmelCase , relax_max_difference=_lowerCAmelCase , ) def __a ( self ): _lowercase : Union[str, Any] = self.get_dummy_components() _lowercase : Optional[int] = self.pipeline_class(**_lowerCAmelCase ) _lowercase : Any = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _lowercase : str = 1 _lowercase : Optional[int] = 2 _lowercase : List[str] = self.get_dummy_inputs(_lowerCAmelCase ) for key in inputs.keys(): if key in self.batch_params: _lowercase : int = batch_size * [inputs[key]] _lowercase : Optional[int] = pipe(**_lowerCAmelCase , num_images_per_prompt=_lowerCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): def __a ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __a ( self ): _lowercase : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) _lowercase : Any = ShapEPipeline.from_pretrained('openai/shap-e' ) _lowercase : List[str] = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _lowercase : Tuple = torch.Generator(device=_lowerCAmelCase ).manual_seed(0 ) _lowercase : int = pipe( 'a shark' , generator=_lowerCAmelCase , guidance_scale=15.0 , num_inference_steps=6_4 , frame_size=6_4 , output_type='np' , ).images[0] assert images.shape == (2_0, 6_4, 6_4, 3) assert_mean_pixel_difference(_lowerCAmelCase , _lowerCAmelCase )
66
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = [False] * len(lowerCAmelCase__ ) lowercase = [-1] * len(lowerCAmelCase__ ) def dfs(lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = True lowercase = c for u in graph[v]: if not visited[u]: dfs(lowerCAmelCase__ ,1 - c ) for i in range(len(lowerCAmelCase__ ) ): if not visited[i]: dfs(lowerCAmelCase__ ,0 ) for i in range(len(lowerCAmelCase__ ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph __SCREAMING_SNAKE_CASE : List[str] ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
428
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available __SCREAMING_SNAKE_CASE ={ """configuration_ernie""": ["""ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ErnieConfig""", """ErnieOnnxConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE =[ """ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST""", """ErnieForCausalLM""", """ErnieForMaskedLM""", """ErnieForMultipleChoice""", """ErnieForNextSentencePrediction""", """ErnieForPreTraining""", """ErnieForQuestionAnswering""", """ErnieForSequenceClassification""", """ErnieForTokenClassification""", """ErnieModel""", """ErniePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
89
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed __SCREAMING_SNAKE_CASE =os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(f"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) __SCREAMING_SNAKE_CASE ="""sshleifer/student_marian_en_ro_6_1""" __SCREAMING_SNAKE_CASE ="""sshleifer/tiny-mbart""" @require_torch class __magic_name__ ( __UpperCAmelCase): '''simple docstring''' def _A ( self: List[Any] , _lowerCamelCase: List[Any]=False , _lowerCamelCase: List[Any]=None , _lowerCamelCase: int=True , _lowerCamelCase: Optional[int]=True , _lowerCamelCase: Any=True , _lowerCamelCase: Any=True , ): SCREAMING_SNAKE_CASE_ = self.run_trainer( eval_steps=1 , max_len=12 , model_name=_lowerCamelCase , num_train_epochs=1 , distributed=_lowerCamelCase , extra_args_str=_lowerCamelCase , predict_with_generate=_lowerCamelCase , do_train=_lowerCamelCase , do_eval=_lowerCamelCase , do_predict=_lowerCamelCase , ) SCREAMING_SNAKE_CASE_ = TrainerState.load_from_json(os.path.join(_lowerCamelCase , '''trainer_state.json''' ) ).log_history if not do_eval: return SCREAMING_SNAKE_CASE_ = [log for log in logs if '''eval_loss''' in log.keys()] SCREAMING_SNAKE_CASE_ = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats SCREAMING_SNAKE_CASE_ = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , _lowerCamelCase ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _A ( self: Optional[int] ): self.run_seqaseq_quick() @require_torch_multi_gpu def _A ( self: Optional[Any] ): self.run_seqaseq_quick(distributed=_lowerCamelCase ) @require_torch_multi_gpu def _A ( self: List[Any] ): self.run_seqaseq_quick(distributed=_lowerCamelCase ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def _A ( self: Optional[int] ): self.run_seqaseq_quick(distributed=_lowerCamelCase , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def _A ( self: Optional[Any] ): self.run_seqaseq_quick(distributed=_lowerCamelCase , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def _A ( self: Union[str, Any] ): self.run_seqaseq_quick(distributed=_lowerCamelCase , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=_lowerCamelCase ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def _A ( self: Optional[Any] ): self.run_seqaseq_quick( distributed=_lowerCamelCase , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=_lowerCamelCase ) @require_apex @require_torch_gpu def _A ( self: List[Any] ): # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=_lowerCamelCase , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=_lowerCamelCase , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def _A ( self: Union[str, Any] , _lowerCamelCase: Dict ): # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout SCREAMING_SNAKE_CASE_ = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } SCREAMING_SNAKE_CASE_ = experiments[experiment_id] SCREAMING_SNAKE_CASE_ = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} SCREAMING_SNAKE_CASE_ = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**_lowerCamelCase , extra_args_str=data['''extra_args_str'''] ) SCREAMING_SNAKE_CASE_ = len(re.findall(_lowerCamelCase , cl.err ) ) self.assertEqual(_lowerCamelCase , data['''n_matches'''] ) @slow def _A ( self: Any ): SCREAMING_SNAKE_CASE_ = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=_lowerCamelCase , learning_rate=3E-4 , num_train_epochs=10 , distributed=_lowerCamelCase , ) # Check metrics SCREAMING_SNAKE_CASE_ = TrainerState.load_from_json(os.path.join(_lowerCamelCase , '''trainer_state.json''' ) ).log_history SCREAMING_SNAKE_CASE_ = [log for log in logs if '''eval_loss''' in log.keys()] SCREAMING_SNAKE_CASE_ = eval_metrics[0] SCREAMING_SNAKE_CASE_ = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , _lowerCamelCase ) # test if do_predict saves generations and metrics SCREAMING_SNAKE_CASE_ = os.listdir(_lowerCamelCase ) SCREAMING_SNAKE_CASE_ = {os.path.basename(_lowerCamelCase ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _A ( self: Optional[int] ): from transformers.training_args import OptimizerNames def train_and_return_metrics(_lowerCamelCase: str ) -> Tuple[int, float]: SCREAMING_SNAKE_CASE_ = '''--skip_memory_metrics 0''' SCREAMING_SNAKE_CASE_ = self.run_trainer( max_len=1_28 , model_name=_lowerCamelCase , learning_rate=3E-4 , num_train_epochs=1 , optim=_lowerCamelCase , distributed=_lowerCamelCase , extra_args_str=_lowerCamelCase , do_eval=_lowerCamelCase , do_predict=_lowerCamelCase , n_gpus_to_use=1 , ) # Check metrics SCREAMING_SNAKE_CASE_ = TrainerState.load_from_json(Path(_lowerCamelCase , '''trainer_state.json''' ) ).log_history SCREAMING_SNAKE_CASE_ = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) SCREAMING_SNAKE_CASE_ = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) SCREAMING_SNAKE_CASE_ = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) SCREAMING_SNAKE_CASE_ = gpu_alloc_mem_orig - gpu_alloc_mem_bnb SCREAMING_SNAKE_CASE_ = gpu_peak_mem_orig + gpu_alloc_mem_orig SCREAMING_SNAKE_CASE_ = gpu_peak_mem_bnb + gpu_alloc_mem_bnb SCREAMING_SNAKE_CASE_ = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings SCREAMING_SNAKE_CASE_ = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( _lowerCamelCase , _lowerCamelCase , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f" a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and" f" gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB" , ) self.assertGreater( _lowerCamelCase , _lowerCamelCase , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f" a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and" f" gpu_total_mem_bnb={gpu_total_mem_bnb}MB" , ) self.assertEqual( _lowerCamelCase , _lowerCamelCase , f"loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}" ) def _A ( self: Union[str, Any] , _lowerCamelCase: int , _lowerCamelCase: str , _lowerCamelCase: int , _lowerCamelCase: float = 3E-3 , _lowerCamelCase: str = "adafactor" , _lowerCamelCase: bool = False , _lowerCamelCase: str = None , _lowerCamelCase: int = 0 , _lowerCamelCase: bool = True , _lowerCamelCase: bool = True , _lowerCamelCase: bool = True , _lowerCamelCase: bool = True , _lowerCamelCase: int = None , ): SCREAMING_SNAKE_CASE_ = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' SCREAMING_SNAKE_CASE_ = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ = f"\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(_lowerCamelCase )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(_lowerCamelCase )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n ".split() SCREAMING_SNAKE_CASE_ = f"\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(_lowerCamelCase )}\n ".split() SCREAMING_SNAKE_CASE_ = ''' --do_predict '''.split() SCREAMING_SNAKE_CASE_ = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f"--optim {optim}".split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: SCREAMING_SNAKE_CASE_ = get_gpu_count() SCREAMING_SNAKE_CASE_ = get_torch_dist_unique_port() SCREAMING_SNAKE_CASE_ = f"\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n ".split() SCREAMING_SNAKE_CASE_ = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(_lowerCamelCase , env=self.get_env() ) else: SCREAMING_SNAKE_CASE_ = ['''run_translation.py'''] + args with patch.object(_lowerCamelCase , '''argv''' , _lowerCamelCase ): main() return output_dir
89
1
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging lowerCAmelCase__ : str ={ """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def a__ ( A__, A__, A__, A__=None ): SCREAMING_SNAKE_CASE_ : Optional[int] = XLNetConfig.from_json_file(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Dict = finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(F'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) SCREAMING_SNAKE_CASE_ : int = finetuning_task SCREAMING_SNAKE_CASE_ : int = GLUE_TASKS_NUM_LABELS[finetuning_task] SCREAMING_SNAKE_CASE_ : Dict = XLNetForSequenceClassification(_UpperCAmelCase ) elif "squad" in finetuning_task: SCREAMING_SNAKE_CASE_ : Tuple = finetuning_task SCREAMING_SNAKE_CASE_ : Any = XLNetForQuestionAnswering(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE_ : Tuple = XLNetLMHeadModel(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(_UpperCAmelCase, _UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.join(_UpperCAmelCase, _UpperCAmelCase ) print(F'''Save PyTorch model to {os.path.abspath(_UpperCAmelCase )}''' ) torch.save(model.state_dict(), _UpperCAmelCase ) print(F'''Save configuration file to {os.path.abspath(_UpperCAmelCase )}''' ) with open(_UpperCAmelCase, 'w', encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase__ : int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--xlnet_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained XLNet model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--finetuning_task', default=None, type=str, help='Name of a task on which the XLNet TensorFlow model was fine-tuned', ) lowerCAmelCase__ : Any =parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
101
def UpperCamelCase ( _UpperCAmelCase : list[int] , _UpperCAmelCase : list[int] ) -> tuple[float, float]: '''simple docstring''' if not len(_UpperCAmelCase ) == len(_UpperCAmelCase ) == 3: raise ValueError("Please enter a valid equation." ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError("Both a & b of two equations can't be zero." ) # Extract the coefficients _lowercase , _lowercase , _lowercase : List[str] = equationa _lowercase , _lowercase , _lowercase : List[str] = equationa # Calculate the determinants of the matrices _lowercase : List[Any] = aa * ba - aa * ba _lowercase : Tuple = ca * ba - ca * ba _lowercase : Union[str, Any] = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("Infinite solutions. (Consistent system)" ) else: raise ValueError("No solution. (Inconsistent system)" ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: _lowercase : str = determinant_x / determinant _lowercase : Union[str, Any] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
461
0
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __lowerCAmelCase :Any = (7_20, 12_80) # Height, Width __lowerCAmelCase :Optional[int] = (0.4, 0.6) # if height or width lower than this scale, drop it. __lowerCAmelCase :int = 1 / 1_00 __lowerCAmelCase :int = '''''' __lowerCAmelCase :str = '''''' __lowerCAmelCase :int = '''''' __lowerCAmelCase :List[str] = 2_50 def A ( ): _snake_case , _snake_case : Tuple = get_dataset(_UpperCAmelCase , _UpperCAmelCase ) for index in range(_UpperCAmelCase ): _snake_case : Optional[int] = random.sample(range(len(_UpperCAmelCase ) ) , 4 ) _snake_case , _snake_case , _snake_case : int = update_image_and_anno( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , filter_scale=_UpperCAmelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' _snake_case : Tuple = random_chars(32 ) _snake_case : Any = path.split(os.sep )[-1].rsplit("." , 1 )[0] _snake_case : int = F"""{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}""" cva.imwrite(F"""{file_root}.jpg""" , _UpperCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}""" ) _snake_case : Optional[Any] = [] for anno in new_annos: _snake_case : Any = anno[3] - anno[1] _snake_case : int = anno[4] - anno[2] _snake_case : str = anno[1] + width / 2 _snake_case : Dict = anno[2] + height / 2 _snake_case : Dict = F"""{anno[0]} {x_center} {y_center} {width} {height}""" annos_list.append(_UpperCAmelCase ) with open(F"""{file_root}.txt""" , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def A ( UpperCAmelCase , UpperCAmelCase ): _snake_case : int = [] _snake_case : Tuple = [] for label_file in glob.glob(os.path.join(_UpperCAmelCase , "*.txt" ) ): _snake_case : List[str] = label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(_UpperCAmelCase ) as in_file: _snake_case : Union[str, Any] = in_file.readlines() _snake_case : int = os.path.join(_UpperCAmelCase , F"""{label_name}.jpg""" ) _snake_case : str = [] for obj_list in obj_lists: _snake_case : List[str] = obj_list.rstrip("\n" ).split(" " ) _snake_case : List[Any] = float(obj[1] ) - float(obj[3] ) / 2 _snake_case : List[Any] = float(obj[2] ) - float(obj[4] ) / 2 _snake_case : Union[str, Any] = float(obj[1] ) + float(obj[3] ) / 2 _snake_case : Optional[Any] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(_UpperCAmelCase ) labels.append(_UpperCAmelCase ) return img_paths, labels def A ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 0.0 , ): _snake_case : Optional[int] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) _snake_case : Dict = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _snake_case : str = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _snake_case : List[Any] = int(scale_x * output_size[1] ) _snake_case : Union[str, Any] = int(scale_y * output_size[0] ) _snake_case : List[str] = [] _snake_case : int = [] for i, index in enumerate(_UpperCAmelCase ): _snake_case : Optional[int] = all_img_list[index] path_list.append(_UpperCAmelCase ) _snake_case : Optional[int] = all_annos[index] _snake_case : List[str] = cva.imread(_UpperCAmelCase ) if i == 0: # top-left _snake_case : List[Any] = cva.resize(_UpperCAmelCase , (divid_point_x, divid_point_y) ) _snake_case : List[Any] = img for bbox in img_annos: _snake_case : Any = bbox[1] * scale_x _snake_case : Optional[Any] = bbox[2] * scale_y _snake_case : Tuple = bbox[3] * scale_x _snake_case : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right _snake_case : Tuple = cva.resize(_UpperCAmelCase , (output_size[1] - divid_point_x, divid_point_y) ) _snake_case : Union[str, Any] = img for bbox in img_annos: _snake_case : List[Any] = scale_x + bbox[1] * (1 - scale_x) _snake_case : Any = bbox[2] * scale_y _snake_case : List[str] = scale_x + bbox[3] * (1 - scale_x) _snake_case : List[str] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left _snake_case : int = cva.resize(_UpperCAmelCase , (divid_point_x, output_size[0] - divid_point_y) ) _snake_case : str = img for bbox in img_annos: _snake_case : str = bbox[1] * scale_x _snake_case : Optional[int] = scale_y + bbox[2] * (1 - scale_y) _snake_case : Optional[int] = bbox[3] * scale_x _snake_case : Optional[Any] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right _snake_case : Any = cva.resize( _UpperCAmelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) _snake_case : List[Any] = img for bbox in img_annos: _snake_case : int = scale_x + bbox[1] * (1 - scale_x) _snake_case : List[str] = scale_y + bbox[2] * (1 - scale_y) _snake_case : Union[str, Any] = scale_x + bbox[3] * (1 - scale_x) _snake_case : Optional[Any] = 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: _snake_case : str = [ 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 A ( UpperCAmelCase ): assert number_char > 1, "The number of character should greater than 1" _snake_case : List[Any] = ascii_lowercase + digits return "".join(random.choice(_UpperCAmelCase ) for _ in range(_UpperCAmelCase ) ) if __name__ == "__main__": main() print('DONE ✅')
716
import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) def A ( UpperCAmelCase ): if hor == 128: _snake_case : int = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") _snake_case : Tuple = (32, 128, 256) _snake_case : str = ("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: _snake_case : List[Any] = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") _snake_case : Optional[int] = (32, 64, 128, 256) _snake_case : int = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") _snake_case : Dict = torch.load(F"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) _snake_case : Dict = model.state_dict() _snake_case : Tuple = { "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 65_536, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } _snake_case : Any = UNetaDModel(**UpperCAmelCase ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) _snake_case : List[Any] = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): _snake_case : Optional[int] = state_dict.pop(UpperCAmelCase ) hf_value_function.load_state_dict(UpperCAmelCase ) torch.save(hf_value_function.state_dict() , F"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(F"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , "w" ) as f: json.dump(UpperCAmelCase , UpperCAmelCase ) def A ( ): _snake_case : Any = { "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 128, 256), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 65_536, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } _snake_case : Dict = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) _snake_case : Optional[int] = model _snake_case : List[str] = UNetaDModel(**UpperCAmelCase ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) _snake_case : Optional[int] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): _snake_case : Any = state_dict.pop(UpperCAmelCase ) hf_value_function.load_state_dict(UpperCAmelCase ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(UpperCAmelCase , UpperCAmelCase ) if __name__ == "__main__": unet(32) # unet(128) value_function()
278
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class lowerCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=1_3 , _lowerCAmelCase=2 , _lowerCAmelCase=2_4 , _lowerCAmelCase=1_6 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=3_2 , _lowerCAmelCase=5 , _lowerCAmelCase=4 , _lowerCAmelCase=3_7 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=1_0 , _lowerCAmelCase=0.02 , _lowerCAmelCase=None , _lowerCAmelCase=2 , _lowerCAmelCase=2 , ): _lowercase : List[Any] = parent _lowercase : Dict = batch_size _lowercase : int = patch_size _lowercase : int = max_length _lowercase : Optional[Any] = num_mel_bins _lowercase : Any = is_training _lowercase : int = use_labels _lowercase : Dict = hidden_size _lowercase : int = num_hidden_layers _lowercase : Any = num_attention_heads _lowercase : str = intermediate_size _lowercase : Tuple = hidden_act _lowercase : Optional[int] = hidden_dropout_prob _lowercase : List[Any] = attention_probs_dropout_prob _lowercase : Dict = type_sequence_label_size _lowercase : List[str] = initializer_range _lowercase : List[Any] = scope _lowercase : str = frequency_stride _lowercase : Optional[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _lowercase : Optional[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 _lowercase : int = (self.max_length - self.patch_size) // self.time_stride + 1 _lowercase : List[Any] = frequency_out_dimension * time_out_dimension _lowercase : Tuple = num_patches + 2 def __a ( self ): _lowercase : List[str] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) _lowercase : Dict = None if self.use_labels: _lowercase : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowercase : Union[str, Any] = self.get_config() return config, input_values, labels def __a ( self ): return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , 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 , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): _lowercase : Dict = ASTModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _lowercase : List[str] = model(_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __a ( self ): _lowercase : Optional[int] = self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ) : Union[str, Any] = config_and_inputs _lowercase : Optional[int] = {'input_values': input_values} return config, inputs_dict @require_torch class lowerCAmelCase_ ( __snake_case , __snake_case , unittest.TestCase ): _UpperCamelCase : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) _UpperCamelCase : Tuple = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) _UpperCamelCase : int = False _UpperCamelCase : Optional[Any] = False _UpperCamelCase : Any = False _UpperCamelCase : str = False def __a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def __a ( self ): _lowercase : Optional[Any] = ASTModelTester(self ) _lowercase : List[Any] = ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=3_7 ) def __a ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='AST does not use inputs_embeds' ) def __a ( self ): pass def __a ( self ): _lowercase , _lowercase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : List[Any] = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowercase : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , nn.Linear ) ) def __a ( self ): _lowercase , _lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : List[Any] = model_class(_lowerCAmelCase ) _lowercase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowercase : List[str] = [*signature.parameters.keys()] _lowercase : Tuple = ['input_values'] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def __a ( self ): _lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) @slow def __a ( self ): for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : Any = ASTModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) def __magic_name__ ( ) -> Any: _lowercase : List[Any] = hf_hub_download( repo_id='nielsr/audio-spectogram-transformer-checkpoint' , filename='sample_audio.flac' , repo_type='dataset' ) _lowercase , _lowercase : Tuple = torchaudio.load(SCREAMING_SNAKE_CASE ) return audio, sampling_rate @require_torch @require_torchaudio class lowerCAmelCase_ ( unittest.TestCase ): @cached_property def __a ( self ): return ( ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' ) if is_torchaudio_available() else None ) @slow def __a ( self ): _lowercase : List[Any] = self.default_feature_extractor _lowercase : List[Any] = ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' ).to(_lowerCAmelCase ) _lowercase : List[Any] = self.default_feature_extractor _lowercase , _lowercase : Any = prepare_audio() _lowercase : int = audio.squeeze().numpy() _lowercase : List[str] = feature_extractor(_lowerCAmelCase , sampling_rate=_lowerCAmelCase , return_tensors='pt' ).to(_lowerCAmelCase ) # forward pass with torch.no_grad(): _lowercase : List[str] = model(**_lowerCAmelCase ) # verify the logits _lowercase : Any = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) _lowercase : Dict = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(_lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1E-4 ) )
66
from PIL import Image def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Image: def brightness(SCREAMING_SNAKE_CASE ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError('level must be between -255.0 (black) and 255.0 (white)' ) return img.point(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 UpperCamelCase = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
66
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "ctrl" _A = ["past_key_values"] _A = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , lowercase__=24_6534 , lowercase__=256 , lowercase__=1280 , lowercase__=8192 , lowercase__=48 , lowercase__=16 , lowercase__=0.1 , lowercase__=0.1 , lowercase__=1e-6 , lowercase__=0.02 , lowercase__=True , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = vocab_size SCREAMING_SNAKE_CASE_ : Any = n_positions SCREAMING_SNAKE_CASE_ : Any = n_embd SCREAMING_SNAKE_CASE_ : Any = n_layer SCREAMING_SNAKE_CASE_ : Optional[int] = n_head SCREAMING_SNAKE_CASE_ : List[Any] = dff SCREAMING_SNAKE_CASE_ : List[str] = resid_pdrop SCREAMING_SNAKE_CASE_ : List[Any] = embd_pdrop SCREAMING_SNAKE_CASE_ : str = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = use_cache super().__init__(**lowercase__ )
714
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
0
'''simple docstring''' import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def __A ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(snake_case_ ) def __A ( _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main __SCREAMING_SNAKE_CASE : int = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(snake_case_ , id=snake_case_ )
211
'''simple docstring''' import random def UpperCamelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' __lowerCAmelCase = num - 1 __lowerCAmelCase = 0 while s % 2 == 0: __lowerCAmelCase = s // 2 t += 1 for _ in range(5 ): __lowerCAmelCase = random.randrange(2 , num - 1 ) __lowerCAmelCase = pow(snake_case_ , snake_case_ , snake_case_ ) if v != 1: __lowerCAmelCase = 0 while v != (num - 1): if i == t - 1: return False else: __lowerCAmelCase = i + 1 __lowerCAmelCase = (v**2) % num return True def UpperCamelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if num < 2: return False __lowerCAmelCase = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(snake_case_ ) def UpperCamelCase_ ( snake_case_ : int = 10_24 ) -> int: '''simple docstring''' while True: __lowerCAmelCase = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(snake_case_ ): return num if __name__ == "__main__": _A : List[Any] = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
427
0
"""simple docstring""" import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right SCREAMING_SNAKE_CASE_ = 12_80_22 SCREAMING_SNAKE_CASE_ = 12_80_28 @require_sentencepiece class snake_case_ ( a_ ,unittest.TestCase ): __lowerCAmelCase = MaMaaaTokenizer __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = True def snake_case_ ( self ): super().setUp() a_ : str = ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"] a_ : List[str] = dict(zip(a_ , range(len(a_ ) ) ) ) a_ : List[str] = Path(self.tmpdirname ) save_json(a_ , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(a_ , save_dir / VOCAB_FILES_NAMES["spm_file"] ) a_ : Optional[int] = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case_ ( self , **a_ ): return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **a_ ) def snake_case_ ( self , a_ ): return ( "This is a test", "This is a test", ) def snake_case_ ( self ): a_ : str = "</s>" a_ : List[str] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def snake_case_ ( self ): a_ : Optional[int] = self.get_tokenizer() a_ : List[Any] = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "</s>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "<s>" ) self.assertEqual(len(a_ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip("Skip this test while all models are still to be uploaded." ) def snake_case_ ( self ): pass def snake_case_ ( self ): a_ : List[str] = self.get_tokenizer() a_ : Tuple = tokenizer.tokenize("This is a test" ) self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a_ ) , [2, 3, 4, 5, 6] , ) a_ : Tuple = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] ) a_ : Dict = tokenizer.convert_tokens_to_string(a_ ) self.assertEqual(a_ , "This is a test" ) @slow def snake_case_ ( self ): # fmt: off a_ : List[Any] = {"input_ids": [[1_2_8_0_2_2, 1_1_0_1_0_8, 3_9_7, 1_1, 3_8_2_7_2, 2_2_4_7, 1_2_4_8_1_1, 2_8_5, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 3_9_5_3_4, 4_4_2_8, 3_9_7, 1_0_1_9, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 4_1_3_3_7, 1_6_7_8_6, 2_4_1, 7, 2_0_2_1_4, 1_7, 1_2_5_6_9_0, 1_0_3_9_8, 7, 4_4_3_7_8, 5_8_0_6_9, 6_8_3_4_2, 7_7_9_8, 7_3_4_3, 1_1, 2_9_9, 3_3_3_1_0, 4, 1_5_8, 3_7_3_5_0, 9_4_0_7_7, 4_5_6_9, 2_9_9, 3_3_3_1_0, 9_0, 4, 5_2_8_4_0, 2_9_0, 4, 3_1_2_7_0, 1_1_2, 2_9_9, 6_8_2, 4, 5_2_8_4_0, 3_9_9_5_3, 1_4_0_7_9, 1_9_3, 5_2_5_1_9, 9_0_8_9_4, 1_7_8_9_4, 1_2_0_6_9_7, 1_1, 4_0_4_4_5, 5_5_1, 1_7, 1_0_1_9, 5_2_5_1_9, 9_0_8_9_4, 1_7_7_5_6, 9_6_3, 1_1, 4_0_4_4_5, 4_8_0, 1_7, 9_7_9_2, 1_1_2_0, 5_1_7_3, 1_3_9_3, 6_2_4_0, 1_6_7_8_6, 2_4_1, 1_2_0_9_9_6, 2_8, 1_2_4_5, 1_3_9_3, 1_1_8_2_4_0, 1_1_1_2_3, 1_0_1_9, 9_3_6_1_2, 2_6_9_1, 1_0_6_1_8, 9_8_0_5_8, 1_2_0_4_0_9, 1_9_2_8, 2_7_9, 4, 4_0_6_8_3, 3_6_7, 1_7_8, 2_0_7, 1_0_1_9, 1_0_3, 1_0_3_1_2_1, 5_0_6, 6_5_2_9_6, 5, 2], [1_2_8_0_2_2, 2_1_2_1_7, 3_6_7, 1_1_7, 1_2_5_4_5_0, 1_2_8, 7_1_9, 7, 7_3_0_8, 4_0, 9_3_6_1_2, 1_2_6_6_9, 1_1_1_6, 1_6_7_0_4, 7_1, 1_7_7_8_5, 3_6_9_9, 1_5_5_9_2, 3_5, 1_4_4, 9_5_8_4, 2_4_1, 1_1_9_4_3, 7_1_3, 9_5_0, 7_9_9, 2_2_4_7, 8_8_4_2_7, 1_5_0, 1_4_9, 1_1_8_8_1_3, 1_2_0_7_0_6, 1_0_1_9, 1_0_6_9_0_6, 8_1_5_1_8, 2_8, 1_2_2_4, 2_2_7_9_9, 3_9_7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1_2_8_0_2_2, 1_6_5_8, 1_2_3_3_1_1, 5_1_5_5, 5_5_7_8, 4_7_2_2, 2_7_9, 1_4_9_4_7, 2_3_6_6, 1_1_2_0, 1_1_9_7, 1_4, 1_3_4_8, 9_2_3_2, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name="facebook/m2m100_418M" , revision="c168bae485c864188cf9aa0e4108b0b6934dc91e" , ) @require_torch @require_sentencepiece @require_tokenizers class snake_case_ ( unittest.TestCase ): __lowerCAmelCase = "facebook/m2m100_418M" __lowerCAmelCase = [ "In my opinion, there are two levels of response from the French government.", "NSA Affair Emphasizes Complete Lack of Debate on Intelligence", ] __lowerCAmelCase = [ "Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.", "L'affaire NSA souligne l'absence totale de débat sur le renseignement", ] # fmt: off __lowerCAmelCase = [EN_CODE, 5_9_3, 1_9_4_9, 1_1_5_7_8_1, 4, 7_1_5_8_6, 4_2_3_4, 6_0_6_3_3, 1_2_6_2_3_3, 4_3_2, 1_2_3_8_0_8, 1_5_5_9_2, 1_1_9_7, 1_1_7_1_3_2, 1_2_0_6_1_8, 5, 2] @classmethod def snake_case_ ( cls ): a_ : MaMaaaTokenizer = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en" , tgt_lang="fr" ) a_ : Optional[Any] = 1 return cls def snake_case_ ( self ): self.assertEqual(self.tokenizer.get_lang_id("ar" ) , 1_2_8_0_0_6 ) self.assertEqual(self.tokenizer.get_lang_id("en" ) , 1_2_8_0_2_2 ) self.assertEqual(self.tokenizer.get_lang_id("ro" ) , 1_2_8_0_7_6 ) self.assertEqual(self.tokenizer.get_lang_id("mr" ) , 1_2_8_0_6_3 ) def snake_case_ ( self ): a_ : Tuple = self.tokenizer.get_vocab() self.assertEqual(len(a_ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab["<unk>"] , 3 ) self.assertIn(self.tokenizer.get_lang_token("en" ) , a_ ) def snake_case_ ( self ): a_ : Optional[int] = "en" a_ : Optional[int] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , a_ ) def snake_case_ ( self ): self.assertIn(a_ , self.tokenizer.all_special_ids ) # fmt: off a_ : List[Any] = [FR_CODE, 5_3_6_4, 8_2, 8_6_4_2, 4, 2_9_4, 4_7, 8, 1_4_0_2_8, 1_3_6, 3_2_8_6, 9_7_0_6, 6, 9_0_7_9_7, 6, 1_4_4_0_1_2, 1_6_2, 8_8_1_2_8, 3_0_0_6_1, 5, 2] # fmt: on a_ : List[Any] = self.tokenizer.decode(a_ , skip_special_tokens=a_ ) a_ : Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=a_ ) self.assertEqual(a_ , a_ ) self.assertNotIn(self.tokenizer.eos_token , a_ ) def snake_case_ ( self ): a_ : Any = tempfile.mkdtemp() a_ : List[str] = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(a_ ) a_ : Tuple = MaMaaaTokenizer.from_pretrained(a_ ) self.assertDictEqual(new_tok.lang_token_to_id , a_ ) @require_torch def snake_case_ ( self ): a_ : Optional[Any] = "en" a_ : Dict = "fr" a_ : Optional[int] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=a_ , return_tensors="pt" ) a_ : List[str] = shift_tokens_right( batch["labels"] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: a_ : Dict = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def snake_case_ ( self ): a_ : Dict = "mr" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) a_ : List[str] = "zh" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def snake_case_ ( self ): a_ : List[str] = "mr" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) a_ : Union[str, Any] = "zh" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def snake_case_ ( self ): a_ : Optional[int] = self.tokenizer._build_translation_inputs("A test" , return_tensors="pt" , src_lang="en" , tgt_lang="ar" ) self.assertEqual( nested_simplify(a_ ) , { # en_XX, A, test, EOS "input_ids": [[1_2_8_0_2_2, 5_8, 4_1_8_3, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 1_2_8_0_0_6, } , )
370
"""simple docstring""" def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ = False ) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_317_044_064_679_887_385_961_981 and not allow_probable: raise ValueError( "Warning: upper bound of deterministic test is exceeded. " "Pass allow_probable=True to allow probabilistic test. " "A return value of True indicates a probable prime." ) # array bounds provided by analysis a_ : Optional[Any] = [ 2_047, 1_373_653, 25_326_001, 3_215_031_751, 2_152_302_898_747, 3_474_749_660_383, 341_550_071_728_321, 1, 3_825_123_056_546_413_051, 1, 1, 318_665_857_834_031_151_167_461, 3_317_044_064_679_887_385_961_981, ] a_ : Optional[int] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(SCREAMING_SNAKE_CASE__, 1 ): if n < _p: # then we have our last prime to check a_ : List[Any] = primes[:idx] break a_ , a_ : Tuple = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: a_ : str = False for r in range(SCREAMING_SNAKE_CASE__ ): a_ : List[str] = pow(SCREAMING_SNAKE_CASE__, d * 2**r, SCREAMING_SNAKE_CASE__ ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): a_ : List[Any] = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def lowerCAmelCase_ ( ) -> None: assert not miller_rabin(561 ) assert miller_rabin(563 ) # 2047 assert not miller_rabin(838_201 ) assert miller_rabin(838_207 ) # 1_373_653 assert not miller_rabin(17_316_001 ) assert miller_rabin(17_316_017 ) # 25_326_001 assert not miller_rabin(3_078_386_641 ) assert miller_rabin(3_078_386_653 ) # 3_215_031_751 assert not miller_rabin(1_713_045_574_801 ) assert miller_rabin(1_713_045_574_819 ) # 2_152_302_898_747 assert not miller_rabin(2_779_799_728_307 ) assert miller_rabin(2_779_799_728_327 ) # 3_474_749_660_383 assert not miller_rabin(113_850_023_909_441 ) assert miller_rabin(113_850_023_909_527 ) # 341_550_071_728_321 assert not miller_rabin(1_275_041_018_848_804_351 ) assert miller_rabin(1_275_041_018_848_804_391 ) # 3_825_123_056_546_413_051 assert not miller_rabin(79_666_464_458_507_787_791_867 ) assert miller_rabin(79_666_464_458_507_787_791_951 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(552_840_677_446_647_897_660_333 ) assert miller_rabin(552_840_677_446_647_897_660_359 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
370
1
"""simple docstring""" from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class _lowerCAmelCase : __UpperCAmelCase : str = field( metadata={'''help''': '''The output directory where the model will be written.'''} , ) __UpperCAmelCase : str = field( metadata={ '''help''': ( '''The encoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train an encoder model from scratch.''' ) } , ) __UpperCAmelCase : str = field( metadata={ '''help''': ( '''The decoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train a decoder model from scratch.''' ) } , ) __UpperCAmelCase : Optional[str] = field( default=A_ , metadata={'''help''': '''Pretrained encoder config name or path if not the same as encoder_model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=A_ , metadata={'''help''': '''Pretrained decoder config name or path if not the same as decoder_model_name'''} ) def __lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" snake_case : Union[str, Any] = HfArgumentParser((ModelArguments,) ) (snake_case) : str = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: snake_case : Union[str, Any] = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: snake_case : Dict = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: snake_case : List[str] = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: snake_case : Dict = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed snake_case : List[str] = True snake_case : List[str] = True snake_case : Optional[int] = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=lowercase , decoder_config=lowercase , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens snake_case : Tuple = decoder_config.decoder_start_token_id snake_case : Union[str, Any] = decoder_config.pad_token_id if decoder_start_token_id is None: snake_case : List[str] = decoder_config.bos_token_id if pad_token_id is None: snake_case : Dict = decoder_config.eos_token_id # This is necessary to make Flax's generate() work snake_case : Union[str, Any] = decoder_config.eos_token_id snake_case : List[Any] = decoder_start_token_id snake_case : Union[str, Any] = pad_token_id snake_case : Union[str, Any] = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) snake_case : Optional[Any] = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) snake_case : Union[str, Any] = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
178
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''EleutherAI/gpt-neo-1.3B''': '''https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json''', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class __A ( A_ ): UpperCamelCase :List[str] = '''gpt_neo''' UpperCamelCase :Tuple = ['''past_key_values'''] UpperCamelCase :Optional[int] = {'''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__(self , __magic_name__=50257 , __magic_name__=2048 , __magic_name__=2048 , __magic_name__=24 , __magic_name__=[[["global", "local"], 12]] , __magic_name__=16 , __magic_name__=None , __magic_name__=256 , __magic_name__="gelu_new" , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=0.1 , __magic_name__=1E-5 , __magic_name__=0.02 , __magic_name__=True , __magic_name__=50256 , __magic_name__=50256 , **__magic_name__ , ): lowerCamelCase__ : Dict = vocab_size lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : str = hidden_size lowerCamelCase__ : List[Any] = num_layers lowerCamelCase__ : List[Any] = num_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : str = window_size lowerCamelCase__ : List[Any] = activation_function lowerCamelCase__ : Any = resid_dropout lowerCamelCase__ : Dict = embed_dropout lowerCamelCase__ : str = attention_dropout lowerCamelCase__ : str = classifier_dropout lowerCamelCase__ : str = layer_norm_epsilon lowerCamelCase__ : Optional[int] = initializer_range lowerCamelCase__ : int = use_cache lowerCamelCase__ : List[Any] = bos_token_id lowerCamelCase__ : int = eos_token_id lowerCamelCase__ : str = attention_types lowerCamelCase__ : List[str] = self.expand_attention_types_params(__magic_name__ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.attention_layers)` == `config.num_layers` """ f"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " f"`config.num_layers = {self.num_layers}`. " """`config.attention_layers` is prepared using `config.attention_types`. """ """Please verify the value of `config.attention_types` argument.""" ) super().__init__(bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) @staticmethod def _snake_case (__magic_name__ ): lowerCamelCase__ : Optional[Any] = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _A (UpperCamelCase : Dict , UpperCamelCase : Dict , UpperCamelCase : Optional[int] , UpperCamelCase : Tuple ) ->int: '''simple docstring''' import torch lowerCamelCase__ : Any = input.size() lowerCamelCase__ : Tuple = len(UpperCamelCase ) lowerCamelCase__ : str = shape[dimension] lowerCamelCase__ : Optional[int] = torch.arange(0 , UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Optional[Any] = torch.div(sizedim - size , UpperCamelCase , rounding_mode="""floor""" ) + 1 lowerCamelCase__ : Tuple = torch.arange(UpperCamelCase ) + low_indices[:min_length][:, None] lowerCamelCase__ : Dict = [slice(UpperCamelCase )] * rank lowerCamelCase__ : Union[str, Any] = indices lowerCamelCase__ : Optional[int] = input[s] lowerCamelCase__ : int = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(UpperCamelCase ) def _A (UpperCamelCase : List[Any] , UpperCamelCase : Optional[int] ) ->Tuple: '''simple docstring''' import torch lowerCamelCase__ : List[Any] = torch.arange(1 , UpperCamelCase ) lowerCamelCase__ : Any = torch.remainder(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Optional[int] = remainders == 0 lowerCamelCase__ : List[str] = candidates[divisor_indices] lowerCamelCase__ : List[Any] = torch.max(UpperCamelCase ) return largest_divisor, torch.div(UpperCamelCase , UpperCamelCase , rounding_mode="""floor""" ) class __A ( A_ ): @property def _snake_case (self ): lowerCamelCase__ : str = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="""inputs""" ) lowerCamelCase__ : Any = {0: """batch""", 1: """past_sequence + sequence"""} else: lowerCamelCase__ : int = {0: """batch""", 1: """sequence"""} return common_inputs @property def _snake_case (self ): return self._config.num_heads def _snake_case (self , __magic_name__ , __magic_name__ = -1 , __magic_name__ = -1 , __magic_name__ = False , __magic_name__ = None , ): lowerCamelCase__ : Union[str, Any] = super(__magic_name__ , self ).generate_dummy_inputs( __magic_name__ , batch_size=__magic_name__ , seq_length=__magic_name__ , is_pair=__magic_name__ , framework=__magic_name__ ) # We need to order the input in the way they appears in the forward() lowerCamelCase__ : List[Any] = 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 lowerCamelCase__ ,lowerCamelCase__ : str = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values lowerCamelCase__ : Any = seqlen + 2 lowerCamelCase__ : List[Any] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCamelCase__ : Dict = [ (torch.zeros(__magic_name__ ), torch.zeros(__magic_name__ )) for _ in range(self.num_layers ) ] lowerCamelCase__ : Dict = common_inputs["""attention_mask"""] if self.use_past: lowerCamelCase__ : int = ordered_inputs["""attention_mask"""].dtype lowerCamelCase__ : List[Any] = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(__magic_name__ , __magic_name__ , dtype=__magic_name__ )] , dim=1 ) return ordered_inputs @property def _snake_case (self ): return 13
157
0
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class _lowercase ( unittest.TestCase ): def A ( self : Tuple ) -> int: """simple docstring""" a = get_activation("swish" ) self.assertIsInstance(__lowerCAmelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def A ( self : Optional[Any] ) -> int: """simple docstring""" a = get_activation("silu" ) self.assertIsInstance(__lowerCAmelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def A ( self : Union[str, Any] ) -> List[str]: """simple docstring""" a = get_activation("mish" ) self.assertIsInstance(__lowerCAmelCase , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def A ( self : int ) -> List[Any]: """simple docstring""" a = get_activation("gelu" ) self.assertIsInstance(__lowerCAmelCase , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
32
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _lowercase : def __init__( self : List[str] ) -> List[str]: """simple docstring""" a = "" a = "" a = [] a = 0 a = 256 a = 0 a = 0 a = 0 a = 0 def A ( self : Optional[Any] , __lowerCAmelCase : Any ) -> int: """simple docstring""" a = cva.imread(__lowerCAmelCase , 0 ) a = copy.deepcopy(self.img ) a , a , a = plt.hist(self.img.ravel() , 256 , [0, 256] , label="x" ) a = np.sum(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): a = x[i] / self.k self.sk += prk a = (self.L - 1) * self.sk if self.rem != 0: a = int(last % last ) a = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__lowerCAmelCase ) a = int(np.ma.count(self.img ) / self.img[1].size ) a = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a = self.img[j][i] if num != self.last_list[num]: a = self.last_list[num] cva.imwrite("output_data/output.jpg" , self.img ) def A ( self : Any ) -> int: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def A ( self : Any ) -> int: """simple docstring""" cva.imshow("Output-Image" , self.img ) cva.imshow("Input-Image" , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": A_ : List[Any] = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') A_ : int = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
32
1
'''simple docstring''' import math import random from typing import Any from .hill_climbing import SearchProblem def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = math.inf , SCREAMING_SNAKE_CASE__ = -math.inf , SCREAMING_SNAKE_CASE__ = math.inf , SCREAMING_SNAKE_CASE__ = -math.inf , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = 1_00 , SCREAMING_SNAKE_CASE__ = 0.01 , SCREAMING_SNAKE_CASE__ = 1 , ): '''simple docstring''' _snake_case = False _snake_case = search_prob _snake_case = start_temperate _snake_case = [] _snake_case = 0 _snake_case = None while not search_end: _snake_case = current_state.score() if best_state is None or current_score > best_state.score(): _snake_case = current_state scores.append(SCREAMING_SNAKE_CASE__ ) iterations += 1 _snake_case = None _snake_case = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _snake_case = random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) # picking a random neighbor _snake_case = neighbors.pop(SCREAMING_SNAKE_CASE__ ) _snake_case = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _snake_case = change * -1 # in case we are finding minimum if change > 0: # improves the solution _snake_case = picked_neighbor else: _snake_case = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _snake_case = picked_neighbor _snake_case = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _snake_case = True else: _snake_case = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) plt.xlabel("Iterations" ) plt.ylabel("Function values" ) plt.show() return best_state if __name__ == "__main__": def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) __magic_name__ : Dict = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) __magic_name__ : List[str] = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( """The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ F'and 50 > y > - 5 found via hill climbing: {local_min.score()}' ) # starting the problem with initial coordinates (12, 47) __magic_name__ : Tuple = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) __magic_name__ : str = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( """The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ F'and 50 > y > - 5 found via hill climbing: {local_min.score()}' ) def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return (3 * x**2) - (6 * y) __magic_name__ : Tuple = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) __magic_name__ : List[Any] = simulated_annealing(prob, find_max=False, visualization=True) print( """The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ F'{local_min.score()}' ) __magic_name__ : List[str] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) __magic_name__ : Any = simulated_annealing(prob, find_max=True, visualization=True) print( """The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ F'{local_min.score()}' )
672
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging __magic_name__ : Dict = logging.get_logger(__name__) def snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): return list(tensor.shape ) _snake_case = tf.shape(SCREAMING_SNAKE_CASE__ ) if tensor.shape == tf.TensorShape(SCREAMING_SNAKE_CASE__ ): return dynamic _snake_case = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(SCREAMING_SNAKE_CASE__ )] def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' return tf.nn.softmax(logits=logits + 1E-9 , axis=SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=-1 ): '''simple docstring''' if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis." ) # Get mean and variance on the axis to be normalized _snake_case , _snake_case = tf.nn.moments(SCREAMING_SNAKE_CASE__ , axes=[axis] , keepdims=SCREAMING_SNAKE_CASE__ ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis _snake_case = [1] * inputs.shape.rank _snake_case = shape_list(SCREAMING_SNAKE_CASE__ )[axis] _snake_case = tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _snake_case = tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Compute layer normalization using the batch_normalization # function. _snake_case = tf.nn.batch_normalization( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , offset=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , variance_epsilon=SCREAMING_SNAKE_CASE__ , ) return outputs def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=-1 ): '''simple docstring''' if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input _snake_case = tf.shape(SCREAMING_SNAKE_CASE__ ) _snake_case = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) _snake_case = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE__ , tf.Tensor ): _snake_case = tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: _snake_case = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: _snake_case = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) _snake_case = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "input_ids" ): '''simple docstring''' tf.debugging.assert_less( SCREAMING_SNAKE_CASE__ , tf.cast(SCREAMING_SNAKE_CASE__ , dtype=tensor.dtype ) , message=( f'''The maximum value of {tensor_name} ({tf.math.reduce_max(SCREAMING_SNAKE_CASE__ )}) must be smaller than the embedding ''' f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' _snake_case = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. _snake_case = [x for x in data if len(SCREAMING_SNAKE_CASE__ ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( "The following attributes cannot be saved to HDF5 file because " f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' f'''bytes: {bad_attributes}''' ) _snake_case = np.asarray(SCREAMING_SNAKE_CASE__ ) _snake_case = 1 _snake_case = np.array_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 _snake_case = np.array_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(SCREAMING_SNAKE_CASE__ ): _snake_case = chunk_data else: _snake_case = data def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if name in group.attrs: _snake_case = [n.decode("utf8" ) if hasattr(SCREAMING_SNAKE_CASE__ , "decode" ) else n for n in group.attrs[name]] else: _snake_case = [] _snake_case = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("utf8" ) if hasattr(SCREAMING_SNAKE_CASE__ , "decode" ) else n for n in group.attrs["%s%d" % (name, chunk_id)]] ) chunk_id += 1 return data def snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def _expand_single_ad_tensor(SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(SCREAMING_SNAKE_CASE__ , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , SCREAMING_SNAKE_CASE__ )
672
1
import numpy # List of input, output pairs A = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) A = (((515, 22, 13), 555), ((61, 35, 49), 150)) A = [2, 4, 1, 5] A = len(train_data) A = 0.009 def _lowerCamelCase( lowerCAmelCase__ : Any , lowerCAmelCase__ : Any="train" ): '''simple docstring''' return calculate_hypothesis_value(_lowerCamelCase , _lowerCamelCase ) - output( _lowerCamelCase , _lowerCamelCase ) def _lowerCamelCase( lowerCAmelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = 0 for i in range(len(_lowerCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _lowerCamelCase( lowerCAmelCase__ : Any , lowerCAmelCase__ : List[Any] ): '''simple docstring''' if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _lowerCamelCase( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ): '''simple docstring''' if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _lowerCamelCase( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any]=m ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = 0 for i in range(_lowerCamelCase ): if index == -1: summation_value += _error(_lowerCamelCase ) else: summation_value += _error(_lowerCamelCase ) * train_data[i][0][index] return summation_value def _lowerCamelCase( lowerCAmelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = summation_of_cost_derivative(_lowerCamelCase , _lowerCamelCase ) / m return cost_derivative_value def _lowerCamelCase( ): '''simple docstring''' global parameter_vector # Tune these values to set a tolerance value for predicted output SCREAMING_SNAKE_CASE_ : List[str] = 0.000_002 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 while True: j += 1 SCREAMING_SNAKE_CASE_ : int = [0, 0, 0, 0] for i in range(0 , len(_lowerCamelCase ) ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_cost_derivative(i - 1 ) SCREAMING_SNAKE_CASE_ : Any = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( _lowerCamelCase , _lowerCamelCase , atol=_lowerCamelCase , rtol=_lowerCamelCase , ): break SCREAMING_SNAKE_CASE_ : Any = temp_parameter_vector print(('Number of iterations:', j) ) def _lowerCamelCase( ): '''simple docstring''' for i in range(len(_lowerCamelCase ) ): print(('Actual output value:', output(_lowerCamelCase , 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(_lowerCamelCase , 'test' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
706
def _lowerCamelCase( ): '''simple docstring''' return 1 def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' return 0 if x < 0 else five_pence(x - 5 ) + two_pence(lowerCAmelCase__ ) def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(lowerCAmelCase__ ) def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(lowerCAmelCase__ ) def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(lowerCAmelCase__ ) def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' return 0 if x < 0 else one_pound(x - 100 ) + fifty_pence(lowerCAmelCase__ ) def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' return 0 if x < 0 else two_pound(x - 200 ) + one_pound(lowerCAmelCase__ ) def _lowerCamelCase( lowerCAmelCase__ : int = 200 ): '''simple docstring''' return two_pound(lowerCAmelCase__ ) if __name__ == "__main__": print(solution(int(input().strip())))
97
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE = {'configuration_vit': ['VIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTConfig', 'ViTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = ['ViTFeatureExtractor'] SCREAMING_SNAKE_CASE = ['ViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = [ 'VIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTForImageClassification', 'ViTForMaskedImageModeling', 'ViTModel', 'ViTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = [ 'TFViTForImageClassification', 'TFViTModel', 'TFViTPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = [ 'FlaxViTForImageClassification', 'FlaxViTModel', 'FlaxViTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
485
from sklearn.metrics import matthews_corrcoef import datasets SCREAMING_SNAKE_CASE = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n' SCREAMING_SNAKE_CASE = '\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results[\'matthews_correlation\'], 2))\n -0.25\n' SCREAMING_SNAKE_CASE = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): '''simple docstring''' def snake_case__ ( self) -> Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32'''), '''references''': datasets.Value('''int32'''), }) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def snake_case__ ( self , _A , _A , _A=None) -> Any: """simple docstring""" return { "matthews_correlation": float(matthews_corrcoef(_A , _A , sample_weight=_A)), }
485
1
from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class __snake_case ( UpperCamelCase__ ): '''simple docstring''' lowerCAmelCase__ = 42 class __snake_case ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' @register_to_config def __init__( self : Optional[Any] , A : int = 16 , A : int = 88 , A : Optional[int] = None , A : Optional[int] = None , A : int = 1 , A : float = 0.0 , A : int = 32 , A : Optional[int] = None , A : bool = False , A : Optional[int] = None , A : str = "geglu" , A : bool = True , A : bool = True , ): super().__init__() __snake_case: List[Any] = num_attention_heads __snake_case: List[str] = attention_head_dim __snake_case: Dict = num_attention_heads * attention_head_dim __snake_case: Union[str, Any] = in_channels __snake_case: Dict = torch.nn.GroupNorm(num_groups=__A , num_channels=__A , eps=1E-6 , affine=__A ) __snake_case: str = nn.Linear(__A , __A ) # 3. Define transformers blocks __snake_case: List[Any] = nn.ModuleList( [ BasicTransformerBlock( __A , __A , __A , dropout=__A , cross_attention_dim=__A , activation_fn=__A , attention_bias=__A , double_self_attention=__A , norm_elementwise_affine=__A , ) for d in range(__A ) ] ) __snake_case: List[Any] = nn.Linear(__A , __A ) def UpperCAmelCase__ ( self : Any , A : int , A : int=None , A : Tuple=None , A : str=None , A : str=1 , A : str=None , A : bool = True , ): __snake_case , __snake_case , __snake_case , __snake_case: List[str] = hidden_states.shape __snake_case: str = batch_frames // num_frames __snake_case: Optional[int] = hidden_states __snake_case: str = hidden_states[None, :].reshape(__A , __A , __A , __A , __A ) __snake_case: int = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) __snake_case: Dict = self.norm(__A ) __snake_case: int = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , __A , __A ) __snake_case: Any = self.proj_in(__A ) # 2. Blocks for block in self.transformer_blocks: __snake_case: Any = block( __A , encoder_hidden_states=__A , timestep=__A , cross_attention_kwargs=__A , class_labels=__A , ) # 3. Output __snake_case: List[str] = self.proj_out(__A ) __snake_case: Optional[int] = ( hidden_states[None, None, :] .reshape(__A , __A , __A , __A , __A ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) __snake_case: Dict = hidden_states.reshape(__A , __A , __A , __A ) __snake_case: int = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=__A )
715
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed __UpperCAmelCase : Any = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(f'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) __UpperCAmelCase : List[Any] = "sshleifer/student_marian_en_ro_6_1" __UpperCAmelCase : Optional[Any] = "sshleifer/tiny-mbart" @require_torch class __snake_case ( __lowerCamelCase ): '''simple docstring''' def UpperCAmelCase__ ( self : int , A : Tuple=False , A : Dict=None , A : List[Any]=True , A : Any=True , A : Optional[Any]=True , A : int=True , ): __snake_case: Dict = self.run_trainer( eval_steps=1 , max_len=12 , model_name=A , num_train_epochs=1 , distributed=A , extra_args_str=A , predict_with_generate=A , do_train=A , do_eval=A , do_predict=A , ) __snake_case: Any = TrainerState.load_from_json(os.path.join(A , """trainer_state.json""" ) ).log_history if not do_eval: return __snake_case: List[Any] = [log for log in logs if """eval_loss""" in log.keys()] __snake_case: int = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __snake_case: int = eval_metrics[-1] assert isinstance(last_step_stats["""eval_bleu"""] , A ) assert not math.isnan(float(last_step_stats["""eval_loss"""] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def UpperCAmelCase__ ( self : Union[str, Any] ): self.run_seqaseq_quick() @require_torch_multi_gpu def UpperCAmelCase__ ( self : Optional[int] ): self.run_seqaseq_quick(distributed=A ) @require_torch_multi_gpu def UpperCAmelCase__ ( self : List[Any] ): self.run_seqaseq_quick(distributed=A ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def UpperCAmelCase__ ( self : Any ): self.run_seqaseq_quick(distributed=A , extra_args_str="""--sharded_ddp simple""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def UpperCAmelCase__ ( self : Optional[Any] ): self.run_seqaseq_quick(distributed=A , extra_args_str="""--sharded_ddp simple --fp16""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def UpperCAmelCase__ ( self : Union[str, Any] ): self.run_seqaseq_quick(distributed=A , extra_args_str="""--sharded_ddp zero_dp_2""" , predict_with_generate=A ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def UpperCAmelCase__ ( self : Dict ): self.run_seqaseq_quick( distributed=A , extra_args_str="""--sharded_ddp zero_dp_2 --fp16""" , predict_with_generate=A ) @require_apex @require_torch_gpu def UpperCAmelCase__ ( self : Any ): # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A , extra_args_str="""--fp16 --fp16_backend=apex""" ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A , extra_args_str="""--fp16 --fp16_backend=apex""" ) @parameterized.expand(["""base""", """low""", """high""", """mixed"""] ) @require_torch_multi_gpu def UpperCAmelCase__ ( self : Tuple , A : List[Any] ): # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __snake_case: Tuple = { # test with the default log_level - should be info and thus log info once """base""": {"""extra_args_str""": """""", """n_matches""": 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes """low""": {"""extra_args_str""": """--log_level debug --log_level_replica debug""", """n_matches""": 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica """high""": {"""extra_args_str""": """--log_level error --log_level_replica debug""", """n_matches""": 1}, # test with high log_level and log_level_replica - should be quiet on all processes """mixed""": {"""extra_args_str""": """--log_level error --log_level_replica error""", """n_matches""": 0}, } __snake_case: int = experiments[experiment_id] __snake_case: Dict = {"""distributed""": True, """predict_with_generate""": False, """do_eval""": False, """do_predict""": False} __snake_case: str = """Running training""" with CaptureStderr() as cl: self.run_seqaseq_quick(**A , extra_args_str=data["""extra_args_str"""] ) __snake_case: List[str] = len(re.findall(A , cl.err ) ) self.assertEqual(A , data["""n_matches"""] ) @slow def UpperCAmelCase__ ( self : Dict ): __snake_case: Optional[int] = self.run_trainer( eval_steps=2 , max_len=128 , model_name=A , learning_rate=3E-4 , num_train_epochs=10 , distributed=A , ) # Check metrics __snake_case: Optional[int] = TrainerState.load_from_json(os.path.join(A , """trainer_state.json""" ) ).log_history __snake_case: Any = [log for log in logs if """eval_loss""" in log.keys()] __snake_case: Tuple = eval_metrics[0] __snake_case: Optional[int] = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats["""eval_bleu"""] , A ) # test if do_predict saves generations and metrics __snake_case: List[str] = os.listdir(A ) __snake_case: List[str] = {os.path.basename(A ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def UpperCAmelCase__ ( self : Any ): from transformers.training_args import OptimizerNames def train_and_return_metrics(A : str ) -> Tuple[int, float]: __snake_case: List[Any] = """--skip_memory_metrics 0""" __snake_case: Tuple = self.run_trainer( max_len=128 , model_name=A , learning_rate=3E-4 , num_train_epochs=1 , optim=A , distributed=A , extra_args_str=A , do_eval=A , do_predict=A , n_gpus_to_use=1 , ) # Check metrics __snake_case: Any = TrainerState.load_from_json(Path(A , """trainer_state.json""" ) ).log_history __snake_case: Tuple = int(logs[0]["""train_mem_gpu_peaked_delta"""] / 2**20 ) __snake_case: Union[str, Any] = int(logs[0]["""train_mem_gpu_alloc_delta"""] / 2**20 ) __snake_case: int = logs[0]["""train_loss"""] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __snake_case , __snake_case , __snake_case: Tuple = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __snake_case , __snake_case , __snake_case: List[str] = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __snake_case: Dict = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __snake_case: Optional[int] = gpu_peak_mem_orig + gpu_alloc_mem_orig __snake_case: str = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __snake_case: Tuple = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __snake_case: Any = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A , A , """should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got""" f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( A , A , """should use ~150MB less total gpu memory with BNB, compared to without it for this model but got""" f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( A , A , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def UpperCAmelCase__ ( self : str , A : int , A : str , A : int , A : float = 3E-3 , A : str = "adafactor" , A : bool = False , A : str = None , A : int = 0 , A : bool = True , A : bool = True , A : bool = True , A : bool = True , A : int = None , ): __snake_case: str = self.test_file_dir / """../fixtures/tests_samples/wmt_en_ro""" __snake_case: str = self.get_auto_remove_tmp_dir() __snake_case: List[str] = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(A )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(A )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __snake_case: str = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(A )} '''.split() __snake_case: Dict = """ --do_predict """.split() __snake_case: Tuple = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __snake_case: Optional[int] = get_gpu_count() __snake_case: List[Any] = get_torch_dist_unique_port() __snake_case: Union[str, Any] = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __snake_case: Optional[int] = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A , env=self.get_env() ) else: __snake_case: int = ["""run_translation.py"""] + args with patch.object(A , """argv""" , A ): main() return output_dir
155
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging _lowerCAmelCase = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" if isinstance(__snake_case , np.ndarray ): return list(tensor.shape ) lowerCAmelCase__ : Optional[int] = tf.shape(__snake_case ) if tensor.shape == tf.TensorShape(__snake_case ): return dynamic lowerCAmelCase__ : int = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(__snake_case )] def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase = None , UpperCamelCase = None ): """simple docstring""" return tf.nn.softmax(logits=logits + 1e-9 , axis=__snake_case , name=__snake_case ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=1e-5 , UpperCamelCase=-1 ): """simple docstring""" if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__snake_case , __snake_case ): raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis.""" ) # Get mean and variance on the axis to be normalized lowerCAmelCase__ , lowerCAmelCase__ : Any = tf.nn.moments(__snake_case , axes=[axis] , keepdims=__snake_case ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis lowerCAmelCase__ : Union[str, Any] = [1] * inputs.shape.rank lowerCAmelCase__ : Tuple = shape_list(__snake_case )[axis] lowerCAmelCase__ : Optional[int] = tf.reshape(__snake_case , __snake_case ) lowerCAmelCase__ : Any = tf.reshape(__snake_case , __snake_case ) # Compute layer normalization using the batch_normalization # function. lowerCAmelCase__ : int = tf.nn.batch_normalization( __snake_case , __snake_case , __snake_case , offset=__snake_case , scale=__snake_case , variance_epsilon=__snake_case , ) return outputs def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase=0 , UpperCamelCase=-1 ): """simple docstring""" if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input lowerCAmelCase__ : Any = tf.shape(__snake_case ) lowerCAmelCase__ : int = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) lowerCAmelCase__ : Any = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(__snake_case , __snake_case ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" if not isinstance(__snake_case , tf.Tensor ): lowerCAmelCase__ : List[str] = tf.convert_to_tensor(__snake_case ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: lowerCAmelCase__ : str = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: lowerCAmelCase__ : Dict = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) lowerCAmelCase__ : Optional[int] = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase = "input_ids" ): """simple docstring""" tf.debugging.assert_less( __snake_case , tf.cast(__snake_case , dtype=tensor.dtype ) , message=( f"""The maximum value of {tensor_name} ({tf.math.reduce_max(__snake_case )}) must be smaller than the embedding """ f"""layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.""" ) , ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[str] = 64512 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. lowerCAmelCase__ : Tuple = [x for x in data if len(__snake_case ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( """The following attributes cannot be saved to HDF5 file because """ f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """ f"""bytes: {bad_attributes}""" ) lowerCAmelCase__ : Tuple = np.asarray(__snake_case ) lowerCAmelCase__ : Optional[int] = 1 lowerCAmelCase__ : Dict = np.array_split(__snake_case , __snake_case ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 lowerCAmelCase__ : Dict = np.array_split(__snake_case , __snake_case ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(__snake_case ): lowerCAmelCase__ : Optional[Any] = chunk_data else: lowerCAmelCase__ : Optional[int] = data def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" if name in group.attrs: lowerCAmelCase__ : List[Any] = [n.decode("""utf8""" ) if hasattr(__snake_case , """decode""" ) else n for n in group.attrs[name]] else: lowerCAmelCase__ : Dict = [] lowerCAmelCase__ : Any = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("""utf8""" ) if hasattr(__snake_case , """decode""" ) else n for n in group.attrs["""%s%d""" % (name, chunk_id)]] ) chunk_id += 1 return data def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" def _expand_single_ad_tensor(UpperCamelCase ): if isinstance(__snake_case , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(__snake_case , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , __snake_case )
565
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ : Any = {"""configuration_timm_backbone""": ["""TimmBackboneConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ["""TimmBackbone"""] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys a_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
676
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowercase__ = logging.get_logger(__name__) lowercase__ = { "microsoft/swin-tiny-patch4-window7-224": ( "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json" ), # See all Swin models at https://huggingface.co/models?filter=swin } class __SCREAMING_SNAKE_CASE ( _a , _a ): UpperCAmelCase = '''swin''' UpperCAmelCase = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __UpperCamelCase=224 , __UpperCamelCase=4 , __UpperCamelCase=3 , __UpperCamelCase=96 , __UpperCamelCase=[2, 2, 6, 2] , __UpperCamelCase=[3, 6, 12, 24] , __UpperCamelCase=7 , __UpperCamelCase=4.0 , __UpperCamelCase=True , __UpperCamelCase=0.0 , __UpperCamelCase=0.0 , __UpperCamelCase=0.1 , __UpperCamelCase="gelu" , __UpperCamelCase=False , __UpperCamelCase=0.02 , __UpperCamelCase=1e-5 , __UpperCamelCase=32 , __UpperCamelCase=None , __UpperCamelCase=None , **__UpperCamelCase , ) -> Optional[int]: super().__init__(**_A ) _a = image_size _a = patch_size _a = num_channels _a = embed_dim _a = depths _a = len(_A ) _a = num_heads _a = window_size _a = mlp_ratio _a = qkv_bias _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = drop_path_rate _a = hidden_act _a = use_absolute_embeddings _a = layer_norm_eps _a = initializer_range _a = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _a = int(embed_dim * 2 ** (len(_A ) - 1) ) _a = ["stem"] + [f"stage{idx}" for idx in range(1 , len(_A ) + 1 )] _a , _a = get_aligned_output_features_output_indices( out_features=_A , out_indices=_A , stage_names=self.stage_names ) class __SCREAMING_SNAKE_CASE ( _a ): UpperCAmelCase = version.parse('''1.11''' ) @property def a_ ( self ) -> Any: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def a_ ( self ) -> Tuple: return 1e-4
714
'''simple docstring''' from manim import * class __SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def a_ ( self ) -> str: _a = Rectangle(height=0.5 , width=0.5 ) _a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _a = [mem.copy() for i in range(6 )] _a = [mem.copy() for i in range(6 )] _a = VGroup(*__UpperCamelCase ).arrange(__UpperCamelCase , buff=0 ) _a = VGroup(*__UpperCamelCase ).arrange(__UpperCamelCase , buff=0 ) _a = VGroup(__UpperCamelCase , __UpperCamelCase ).arrange(__UpperCamelCase , buff=0 ) _a = Text("CPU" , font_size=24 ) _a = Group(__UpperCamelCase , __UpperCamelCase ).arrange(__UpperCamelCase , buff=0.5 , aligned_edge=__UpperCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__UpperCamelCase ) _a = [mem.copy() for i in range(1 )] _a = VGroup(*__UpperCamelCase ).arrange(__UpperCamelCase , buff=0 ) _a = Text("GPU" , font_size=24 ) _a = Group(__UpperCamelCase , __UpperCamelCase ).arrange(__UpperCamelCase , buff=0.5 , aligned_edge=__UpperCamelCase ) gpu.align_to(__UpperCamelCase , __UpperCamelCase ) gpu.set_x(gpu.get_x() - 1 ) self.add(__UpperCamelCase ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__UpperCamelCase ).arrange(__UpperCamelCase , buff=0 ) _a = Text("Model" , font_size=24 ) _a = Group(__UpperCamelCase , __UpperCamelCase ).arrange(__UpperCamelCase , buff=0.5 , aligned_edge=__UpperCamelCase ) model.move_to([3, -1.0, 0] ) self.play( Create(__UpperCamelCase , run_time=1 ) , Create(__UpperCamelCase , run_time=1 ) , Create(__UpperCamelCase , run_time=1 ) , ) _a = MarkupText( f"First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM." , font_size=24 , ) _a = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _a = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(__UpperCamelCase , run_time=2.5 ) , Write(__UpperCamelCase ) , Write(__UpperCamelCase ) ) self.add(__UpperCamelCase ) _a = [] _a = [] _a = [] for i, rect in enumerate(__UpperCamelCase ): _a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(__UpperCamelCase , opacity=0.7 ) cpu_target.move_to(__UpperCamelCase ) cpu_target.generate_target() _a = 0.46 / 4 _a = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__UpperCamelCase ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=__UpperCamelCase , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=__UpperCamelCase , buff=0.0 ) cpu_targs.append(__UpperCamelCase ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(__UpperCamelCase ) ) second_animations.append(MoveToTarget(__UpperCamelCase , run_time=1.5 ) ) self.play(*__UpperCamelCase ) self.play(*__UpperCamelCase ) self.wait()
276
0
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig a_ = logging.get_logger(__name__) # General docstring a_ = '''RegNetConfig''' # Base docstring a_ = '''facebook/regnet-y-040''' a_ = [1, 1088, 7, 7] # Image classification docstring a_ = '''facebook/regnet-y-040''' a_ = '''tabby, tabby cat''' a_ = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 3 , __UpperCAmelCase = 1 , __UpperCAmelCase = 1 , __UpperCAmelCase = "relu" , )-> int: '''simple docstring''' super().__init__() lowerCAmelCase__ = nn.Convad( __UpperCAmelCase , __UpperCAmelCase , kernel_size=__UpperCAmelCase , stride=__UpperCAmelCase , padding=kernel_size // 2 , groups=__UpperCAmelCase , bias=__UpperCAmelCase , ) lowerCAmelCase__ = nn.BatchNormad(__UpperCAmelCase ) lowerCAmelCase__ = ACTaFN[activation] if activation is not None else nn.Identity() def UpperCAmelCase ( self , __UpperCAmelCase )-> str: '''simple docstring''' lowerCAmelCase__ = self.convolution(__UpperCAmelCase ) lowerCAmelCase__ = self.normalization(__UpperCAmelCase ) lowerCAmelCase__ = self.activation(__UpperCAmelCase ) return hidden_state class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase )-> Dict: '''simple docstring''' super().__init__() lowerCAmelCase__ = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) lowerCAmelCase__ = config.num_channels def UpperCAmelCase ( self , __UpperCAmelCase )-> Tuple: '''simple docstring''' lowerCAmelCase__ = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) lowerCAmelCase__ = self.embedder(__UpperCAmelCase ) return hidden_state class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 2 )-> Union[str, Any]: '''simple docstring''' super().__init__() lowerCAmelCase__ = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , kernel_size=1 , stride=__UpperCAmelCase , bias=__UpperCAmelCase ) lowerCAmelCase__ = nn.BatchNormad(__UpperCAmelCase ) def UpperCAmelCase ( self , __UpperCAmelCase )-> Tensor: '''simple docstring''' lowerCAmelCase__ = self.convolution(__UpperCAmelCase ) lowerCAmelCase__ = self.normalization(__UpperCAmelCase ) return hidden_state class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase )-> int: '''simple docstring''' super().__init__() lowerCAmelCase__ = nn.AdaptiveAvgPoolad((1, 1) ) lowerCAmelCase__ = nn.Sequential( nn.Convad(__UpperCAmelCase , __UpperCAmelCase , kernel_size=1 ) , nn.ReLU() , nn.Convad(__UpperCAmelCase , __UpperCAmelCase , kernel_size=1 ) , nn.Sigmoid() , ) def UpperCAmelCase ( self , __UpperCAmelCase )-> List[Any]: '''simple docstring''' lowerCAmelCase__ = self.pooler(__UpperCAmelCase ) lowerCAmelCase__ = self.attention(__UpperCAmelCase ) lowerCAmelCase__ = hidden_state * attention return hidden_state class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 1 )-> Tuple: '''simple docstring''' super().__init__() lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( RegNetShortCut(__UpperCAmelCase , __UpperCAmelCase , stride=__UpperCAmelCase ) if should_apply_shortcut else nn.Identity() ) lowerCAmelCase__ = nn.Sequential( RegNetConvLayer(__UpperCAmelCase , __UpperCAmelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__UpperCAmelCase , __UpperCAmelCase , stride=__UpperCAmelCase , groups=__UpperCAmelCase , activation=config.hidden_act ) , RegNetConvLayer(__UpperCAmelCase , __UpperCAmelCase , kernel_size=1 , activation=__UpperCAmelCase ) , ) lowerCAmelCase__ = ACTaFN[config.hidden_act] def UpperCAmelCase ( self , __UpperCAmelCase )-> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = hidden_state lowerCAmelCase__ = self.layer(__UpperCAmelCase ) lowerCAmelCase__ = self.shortcut(__UpperCAmelCase ) hidden_state += residual lowerCAmelCase__ = self.activation(__UpperCAmelCase ) return hidden_state class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 1 )-> Any: '''simple docstring''' super().__init__() lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( RegNetShortCut(__UpperCAmelCase , __UpperCAmelCase , stride=__UpperCAmelCase ) if should_apply_shortcut else nn.Identity() ) lowerCAmelCase__ = nn.Sequential( RegNetConvLayer(__UpperCAmelCase , __UpperCAmelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__UpperCAmelCase , __UpperCAmelCase , stride=__UpperCAmelCase , groups=__UpperCAmelCase , activation=config.hidden_act ) , RegNetSELayer(__UpperCAmelCase , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(__UpperCAmelCase , __UpperCAmelCase , kernel_size=1 , activation=__UpperCAmelCase ) , ) lowerCAmelCase__ = ACTaFN[config.hidden_act] def UpperCAmelCase ( self , __UpperCAmelCase )-> Any: '''simple docstring''' lowerCAmelCase__ = hidden_state lowerCAmelCase__ = self.layer(__UpperCAmelCase ) lowerCAmelCase__ = self.shortcut(__UpperCAmelCase ) hidden_state += residual lowerCAmelCase__ = self.activation(__UpperCAmelCase ) return hidden_state class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 2 , __UpperCAmelCase = 2 , )-> str: '''simple docstring''' super().__init__() lowerCAmelCase__ = RegNetXLayer if config.layer_type == "x" else RegNetYLayer lowerCAmelCase__ = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , stride=__UpperCAmelCase , ) , *[layer(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) for _ in range(depth - 1 )] , ) def UpperCAmelCase ( self , __UpperCAmelCase )-> str: '''simple docstring''' lowerCAmelCase__ = self.layers(__UpperCAmelCase ) return hidden_state class lowercase__ ( nn.Module ): def __init__( self , __UpperCAmelCase )-> Optional[int]: '''simple docstring''' super().__init__() lowerCAmelCase__ = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( __UpperCAmelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) lowerCAmelCase__ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(__UpperCAmelCase , config.depths[1:] ): self.stages.append(RegNetStage(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , depth=__UpperCAmelCase ) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = False , __UpperCAmelCase = True )-> BaseModelOutputWithNoAttention: '''simple docstring''' lowerCAmelCase__ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) lowerCAmelCase__ = stage_module(__UpperCAmelCase ) if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__UpperCAmelCase , hidden_states=__UpperCAmelCase ) class lowercase__ ( _UpperCAmelCase ): a_ =RegNetConfig a_ ="""regnet""" a_ ="""pixel_values""" a_ =True def UpperCAmelCase ( self , __UpperCAmelCase )-> Union[str, Any]: '''simple docstring''' if isinstance(__UpperCAmelCase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="fan_out" , nonlinearity="relu" ) elif isinstance(__UpperCAmelCase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase=False )-> List[Any]: '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ = value a_ = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a_ = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( """The bare RegNet model outputting raw features without any specific head on top.""", _UpperCAmelCase, ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class lowercase__ ( _UpperCAmelCase ): def __init__( self , __UpperCAmelCase )-> int: '''simple docstring''' super().__init__(__UpperCAmelCase ) lowerCAmelCase__ = config lowerCAmelCase__ = RegNetEmbeddings(__UpperCAmelCase ) lowerCAmelCase__ = RegNetEncoder(__UpperCAmelCase ) lowerCAmelCase__ = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__UpperCAmelCase , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None )-> BaseModelOutputWithPoolingAndNoAttention: '''simple docstring''' lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.embedder(__UpperCAmelCase ) lowerCAmelCase__ = self.encoder( __UpperCAmelCase , output_hidden_states=__UpperCAmelCase , return_dict=__UpperCAmelCase ) lowerCAmelCase__ = encoder_outputs[0] lowerCAmelCase__ = self.pooler(__UpperCAmelCase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__UpperCAmelCase , pooler_output=__UpperCAmelCase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( """ RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """, _UpperCAmelCase, ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class lowercase__ ( _UpperCAmelCase ): def __init__( self , __UpperCAmelCase )-> Any: '''simple docstring''' super().__init__(__UpperCAmelCase ) lowerCAmelCase__ = config.num_labels lowerCAmelCase__ = RegNetModel(__UpperCAmelCase ) # classification head lowerCAmelCase__ = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__UpperCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase ( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , )-> ImageClassifierOutputWithNoAttention: '''simple docstring''' lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet(__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , return_dict=__UpperCAmelCase ) lowerCAmelCase__ = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase__ = self.classifier(__UpperCAmelCase ) lowerCAmelCase__ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowerCAmelCase__ = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowerCAmelCase__ = "single_label_classification" else: lowerCAmelCase__ = "multi_label_classification" if self.config.problem_type == "regression": lowerCAmelCase__ = MSELoss() if self.num_labels == 1: lowerCAmelCase__ = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowerCAmelCase__ = loss_fct(__UpperCAmelCase , __UpperCAmelCase ) elif self.config.problem_type == "single_label_classification": lowerCAmelCase__ = CrossEntropyLoss() lowerCAmelCase__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowerCAmelCase__ = BCEWithLogitsLoss() lowerCAmelCase__ = loss_fct(__UpperCAmelCase , __UpperCAmelCase ) if not return_dict: lowerCAmelCase__ = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__UpperCAmelCase , logits=__UpperCAmelCase , hidden_states=outputs.hidden_states )
339
import functools def _a ( UpperCamelCase_ : list[int] , UpperCamelCase_ : list[int] ) -> int: """simple docstring""" if not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or not all(isinstance(UpperCamelCase_ , UpperCamelCase_ ) for day in days ): raise ValueError("The parameter days should be a list of integers" ) if len(UpperCamelCase_ ) != 3 or not all(isinstance(UpperCamelCase_ , UpperCamelCase_ ) for cost in costs ): raise ValueError("The parameter costs should be a list of three integers" ) if len(UpperCamelCase_ ) == 0: return 0 if min(UpperCamelCase_ ) <= 0: raise ValueError("All days elements should be greater than 0" ) if max(UpperCamelCase_ ) >= 366: raise ValueError("All days elements should be less than 366" ) lowerCAmelCase__ = set(UpperCamelCase_ ) @functools.cache def dynamic_programming(UpperCamelCase_ : int ) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 30 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
339
1
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": lowerCamelCase : Dict = argparse.ArgumentParser( description=( 'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='roberta', choices=['roberta', 'gpt2']) parser.add_argument('--model_name', default='roberta-large', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_roberta_048131723.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') lowerCamelCase : Union[str, Any] = parser.parse_args() if args.model_type == "roberta": lowerCamelCase : int = RobertaForMaskedLM.from_pretrained(args.model_name) lowerCamelCase : List[Any] = 'roberta' elif args.model_type == "gpt2": lowerCamelCase : str = GPTaLMHeadModel.from_pretrained(args.model_name) lowerCamelCase : Dict = 'transformer' lowerCamelCase : List[Any] = model.state_dict() lowerCamelCase : List[Any] = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: lowerCamelCase : Optional[int] = state_dict[f"""{prefix}.{param_name}"""] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: lowerCamelCase : List[Any] = f"""{prefix}.embeddings.{w}.weight""" lowerCamelCase : List[Any] = state_dict[param_name] for w in ["weight", "bias"]: lowerCamelCase : List[Any] = f"""{prefix}.embeddings.LayerNorm.{w}""" lowerCamelCase : Tuple = state_dict[param_name] # Transformer Blocks # lowerCamelCase : Optional[int] = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: lowerCamelCase : Any = state_dict[ f"""{prefix}.h.{teacher_idx}.{layer}.{w}""" ] lowerCamelCase : Union[str, Any] = state_dict[f"""{prefix}.h.{teacher_idx}.attn.bias"""] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: lowerCamelCase : Tuple = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}""" ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: lowerCamelCase : Union[str, Any] = state_dict[f"""{layer}"""] if args.vocab_transform: for w in ["weight", "bias"]: lowerCamelCase : Union[str, Any] = state_dict[f"""lm_head.dense.{w}"""] lowerCamelCase : Union[str, Any] = state_dict[f"""lm_head.layer_norm.{w}"""] elif args.model_type == "gpt2": for w in ["weight", "bias"]: lowerCamelCase : Optional[int] = state_dict[f"""{prefix}.ln_f.{w}"""] lowerCamelCase : Optional[int] = state_dict['lm_head.weight'] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
702
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCamelCase : Tuple = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
684
0
"""simple docstring""" import os def snake_case ( ) -> List[str]: with open(os.path.dirname(lowerCAmelCase_ ) + '''/grid.txt''' ) as f: _snake_case = [] # noqa: E741 for _ in range(20 ): l.append([int(lowerCAmelCase_ ) for x in f.readline().split()] ) _snake_case = 0 # right for i in range(20 ): for j in range(17 ): _snake_case = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: _snake_case = temp # down for i in range(17 ): for j in range(20 ): _snake_case = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: _snake_case = temp # diagonal 1 for i in range(17 ): for j in range(17 ): _snake_case = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: _snake_case = temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): _snake_case = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: _snake_case = temp return maximum if __name__ == "__main__": print(solution())
103
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ = {"configuration_plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["PLBartTokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "PLBART_PRETRAINED_MODEL_ARCHIVE_LIST", "PLBartForCausalLM", "PLBartForConditionalGeneration", "PLBartForSequenceClassification", "PLBartModel", "PLBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
143
0
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Optional[int]: # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection snake_case__ = len(__lowerCAmelCase ) snake_case__ = max(__lowerCAmelCase ) snake_case__ = min(__lowerCAmelCase ) # create the counting array snake_case__ = coll_max + 1 - coll_min snake_case__ = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , __lowerCAmelCase ): snake_case__ = counting_arr[i] + counting_arr[i - 1] # create the output collection snake_case__ = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , __lowerCAmelCase ) ): snake_case__ = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Optional[int]: return "".join([chr(__lowerCAmelCase ) for i in counting_sort([ord(__lowerCAmelCase ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string("""thisisthestring""") == "eghhiiinrsssttt" lowerCamelCase__ : Optional[Any] = input("""Enter numbers separated by a comma:\n""").strip() lowerCamelCase__ : List[str] = [int(item) for item in user_input.split(""",""")] print(counting_sort(unsorted))
208
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ : Optional[int] = logging.get_logger() @dataclass class __magic_name__ : '''simple docstring''' __lowercase : nn.Module __lowercase : List[nn.Module] = field(default_factory=snake_case_ ) __lowercase : list = field(default_factory=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self:Optional[int] , _a:int , _a:Tensor , _a:Tensor ): snake_case__ = len(list(m.modules() ) ) == 1 or isinstance(_a , nn.Convad ) or isinstance(_a , nn.BatchNormad ) if has_not_submodules: self.traced.append(_a ) def __call__( self:int , _a:Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(_a ) [x.remove() for x in self.handles] return self @property def SCREAMING_SNAKE_CASE__ ( self:List[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda _a : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class __magic_name__ : '''simple docstring''' __lowercase : nn.Module __lowercase : nn.Module __lowercase : int = 0 __lowercase : List = field(default_factory=snake_case_ ) __lowercase : List = field(default_factory=snake_case_ ) def __call__( self:List[Any] , _a:Tensor ): snake_case__ = Tracker(self.dest )(_a ).parametrized snake_case__ = Tracker(self.src )(_a ).parametrized snake_case__ = list(filter(lambda _a : type(_a ) not in self.src_skip , _a ) ) snake_case__ = list(filter(lambda _a : type(_a ) not in self.dest_skip , _a ) ) if len(_a ) != len(_a ): raise Exception( F"""Numbers of operations are different. Source module has {len(_a )} operations while""" F""" destination module has {len(_a )}.""" ) for dest_m, src_m in zip(_a , _a ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F"""Transfered from={src_m} to={dest_m}""" ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = True ) -> List[str]: print(F"""Converting {name}...""" ) with torch.no_grad(): snake_case__ = timm.create_model(__lowerCAmelCase , pretrained=__lowerCAmelCase ).eval() snake_case__ = ResNetForImageClassification(__lowerCAmelCase ).eval() snake_case__ = ModuleTransfer(src=__lowerCAmelCase , dest=__lowerCAmelCase ) snake_case__ = torch.randn((1, 3, 224, 224) ) module_transfer(__lowerCAmelCase ) assert torch.allclose(from_model(__lowerCAmelCase ) , our_model(__lowerCAmelCase ).logits ), "The model logits don't match the original one." snake_case__ = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(__lowerCAmelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=__lowerCAmelCase , ) # we can use the convnext one snake_case__ = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=__lowerCAmelCase , ) print(F"""Pushed {checkpoint_name}""" ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = True ) -> List[str]: snake_case__ = '''imagenet-1k-id2label.json''' snake_case__ = 1000 snake_case__ = (1, num_labels) snake_case__ = '''huggingface/label-files''' snake_case__ = num_labels snake_case__ = json.load(open(hf_hub_download(__lowerCAmelCase , __lowerCAmelCase , repo_type='''dataset''' ) , '''r''' ) ) snake_case__ = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} snake_case__ = idalabel snake_case__ = {v: k for k, v in idalabel.items()} snake_case__ = partial(__lowerCAmelCase , num_labels=__lowerCAmelCase , idalabel=__lowerCAmelCase , labelaid=__lowerCAmelCase ) snake_case__ = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(__lowerCAmelCase , names_to_config[model_name] , __lowerCAmelCase , __lowerCAmelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return config, expected_shape if __name__ == "__main__": lowerCamelCase__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported resnet* architecture,""" """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) lowerCamelCase__ : str = parser.parse_args() lowerCamelCase__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
208
1
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class A : @staticmethod def lowerCAmelCase__ ( *_lowerCAmelCase: Tuple , **_lowerCAmelCase: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' pass def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =hashlib.mda(image.tobytes() ) return m.hexdigest()[:1_0] def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =np.array(lowercase__ ) UpperCAmelCase_ =npimg.shape return {"hash": hashimage(lowercase__ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class A ( unittest.TestCase ): _snake_case =dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _snake_case =dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def lowerCAmelCase__ ( self: str , _lowerCAmelCase: Optional[int] , _lowerCAmelCase: int , _lowerCAmelCase: str ) -> Any: '''simple docstring''' UpperCAmelCase_ =MaskGenerationPipeline(model=_lowerCAmelCase , image_processor=_lowerCAmelCase ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def lowerCAmelCase__ ( self: Optional[Any] , _lowerCAmelCase: int , _lowerCAmelCase: Optional[Any] ) -> Dict: '''simple docstring''' pass @require_tf @unittest.skip("Image segmentation not implemented in TF" ) def lowerCAmelCase__ ( self: str ) -> int: '''simple docstring''' pass @slow @require_torch def lowerCAmelCase__ ( self: Optional[int] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ =pipeline("mask-generation" , model="facebook/sam-vit-huge" ) UpperCAmelCase_ =image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg" , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase_ =[] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_lowerCAmelCase ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.0_21}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, {"mask": {"hash": "e2d0b7a0b7", "shape": (480, 640)}, "scores": 0.99_67}, {"mask": {"hash": "453c7844bd", "shape": (480, 640)}, "scores": 0.9_93}, {"mask": {"hash": "3d44f2926d", "shape": (480, 640)}, "scores": 0.99_09}, {"mask": {"hash": "64033ddc3f", "shape": (480, 640)}, "scores": 0.98_79}, {"mask": {"hash": "801064ff79", "shape": (480, 640)}, "scores": 0.98_34}, {"mask": {"hash": "6172f276ef", "shape": (480, 640)}, "scores": 0.97_16}, {"mask": {"hash": "b49e60e084", "shape": (480, 640)}, "scores": 0.96_12}, {"mask": {"hash": "a811e775fd", "shape": (480, 640)}, "scores": 0.95_99}, {"mask": {"hash": "a6a8ebcf4b", "shape": (480, 640)}, "scores": 0.95_52}, {"mask": {"hash": "9d8257e080", "shape": (480, 640)}, "scores": 0.95_32}, {"mask": {"hash": "32de6454a8", "shape": (480, 640)}, "scores": 0.95_16}, {"mask": {"hash": "af3d4af2c8", "shape": (480, 640)}, "scores": 0.94_99}, {"mask": {"hash": "3c6db475fb", "shape": (480, 640)}, "scores": 0.94_83}, {"mask": {"hash": "c290813fb9", "shape": (480, 640)}, "scores": 0.94_64}, {"mask": {"hash": "b6f0b8f606", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "92ce16bfdf", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "c749b25868", "shape": (480, 640)}, "scores": 0.94_08}, {"mask": {"hash": "efb6cab859", "shape": (480, 640)}, "scores": 0.93_35}, {"mask": {"hash": "1ff2eafb30", "shape": (480, 640)}, "scores": 0.93_26}, {"mask": {"hash": "788b798e24", "shape": (480, 640)}, "scores": 0.92_62}, {"mask": {"hash": "abea804f0e", "shape": (480, 640)}, "scores": 0.89_99}, {"mask": {"hash": "7b9e8ddb73", "shape": (480, 640)}, "scores": 0.89_86}, {"mask": {"hash": "cd24047c8a", "shape": (480, 640)}, "scores": 0.89_84}, {"mask": {"hash": "6943e6bcbd", "shape": (480, 640)}, "scores": 0.88_73}, {"mask": {"hash": "b5f47c9191", "shape": (480, 640)}, "scores": 0.88_71} ] , ) # fmt: on @require_torch @slow def lowerCAmelCase__ ( self: str ) -> Any: '''simple docstring''' UpperCAmelCase_ ="facebook/sam-vit-huge" UpperCAmelCase_ =pipeline("mask-generation" , model=_lowerCAmelCase ) UpperCAmelCase_ =image_segmenter( "http://images.cocodataset.org/val2017/000000039769.jpg" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase_ =[] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_lowerCAmelCase ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.02_10}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, ] , )
54
'''simple docstring''' __UpperCAmelCase = """0.18.2""" from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( 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, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel 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 .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
379
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "InformerForPrediction", "InformerModel", "InformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
715
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = "https://openaipublic.azureedge.net/jukebox/models/" UpperCAmelCase__ = { "jukebox-1b-lyrics": [ "5b/vqvae.pth.tar", "5b/prior_level_0.pth.tar", "5b/prior_level_1.pth.tar", "1b_lyrics/prior_level_2.pth.tar", ], "jukebox-5b-lyrics": [ "5b/vqvae.pth.tar", "5b/prior_level_0.pth.tar", "5b/prior_level_1.pth.tar", "5b_lyrics/prior_level_2.pth.tar", ], } def A ( _UpperCAmelCase : List[str] ) -> Tuple: '''simple docstring''' if key.endswith('.model.1.bias' ) and len(key.split('.' ) ) > 10: _UpperCAmelCase = key.replace('.model.1.bias' , '.conv1d_1.bias' ) elif key.endswith('.model.1.weight' ) and len(key.split('.' ) ) > 10: _UpperCAmelCase = key.replace('.model.1.weight' , '.conv1d_1.weight' ) elif key.endswith('.model.3.bias' ) and len(key.split('.' ) ) > 10: _UpperCAmelCase = key.replace('.model.3.bias' , '.conv1d_2.bias' ) elif key.endswith('.model.3.weight' ) and len(key.split('.' ) ) > 10: _UpperCAmelCase = key.replace('.model.3.weight' , '.conv1d_2.weight' ) if "conditioner_blocks.0." in key: _UpperCAmelCase = key.replace('conditioner_blocks.0' , 'conditioner_blocks' ) if "prime_prior" in key: _UpperCAmelCase = key.replace('prime_prior' , 'encoder' ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: _UpperCAmelCase = key.replace('.emb.' , '.' ) if key.endswith('k' ): # replace vqvae.X.k with vqvae.X.codebook return key.replace('.k' , '.codebook' ) if "y_emb." in key: return key.replace('y_emb.' , 'metadata_embedding.' ) if "x_emb.emb." in key: _UpperCAmelCase = key.replace('0.x_emb.emb' , 'embed_tokens' ) if "prime_state_ln" in key: return key.replace('prime_state_ln' , 'encoder.final_layer_norm' ) if ".ln" in key: return key.replace('.ln' , '.layer_norm' ) if "_ln" in key: return key.replace('_ln' , '_layer_norm' ) if "prime_state_proj" in key: return key.replace('prime_state_proj' , 'encoder.proj_in' ) if "prime_x_out" in key: return key.replace('prime_x_out' , 'encoder.lm_head' ) if "prior.x_out" in key: return key.replace('x_out' , 'fc_proj_out' ) if "x_emb" in key: return key.replace('x_emb' , 'embed_tokens' ) return key def A ( _UpperCAmelCase : str , _UpperCAmelCase : str , _UpperCAmelCase : Tuple , _UpperCAmelCase : List[Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = {} import re _UpperCAmelCase = re.compile(R'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) _UpperCAmelCase = re.compile( R'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) _UpperCAmelCase = re.compile( R'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)' ) _UpperCAmelCase = re.compile( R'conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)' ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_encoder_block_conv_in.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) _UpperCAmelCase = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}" _UpperCAmelCase = re_encoder_block_conv_in.sub(_UpperCAmelCase , _UpperCAmelCase ) elif re_encoder_block_resnet.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_encoder_block_resnet.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) _UpperCAmelCase = {'1': 1, '3': 2}[groups[-2]] _UpperCAmelCase = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}." _UpperCAmelCase = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" _UpperCAmelCase = prefix + resnet_block _UpperCAmelCase = re_encoder_block_resnet.sub(_UpperCAmelCase , _UpperCAmelCase ) elif re_encoder_block_proj_out.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_encoder_block_proj_out.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = F"encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}" _UpperCAmelCase = re_encoder_block_proj_out.sub(_UpperCAmelCase , _UpperCAmelCase ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_decoder_block_conv_out.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 _UpperCAmelCase = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}" _UpperCAmelCase = re_decoder_block_conv_out.sub(_UpperCAmelCase , _UpperCAmelCase ) elif re_decoder_block_resnet.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_decoder_block_resnet.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 _UpperCAmelCase = {'1': 1, '3': 2}[groups[-2]] _UpperCAmelCase = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}." _UpperCAmelCase = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" _UpperCAmelCase = prefix + resnet_block _UpperCAmelCase = re_decoder_block_resnet.sub(_UpperCAmelCase , _UpperCAmelCase ) elif re_decoder_block_proj_in.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_decoder_block_proj_in.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = F"decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}" _UpperCAmelCase = re_decoder_block_proj_in.sub(_UpperCAmelCase , _UpperCAmelCase ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_prior_cond_conv_out.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 _UpperCAmelCase = F"conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}" _UpperCAmelCase = re_prior_cond_conv_out.sub(_UpperCAmelCase , _UpperCAmelCase ) elif re_prior_cond_resnet.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_prior_cond_resnet.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 _UpperCAmelCase = {'1': 1, '3': 2}[groups[-2]] _UpperCAmelCase = F"conditioner_blocks.upsampler.upsample_block.{block_index}." _UpperCAmelCase = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" _UpperCAmelCase = prefix + resnet_block _UpperCAmelCase = re_prior_cond_resnet.sub(_UpperCAmelCase , _UpperCAmelCase ) elif re_prior_cond_proj_in.fullmatch(_UpperCAmelCase ): _UpperCAmelCase = re_prior_cond_proj_in.match(_UpperCAmelCase ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = F"conditioner_blocks.upsampler.proj_in.{groups[-1]}" _UpperCAmelCase = re_prior_cond_proj_in.sub(_UpperCAmelCase , _UpperCAmelCase ) # keep original key else: _UpperCAmelCase = original_key _UpperCAmelCase = replace_key(_UpperCAmelCase ) if F"{key_prefix}.{key}" not in model_state_dict or key is None: print(F"failed converting {original_key} to {key}, does not match" ) # handle missmatched shape elif value.shape != model_state_dict[F"{key_prefix}.{key}"].shape: _UpperCAmelCase = model_state_dict[F"{key_prefix}.{key}"] print(F"{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match" ) _UpperCAmelCase = original_key _UpperCAmelCase = original_key _UpperCAmelCase = value return new_dict @torch.no_grad() def A ( _UpperCAmelCase : List[str]=None , _UpperCAmelCase : Dict=None ) -> Dict: '''simple docstring''' for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" ): _UpperCAmelCase = requests.get(F"{PREFIX}{file}" , allow_redirects=_UpperCAmelCase ) os.makedirs(F"{pytorch_dump_folder_path}/" , exist_ok=_UpperCAmelCase ) open(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" , 'wb' ).write(r.content ) _UpperCAmelCase = MODEL_MAPPING[model_name.split('/' )[-1]] _UpperCAmelCase = JukeboxConfig.from_pretrained(_UpperCAmelCase ) _UpperCAmelCase = JukeboxModel(_UpperCAmelCase ) _UpperCAmelCase = [] _UpperCAmelCase = {} for i, dict_name in enumerate(_UpperCAmelCase ): _UpperCAmelCase = torch.load(F"{pytorch_dump_folder_path}/{dict_name.split('/' )[-1]}" )['model'] _UpperCAmelCase = {} for k in old_dic.keys(): if k.endswith('.b' ): _UpperCAmelCase = old_dic[k] elif k.endswith('.w' ): _UpperCAmelCase = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: _UpperCAmelCase = old_dic[k] else: _UpperCAmelCase = old_dic[k] _UpperCAmelCase = 'vqvae' if i == 0 else F"priors.{3 - i}" _UpperCAmelCase = fix_jukebox_keys(_UpperCAmelCase , model.state_dict() , _UpperCAmelCase , _UpperCAmelCase ) weight_dict.append(_UpperCAmelCase ) _UpperCAmelCase = weight_dict.pop(0 ) model.vqvae.load_state_dict(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) with open(F"{pytorch_dump_folder_path}/mapping.json" , 'w' ) as txtfile: json.dump(_UpperCAmelCase , _UpperCAmelCase ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCAmelCase ) return weight_dict if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="jukebox-5b-lyrics", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default="jukebox-5b-lyrics-converted", type=str, help="Path to the output PyTorch model directory.", ) UpperCAmelCase__ = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
639
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase_ = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n >>> pipe_prior.to("cuda")\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n >>> pipe.to("cuda")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save("cat.png")\n ```\n' def a ( A__ : Any , A__ : Optional[Any] , A__ : Optional[Any]=8 ) -> int: """simple docstring""" _lowercase =height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _lowercase =width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class __lowerCAmelCase ( SCREAMING_SNAKE_CASE ): def __init__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ) -> Any: '''simple docstring''' super().__init__() self.register_modules( unet=lowerCAmelCase , scheduler=lowerCAmelCase , movq=lowerCAmelCase , ) _lowercase =2 ** (len(self.movq.config.block_out_channels ) - 1) def A__ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Tuple: '''simple docstring''' if latents is None: _lowercase =randn_tensor(lowerCAmelCase , generator=lowerCAmelCase , device=lowerCAmelCase , dtype=lowerCAmelCase ) else: if latents.shape != shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) _lowercase =latents.to(lowerCAmelCase ) _lowercase =latents * scheduler.init_noise_sigma return latents def A__ ( self , lowerCAmelCase=0 ) -> Optional[int]: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) _lowercase =torch.device(F'''cuda:{gpu_id}''' ) _lowercase =[ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCAmelCase , lowerCAmelCase ) def A__ ( self , lowerCAmelCase=0 ) -> str: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) _lowercase =torch.device(F'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=lowerCAmelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _lowercase =None for cpu_offloaded_model in [self.unet, self.movq]: _lowercase , _lowercase =cpu_offload_with_hook(lowerCAmelCase , lowerCAmelCase , prev_module_hook=lowerCAmelCase ) # We'll offload the last model manually. _lowercase =hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def A__ ( self ) -> Tuple: '''simple docstring''' if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCAmelCase , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(lowerCAmelCase ) def __call__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = 512 , lowerCAmelCase = 512 , lowerCAmelCase = 100 , lowerCAmelCase = 4.0 , lowerCAmelCase = 1 , lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = "pil" , lowerCAmelCase = True , ) -> List[str]: '''simple docstring''' _lowercase =self._execution_device _lowercase =guidance_scale > 1.0 if isinstance(lowerCAmelCase , lowerCAmelCase ): _lowercase =torch.cat(lowerCAmelCase , dim=0 ) _lowercase =image_embeds.shape[0] * num_images_per_prompt if isinstance(lowerCAmelCase , lowerCAmelCase ): _lowercase =torch.cat(lowerCAmelCase , dim=0 ) if do_classifier_free_guidance: _lowercase =image_embeds.repeat_interleave(lowerCAmelCase , dim=0 ) _lowercase =negative_image_embeds.repeat_interleave(lowerCAmelCase , dim=0 ) _lowercase =torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCAmelCase ) self.scheduler.set_timesteps(lowerCAmelCase , device=lowerCAmelCase ) _lowercase =self.scheduler.timesteps _lowercase =self.unet.config.in_channels _lowercase , _lowercase =downscale_height_and_width(lowerCAmelCase , lowerCAmelCase , self.movq_scale_factor ) # create initial latent _lowercase =self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCAmelCase ) ): # expand the latents if we are doing classifier free guidance _lowercase =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _lowercase ={'image_embeds': image_embeds} _lowercase =self.unet( sample=lowerCAmelCase , timestep=lowerCAmelCase , encoder_hidden_states=lowerCAmelCase , added_cond_kwargs=lowerCAmelCase , return_dict=lowerCAmelCase , )[0] if do_classifier_free_guidance: _lowercase , _lowercase =noise_pred.split(latents.shape[1] , dim=1 ) _lowercase , _lowercase =noise_pred.chunk(2 ) _lowercase , _lowercase =variance_pred.chunk(2 ) _lowercase =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _lowercase =torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _lowercase , _lowercase =noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _lowercase =self.scheduler.step( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , generator=lowerCAmelCase , )[0] # post-processing _lowercase =self.movq.decode(lowerCAmelCase , force_not_quantize=lowerCAmelCase )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: _lowercase =image * 0.5 + 0.5 _lowercase =image.clamp(0 , 1 ) _lowercase =image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _lowercase =self.numpy_to_pil(lowerCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase )
291
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder lowercase_ = datasets.utils.logging.get_logger(__name__) class __lowerCAmelCase ( folder_based_builder.FolderBasedBuilderConfig ): _a = None _a = None class __lowerCAmelCase ( folder_based_builder.FolderBasedBuilder ): _a = datasets.Audio() _a = """audio""" _a = AudioFolderConfig _a = 42 # definition at the bottom of the script _a = AudioClassification(audio_column="""audio""" , label_column="""label""" ) lowercase_ = [ '.aiff', '.au', '.avr', '.caf', '.flac', '.htk', '.svx', '.mat4', '.mat5', '.mpc2k', '.ogg', '.paf', '.pvf', '.raw', '.rf64', '.sd2', '.sds', '.ircam', '.voc', '.w64', '.wav', '.nist', '.wavex', '.wve', '.xi', '.mp3', '.opus', ] lowercase_ = AUDIO_EXTENSIONS
291
1
def A__ ( lowerCamelCase , lowerCamelCase ) -> int: while second != 0: UpperCamelCase_: Optional[Any] = first & second first ^= second UpperCamelCase_: Any = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : List[Any] = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : Tuple = int(input("""Enter the second number: """).strip()) print(F"""{add(first, second) = }""")
670
class _UpperCamelCase : '''simple docstring''' def __init__( self : List[str] , snake_case_ : int , snake_case_ : Optional[Any]=None , snake_case_ : List[str]=None ): UpperCamelCase_: List[Any] = data UpperCamelCase_: List[Any] = previous UpperCamelCase_: Tuple = next_node def __str__( self : Dict ): return f'''{self.data}''' def lowerCAmelCase__ ( self : List[str] ): return self.data def lowerCAmelCase__ ( self : Any ): return self.next def lowerCAmelCase__ ( self : List[str] ): return self.previous class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[Any] , snake_case_ : int ): UpperCamelCase_: Union[str, Any] = head def __iter__( self : Union[str, Any] ): return self def lowerCAmelCase__ ( self : Union[str, Any] ): if not self.current: raise StopIteration else: UpperCamelCase_: Dict = self.current.get_data() UpperCamelCase_: Tuple = self.current.get_next() return value class _UpperCamelCase : '''simple docstring''' def __init__( self : int ): UpperCamelCase_: Optional[int] = None # First node in list UpperCamelCase_: Dict = None # Last node in list def __str__( self : Tuple ): UpperCamelCase_: int = self.head UpperCamelCase_: Tuple = [] while current is not None: nodes.append(current.get_data() ) UpperCamelCase_: List[str] = current.get_next() return " ".join(str(snake_case_ ) for node in nodes ) def __contains__( self : int , snake_case_ : int ): UpperCamelCase_: Optional[Any] = self.head while current: if current.get_data() == value: return True UpperCamelCase_: Any = current.get_next() return False def __iter__( self : Any ): return LinkedListIterator(self.head ) def lowerCAmelCase__ ( self : Tuple ): if self.head: return self.head.get_data() return None def lowerCAmelCase__ ( self : Optional[Any] ): if self.tail: return self.tail.get_data() return None def lowerCAmelCase__ ( self : Optional[int] , snake_case_ : Node ): if self.head is None: UpperCamelCase_: Tuple = node UpperCamelCase_: Optional[int] = node else: self.insert_before_node(self.head , snake_case_ ) def lowerCAmelCase__ ( self : Optional[Any] , snake_case_ : Node ): if self.head is None: self.set_head(snake_case_ ) else: self.insert_after_node(self.tail , snake_case_ ) def lowerCAmelCase__ ( self : List[Any] , snake_case_ : int ): UpperCamelCase_: Any = Node(snake_case_ ) if self.head is None: self.set_head(snake_case_ ) else: self.set_tail(snake_case_ ) def lowerCAmelCase__ ( self : Optional[Any] , snake_case_ : Node , snake_case_ : Node ): UpperCamelCase_: str = node UpperCamelCase_: int = node.previous if node.get_previous() is None: UpperCamelCase_: int = node_to_insert else: UpperCamelCase_: Dict = node_to_insert UpperCamelCase_: int = node_to_insert def lowerCAmelCase__ ( self : Dict , snake_case_ : Node , snake_case_ : Node ): UpperCamelCase_: Tuple = node UpperCamelCase_: Dict = node.next if node.get_next() is None: UpperCamelCase_: Union[str, Any] = node_to_insert else: UpperCamelCase_: str = node_to_insert UpperCamelCase_: int = node_to_insert def lowerCAmelCase__ ( self : Tuple , snake_case_ : int , snake_case_ : int ): UpperCamelCase_: Union[str, Any] = 1 UpperCamelCase_: List[str] = Node(snake_case_ ) UpperCamelCase_: Optional[Any] = self.head while node: if current_position == position: self.insert_before_node(snake_case_ , snake_case_ ) return current_position += 1 UpperCamelCase_: Dict = node.next self.insert_after_node(self.tail , snake_case_ ) def lowerCAmelCase__ ( self : int , snake_case_ : int ): UpperCamelCase_: Union[str, Any] = self.head while node: if node.get_data() == item: return node UpperCamelCase_: List[Any] = node.get_next() raise Exception("""Node not found""" ) def lowerCAmelCase__ ( self : List[Any] , snake_case_ : List[str] ): if (node := self.get_node(snake_case_ )) is not None: if node == self.head: UpperCamelCase_: Optional[int] = self.head.get_next() if node == self.tail: UpperCamelCase_: Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(snake_case_ ) @staticmethod def lowerCAmelCase__ ( snake_case_ : Node ): if node.get_next(): UpperCamelCase_: str = node.previous if node.get_previous(): UpperCamelCase_: int = node.next UpperCamelCase_: List[str] = None UpperCamelCase_: int = None def lowerCAmelCase__ ( self : str ): return self.head is None def A__ ( ) -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
670
1
'''simple docstring''' from __future__ import annotations import time lowerCAmelCase : Union[str, Any] = list[tuple[int, int]] lowerCAmelCase : Optional[Any] = [ [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], ] lowerCAmelCase : Optional[int] = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class UpperCamelCase__ : """simple docstring""" def __init__( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Any = pos_x _lowerCAmelCase : List[Any] = pos_y _lowerCAmelCase : Union[str, Any] = (pos_y, pos_x) _lowerCAmelCase : int = goal_x _lowerCAmelCase : Any = goal_y _lowerCAmelCase : int = parent class UpperCamelCase__ : """simple docstring""" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = Node(start[1] , start[0] , goal[1] , goal[0] , snake_case__ ) _lowerCAmelCase : str = Node(goal[1] , goal[0] , goal[1] , goal[0] , snake_case__ ) _lowerCAmelCase : Dict = [self.start] _lowerCAmelCase : str = False def a ( self ): '''simple docstring''' while self.node_queue: _lowerCAmelCase : Any = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: _lowerCAmelCase : Optional[int] = True return self.retrace_path(snake_case__ ) _lowerCAmelCase : Union[str, Any] = self.get_successors(snake_case__ ) for node in successors: self.node_queue.append(snake_case__ ) if not self.reached: return [self.start.pos] return None def a ( self , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Optional[int] = [] for action in delta: _lowerCAmelCase : int = parent.pos_x + action[1] _lowerCAmelCase : Any = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(snake_case__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(snake_case__ , snake_case__ , self.target.pos_y , self.target.pos_x , snake_case__ ) ) return successors def a ( self , snake_case__ ): '''simple docstring''' _lowerCAmelCase : int = 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 UpperCamelCase__ : """simple docstring""" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Dict = BreadthFirstSearch(snake_case__ , snake_case__ ) _lowerCAmelCase : Optional[int] = BreadthFirstSearch(snake_case__ , snake_case__ ) _lowerCAmelCase : Dict = False def a ( self ): '''simple docstring''' while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: _lowerCAmelCase : Union[str, Any] = self.fwd_bfs.node_queue.pop(0 ) _lowerCAmelCase : Optional[Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: _lowerCAmelCase : List[Any] = True return self.retrace_bidirectional_path( snake_case__ , snake_case__ ) _lowerCAmelCase : Union[str, Any] = current_bwd_node _lowerCAmelCase : List[Any] = current_fwd_node _lowerCAmelCase : Optional[Any] = { self.fwd_bfs: self.fwd_bfs.get_successors(snake_case__ ), self.bwd_bfs: self.bwd_bfs.get_successors(snake_case__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(snake_case__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def a ( self , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = self.fwd_bfs.retrace_path(snake_case__ ) _lowerCAmelCase : List[Any] = self.bwd_bfs.retrace_path(snake_case__ ) bwd_path.pop() bwd_path.reverse() _lowerCAmelCase : Union[str, Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() lowerCAmelCase : Union[str, Any] = (0, 0) lowerCAmelCase : int = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) lowerCAmelCase : List[str] = time.time() lowerCAmelCase : Any = BreadthFirstSearch(init, goal) lowerCAmelCase : List[str] = bfs.search() lowerCAmelCase : List[Any] = time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) lowerCAmelCase : Dict = time.time() lowerCAmelCase : Union[str, Any] = BidirectionalBreadthFirstSearch(init, goal) lowerCAmelCase : Any = bd_bfs.search() lowerCAmelCase : List[Any] = time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
444
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowerCAmelCase : Optional[int] = datasets.logging.get_logger(__name__) lowerCAmelCase : List[str] = """\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } """ lowerCAmelCase : List[Any] = """\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project's README at https://github.com/google-research/bleurt#readme for more information. """ lowerCAmelCase : str = """ BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: 'scores': List of scores. Examples: >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> bleurt = datasets.load_metric(\"bleurt\") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results[\"scores\"]]) [1.03, 1.04] """ lowerCAmelCase : Optional[Any] = { """bleurt-tiny-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip""", """bleurt-tiny-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip""", """bleurt-base-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip""", """bleurt-base-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip""", """bleurt-large-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip""", """bleurt-large-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip""", """BLEURT-20-D3""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip""", """BLEURT-20-D6""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip""", """BLEURT-20-D12""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip""", """BLEURT-20""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip""", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): """simple docstring""" def a ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/google-research/bleurt' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/google-research/bleurt'] , reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'] , ) def a ( self , snake_case__ ): '''simple docstring''' if self.config_name == "default": logger.warning( 'Using default BLEURT-Base checkpoint for sequence maximum length 128. ' 'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' ) _lowerCAmelCase : Tuple = 'bleurt-base-128' if self.config_name.lower() in CHECKPOINT_URLS: _lowerCAmelCase : int = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: _lowerCAmelCase : str = self.config_name.upper() else: raise KeyError( F'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' ) # download the model checkpoint specified by self.config_name and set up the scorer _lowerCAmelCase : Optional[Any] = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) _lowerCAmelCase : str = score.BleurtScorer(os.path.join(snake_case__ , snake_case__ ) ) def a ( self , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Tuple = self.scorer.score(references=snake_case__ , candidates=snake_case__ ) return {"scores": scores}
444
1
import socket def lowerCamelCase__ ( ) -> int: '''simple docstring''' _snake_case = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) _snake_case = socket.gethostname() _snake_case = 12_312 sock.connect((host, port) ) sock.send(b'Hello server!' ) with open('Received_file' , 'wb' ) as out_file: print('File opened' ) print('Receiving data...' ) while True: _snake_case = sock.recv(1_024 ) if not data: break out_file.write(__A ) print('Successfully received the file' ) sock.close() print('Connection closed' ) if __name__ == "__main__": main()
715
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset UpperCAmelCase_ = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class UpperCamelCase_ ( nn.Module ): def __init__( self , lowerCAmelCase_ ) -> int: super().__init__() _snake_case = torchvision.models.resnetaaa(pretrained=lowerCAmelCase_ ) _snake_case = list(model.children() )[:-2] _snake_case = nn.Sequential(*lowerCAmelCase_ ) _snake_case = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def lowerCAmelCase ( self , lowerCAmelCase_ ) -> str: # Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048 _snake_case = self.pool(self.model(lowerCAmelCase_ ) ) _snake_case = torch.flatten(lowerCAmelCase_ , start_dim=2 ) _snake_case = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class UpperCamelCase_ ( _lowerCamelCase ): def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[Any]: _snake_case = [json.loads(lowerCAmelCase_ ) for l in open(lowerCAmelCase_ )] _snake_case = os.path.dirname(lowerCAmelCase_ ) _snake_case = tokenizer _snake_case = labels _snake_case = len(lowerCAmelCase_ ) _snake_case = max_seq_length _snake_case = transforms def __len__( self ) -> Any: return len(self.data ) def __getitem__( self , lowerCAmelCase_ ) -> Optional[int]: _snake_case = torch.LongTensor(self.tokenizer.encode(self.data[index]['text'] , add_special_tokens=lowerCAmelCase_ ) ) _snake_case , _snake_case , _snake_case = sentence[0], sentence[1:-1], sentence[-1] _snake_case = sentence[: self.max_seq_length] _snake_case = torch.zeros(self.n_classes ) _snake_case = 1 _snake_case = Image.open(os.path.join(self.data_dir , self.data[index]['img'] ) ).convert('RGB' ) _snake_case = self.transforms(lowerCAmelCase_ ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def lowerCAmelCase ( self ) -> Tuple: _snake_case = Counter() for row in self.data: label_freqs.update(row['label'] ) return label_freqs def lowerCamelCase__ ( UpperCamelCase__ : str ) -> Dict: '''simple docstring''' _snake_case = [len(row['sentence'] ) for row in batch] _snake_case , _snake_case = len(UpperCamelCase__ ), max(UpperCamelCase__ ) _snake_case = torch.zeros(UpperCamelCase__ , UpperCamelCase__ , dtype=torch.long ) _snake_case = torch.zeros(UpperCamelCase__ , UpperCamelCase__ , dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(UpperCamelCase__ , UpperCamelCase__ ) ): _snake_case = input_row['sentence'] _snake_case = 1 _snake_case = torch.stack([row['image'] for row in batch] ) _snake_case = torch.stack([row['label'] for row in batch] ) _snake_case = torch.stack([row['image_start_token'] for row in batch] ) _snake_case = torch.stack([row['image_end_token'] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def lowerCamelCase__ ( ) -> str: '''simple docstring''' return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def lowerCamelCase__ ( ) -> Tuple: '''simple docstring''' return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.4677_7044, 0.4453_1429, 0.4066_1017] , std=[0.1222_1994, 0.1214_5835, 0.1438_0469] , ), ] )
541
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase__ = { '''configuration_blip_2''': [ '''BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Blip2Config''', '''Blip2QFormerConfig''', '''Blip2VisionConfig''', ], '''processing_blip_2''': ['''Blip2Processor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ '''BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Blip2Model''', '''Blip2QFormerModel''', '''Blip2PreTrainedModel''', '''Blip2ForConditionalGeneration''', '''Blip2VisionModel''', ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
547
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class _lowerCAmelCase ( unittest.TestCase ): def __init__( self : Tuple , __snake_case : int , __snake_case : List[str]=13 , __snake_case : int=7 , __snake_case : int=True , __snake_case : int=True , __snake_case : Dict=True , __snake_case : str=True , __snake_case : Dict=99 , __snake_case : Optional[int]=32 , __snake_case : Optional[Any]=5 , __snake_case : Union[str, Any]=4 , __snake_case : Union[str, Any]=37 , __snake_case : int="gelu" , __snake_case : Union[str, Any]=0.1 , __snake_case : Union[str, Any]=0.1 , __snake_case : Any=512 , __snake_case : Dict=16 , __snake_case : Optional[int]=2 , __snake_case : str=0.0_2 , __snake_case : int=4 , ): lowerCamelCase :Union[str, Any] = parent lowerCamelCase :str = batch_size lowerCamelCase :Dict = seq_length lowerCamelCase :int = is_training lowerCamelCase :int = use_attention_mask lowerCamelCase :Optional[Any] = use_token_type_ids lowerCamelCase :int = use_labels lowerCamelCase :List[Any] = vocab_size lowerCamelCase :str = hidden_size lowerCamelCase :Optional[int] = num_hidden_layers lowerCamelCase :Tuple = num_attention_heads lowerCamelCase :Tuple = intermediate_size lowerCamelCase :Tuple = hidden_act lowerCamelCase :Any = hidden_dropout_prob lowerCamelCase :List[str] = attention_probs_dropout_prob lowerCamelCase :Any = max_position_embeddings lowerCamelCase :Dict = type_vocab_size lowerCamelCase :int = type_sequence_label_size lowerCamelCase :str = initializer_range lowerCamelCase :Any = num_choices def snake_case ( self : Any ): lowerCamelCase :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase :Any = None if self.use_attention_mask: lowerCamelCase :int = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase :Dict = None if self.use_token_type_ids: lowerCamelCase :Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase :List[str] = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__snake_case , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def snake_case ( self : Any ): lowerCamelCase :int = self.prepare_config_and_inputs() lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase :Any = config_and_inputs lowerCamelCase :str = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def snake_case ( self : str ): lowerCamelCase :Optional[int] = self.prepare_config_and_inputs() lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase :Optional[Any] = config_and_inputs lowerCamelCase :List[Any] = True lowerCamelCase :Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCamelCase :str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class _lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase = True _UpperCAmelCase = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def snake_case ( self : Optional[int] ): lowerCamelCase :str = FlaxRobertaPreLayerNormModelTester(self ) @slow def snake_case ( self : Any ): for model_class_name in self.all_model_classes: lowerCamelCase :Dict = model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=__snake_case ) lowerCamelCase :Optional[Any] = model(np.ones((1, 1) ) ) self.assertIsNotNone(__snake_case ) @require_flax class _lowerCAmelCase ( unittest.TestCase ): @slow def snake_case ( self : Tuple ): lowerCamelCase :List[str] = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=__snake_case ) lowerCamelCase :int = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] , dtype=jnp.intaa ) lowerCamelCase :List[str] = model(__snake_case )[0] lowerCamelCase :Tuple = [1, 11, 50265] self.assertEqual(list(output.shape ) , __snake_case ) # compare the actual values for a slice. lowerCamelCase :Optional[Any] = np.array( [[[4_0.4_8_8_0, 1_8.0_1_9_9, -5.2_3_6_7], [-1.8_8_7_7, -4.0_8_8_5, 1_0.7_0_8_5], [-2.2_6_1_3, -5.6_1_1_0, 7.2_6_6_5]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , __snake_case , atol=1e-4 ) ) @slow def snake_case ( self : Any ): lowerCamelCase :Optional[int] = FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=__snake_case ) lowerCamelCase :Union[str, Any] = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] , dtype=jnp.intaa ) lowerCamelCase :int = model(__snake_case )[0] # compare the actual values for a slice. lowerCamelCase :List[Any] = np.array( [[[0.0_2_0_8, -0.0_3_5_6, 0.0_2_3_7], [-0.1_5_6_9, -0.0_4_1_1, -0.2_6_2_6], [0.1_8_7_9, 0.0_1_2_5, -0.0_0_8_9]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , __snake_case , atol=1e-4 ) )
166
0
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger lowercase = '''<<<<<<< This should probably be modified because it mentions: ''' lowercase = '''======= >>>>>>> ''' lowercase = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] lowercase = [ # (pattern, replacement) # Order is important here for some replacements (r'''tfds\.core''', r'''datasets'''), (r'''tf\.io\.gfile\.GFile''', r'''open'''), (r'''tf\.([\w\d]+)''', r'''datasets.Value(\'\1\')'''), (r'''tfds\.features\.Text\(\)''', r'''datasets.Value(\'string\')'''), (r'''tfds\.features\.Text\(''', r'''datasets.Value(\'string\'),'''), (r'''features\s*=\s*tfds.features.FeaturesDict\(''', r'''features=datasets.Features('''), (r'''tfds\.features\.FeaturesDict\(''', r'''dict('''), (r'''The TensorFlow Datasets Authors''', r'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (r'''tfds\.''', r'''datasets.'''), (r'''dl_manager\.manual_dir''', r'''self.config.data_dir'''), (r'''self\.builder_config''', r'''self.config'''), ] def UpperCAmelCase ( A : Namespace ): '''simple docstring''' return ConvertCommand(args.tfds_path , args.datasets_directory ) class lowercase__ ( A ): '''simple docstring''' @staticmethod def lowerCamelCase_ ( snake_case ) -> str: _UpperCAmelCase = parser.add_parser( 'convert' , help='Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.' , ) train_parser.add_argument( '--tfds_path' , type=snake_case , required=snake_case , help='Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.' , ) train_parser.add_argument( '--datasets_directory' , type=snake_case , required=snake_case , help='Path to the HuggingFace Datasets folder.' ) train_parser.set_defaults(func=snake_case ) def __init__( self , snake_case , snake_case , *snake_case ) -> Any: _UpperCAmelCase = get_logger('datasets-cli/converting' ) _UpperCAmelCase = tfds_path _UpperCAmelCase = datasets_directory def lowerCamelCase_ ( self ) -> Optional[Any]: if os.path.isdir(self._tfds_path ): _UpperCAmelCase = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): _UpperCAmelCase = os.path.dirname(self._tfds_path ) else: raise ValueError('--tfds_path is neither a directory nor a file. Please check path.' ) _UpperCAmelCase = os.path.abspath(self._datasets_directory ) self._logger.info(f'Converting datasets from {abs_tfds_path} to {abs_datasets_path}' ) _UpperCAmelCase = [] _UpperCAmelCase = [] _UpperCAmelCase = {} if os.path.isdir(self._tfds_path ): _UpperCAmelCase = os.listdir(snake_case ) else: _UpperCAmelCase = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'Looking at file {f_name}' ) _UpperCAmelCase = os.path.join(snake_case , snake_case ) _UpperCAmelCase = os.path.join(snake_case , snake_case ) if not os.path.isfile(snake_case ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('Skipping file' ) continue with open(snake_case , encoding='utf-8' ) as f: _UpperCAmelCase = f.readlines() _UpperCAmelCase = [] _UpperCAmelCase = False _UpperCAmelCase = False _UpperCAmelCase = [] for line in lines: _UpperCAmelCase = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: _UpperCAmelCase = 'import datasets\n' elif "import tensorflow" in out_line: # order is important here _UpperCAmelCase = '' continue elif "from absl import logging" in out_line: _UpperCAmelCase = 'from datasets import logging\n' elif "getLogger" in out_line: _UpperCAmelCase = out_line.replace('getLogger' , 'get_logger' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): _UpperCAmelCase = True _UpperCAmelCase = list(filter(lambda snake_case : e in out_line , snake_case ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(snake_case ) + '\n' ) out_lines.append(snake_case ) out_lines.append(snake_case ) continue else: for pattern, replacement in TO_CONVERT: _UpperCAmelCase = re.sub(snake_case , snake_case , snake_case ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: _UpperCAmelCase = re.match(r'from\stensorflow_datasets.*import\s([^\.\r\n]+)' , snake_case ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(',' ) ) _UpperCAmelCase = 'from . import ' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'Error converting {out_line.strip()}' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: _UpperCAmelCase = True out_lines.append(snake_case ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset _UpperCAmelCase = f_name.replace('.py' , '' ) _UpperCAmelCase = os.path.join(snake_case , snake_case ) _UpperCAmelCase = os.path.join(snake_case , snake_case ) os.makedirs(snake_case , exist_ok=snake_case ) self._logger.info(f'Adding directory {output_dir}' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(snake_case ) if needs_manual_update: with_manual_update.append(snake_case ) with open(snake_case , 'w' , encoding='utf-8' ) as f: f.writelines(snake_case ) self._logger.info(f'Converted in {output_file}' ) for utils_file in utils_files: try: _UpperCAmelCase = os.path.basename(snake_case ) _UpperCAmelCase = imports_to_builder_map[f_name.replace('.py' , '' )] self._logger.info(f'Moving {dest_folder} to {utils_file}' ) shutil.copy(snake_case , snake_case ) except KeyError: self._logger.error(f'Cannot find destination folder for {utils_file}. Please copy manually.' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.' )
24
"""simple docstring""" from __future__ import annotations from cmath import sqrt def UpperCAmelCase ( A : int , A : int , A : int ): '''simple docstring''' if a == 0: raise ValueError('Coefficient \'a\' must not be zero.' ) _UpperCAmelCase = b * b - 4 * a * c _UpperCAmelCase = (-b + sqrt(A )) / (2 * a) _UpperCAmelCase = (-b - sqrt(A )) / (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 UpperCAmelCase ( ): '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = quadratic_roots(a=5 , b=6 , c=1 ) print(f'The solutions are: {solutiona} and {solutiona}' ) if __name__ == "__main__": main()
24
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='session') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = datasets.Features( { 'tokens': datasets.Sequence(datasets.Value('string')), 'labels': datasets.Sequence(datasets.ClassLabel(names=['negative', 'positive'])), 'answers': datasets.Sequence( { 'text': datasets.Value('string'), 'answer_start': datasets.Value('int32'), }), 'id': datasets.Value('int64'), }) SCREAMING_SNAKE_CASE = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(_UpperCAmelCase)), } , features=_UpperCAmelCase , ) return dataset @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'file.arrow') dataset.map(cache_file_name=_UpperCAmelCase) return filename # FILE_CONTENT + files a_ : Tuple = '\\n Text data.\n Second line of data.' @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt' SCREAMING_SNAKE_CASE = FILE_CONTENT with open(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase) return filename @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): import bza SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt.bz2' SCREAMING_SNAKE_CASE = bytes(_UpperCAmelCase , 'utf-8') with bza.open(_UpperCAmelCase , 'wb') as f: f.write(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'file.txt.gz') SCREAMING_SNAKE_CASE = bytes(_UpperCAmelCase , 'utf-8') with gzip.open(_UpperCAmelCase , 'wb') as f: f.write(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): if datasets.config.LZ4_AVAILABLE: import lza.frame SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt.lz4' SCREAMING_SNAKE_CASE = bytes(_UpperCAmelCase , 'utf-8') with lza.frame.open(_UpperCAmelCase , 'wb') as f: f.write(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if datasets.config.PY7ZR_AVAILABLE: import pyazr SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt.7z' with pyazr.SevenZipFile(_UpperCAmelCase , 'w') as archive: archive.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): import tarfile SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt.tar' with tarfile.TarFile(_UpperCAmelCase , 'w') as f: f.add(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): import lzma SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt.xz' SCREAMING_SNAKE_CASE = bytes(_UpperCAmelCase , 'utf-8') with lzma.open(_UpperCAmelCase , 'wb') as f: f.write(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): import zipfile SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.txt.zst' SCREAMING_SNAKE_CASE = bytes(_UpperCAmelCase , 'utf-8') with zstd.open(_UpperCAmelCase , 'wb') as f: f.write(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'file.xml' SCREAMING_SNAKE_CASE = textwrap.dedent( '\\n <?xml version="1.0" encoding="UTF-8" ?>\n <tmx version="1.4">\n <header segtype="sentence" srclang="ca" />\n <body>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>') with open(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase) return filename a_ : Tuple = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] a_ : Any = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] a_ : List[Any] = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } a_ : Dict = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] a_ : List[Any] = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope='session') def lowerCamelCase__ (): return DATA_DICT_OF_LISTS @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = datasets.Dataset.from_dict(_UpperCAmelCase) SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.arrow') dataset.map(cache_file_name=_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.sqlite') with contextlib.closing(sqlitea.connect(_UpperCAmelCase)) as con: SCREAMING_SNAKE_CASE = con.cursor() cur.execute('CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)') for item in DATA: cur.execute('INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)' , tuple(item.values())) con.commit() return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.csv') with open(_UpperCAmelCase , 'w' , newline='') as f: SCREAMING_SNAKE_CASE = csv.DictWriter(_UpperCAmelCase , fieldnames=['col_1', 'col_2', 'col_3']) writer.writeheader() for item in DATA: writer.writerow(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset2.csv') with open(_UpperCAmelCase , 'w' , newline='') as f: SCREAMING_SNAKE_CASE = csv.DictWriter(_UpperCAmelCase , fieldnames=['col_1', 'col_2', 'col_3']) writer.writeheader() for item in DATA: writer.writerow(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): import bza SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.csv.bz2' with open(_UpperCAmelCase , 'rb') as f: SCREAMING_SNAKE_CASE = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(_UpperCAmelCase , 'wb') as f: f.write(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.csv.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.csv.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.basename(csv_path.replace('.csv' , '.CSV'))) f.write(_UpperCAmelCase , arcname=os.path.basename(csva_path.replace('.csv' , '.CSV'))) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(_UpperCAmelCase))) f.write(_UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(_UpperCAmelCase))) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.parquet') SCREAMING_SNAKE_CASE = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), }) with open(_UpperCAmelCase , 'wb') as f: SCREAMING_SNAKE_CASE = pq.ParquetWriter(_UpperCAmelCase , schema=_UpperCAmelCase) SCREAMING_SNAKE_CASE = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(_UpperCAmelCase))] for k in DATA[0]} , schema=_UpperCAmelCase) writer.write_table(_UpperCAmelCase) writer.close() return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.json') SCREAMING_SNAKE_CASE = {'data': DATA} with open(_UpperCAmelCase , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.json') SCREAMING_SNAKE_CASE = {'data': DATA_DICT_OF_LISTS} with open(_UpperCAmelCase , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.jsonl') with open(_UpperCAmelCase , 'w') as f: for item in DATA: f.write(json.dumps(_UpperCAmelCase) + '\n') return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset2.jsonl') with open(_UpperCAmelCase , 'w') as f: for item in DATA: f.write(json.dumps(_UpperCAmelCase) + '\n') return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset_312.jsonl') with open(_UpperCAmelCase , 'w') as f: for item in DATA_312: f.write(json.dumps(_UpperCAmelCase) + '\n') return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset-str.jsonl') with open(_UpperCAmelCase , 'w') as f: for item in DATA_STR: f.write(json.dumps(_UpperCAmelCase) + '\n') return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.txt.gz') with open(_UpperCAmelCase , 'rb') as orig_file: with gzip.open(_UpperCAmelCase , 'wb') as zipped_file: zipped_file.writelines(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.jsonl.gz') with open(_UpperCAmelCase , 'rb') as orig_file: with gzip.open(_UpperCAmelCase , 'wb') as zipped_file: zipped_file.writelines(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.jsonl.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.join('nested' , os.path.basename(_UpperCAmelCase))) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(_UpperCAmelCase))) f.write(_UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(_UpperCAmelCase))) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.jsonl.tar' with tarfile.TarFile(_UpperCAmelCase , 'w') as f: f.add(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) f.add(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset_nested.jsonl.tar' with tarfile.TarFile(_UpperCAmelCase , 'w') as f: f.add(_UpperCAmelCase , arcname=os.path.join('nested' , os.path.basename(_UpperCAmelCase))) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = ['0', '1', '2', '3'] SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset.txt') with open(_UpperCAmelCase , 'w') as f: for item in data: f.write(item + '\n') return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = ['0', '1', '2', '3'] SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset2.txt') with open(_UpperCAmelCase , 'w') as f: for item in data: f.write(item + '\n') return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = ['0', '1', '2', '3'] SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.abc' with open(_UpperCAmelCase , 'w') as f: for item in data: f.write(item + '\n') return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.text.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset_with_dir.text.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(_UpperCAmelCase))) f.write(_UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(_UpperCAmelCase))) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.ext.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.basename('unsupported.ext')) f.write(_UpperCAmelCase , arcname=os.path.basename('unsupported_2.ext')) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third']) SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp('data') / 'dataset_with_unicode_new_lines.txt') with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: f.write(_UpperCAmelCase) return path @pytest.fixture(scope='session') def lowerCamelCase__ (): return os.path.join('tests' , 'features' , 'data' , 'test_image_rgb.jpg') @pytest.fixture(scope='session') def lowerCamelCase__ (): return os.path.join('tests' , 'features' , 'data' , 'test_audio_44100.wav') @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data') / 'dataset.img.zip' with zipfile.ZipFile(_UpperCAmelCase , 'w') as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase)) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase).replace('.jpg' , '2.jpg')) return path @pytest.fixture(scope='session') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('data_dir') (data_dir / "subdir").mkdir() with open(data_dir / 'subdir' / 'train.txt' , 'w') as f: f.write('foo\n' * 10) with open(data_dir / 'subdir' / 'test.txt' , 'w') as f: f.write('bar\n' * 10) # hidden file with open(data_dir / 'subdir' / '.test.txt' , 'w') as f: f.write('bar\n' * 10) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '.subdir' / 'train.txt' , 'w') as f: f.write('foo\n' * 10) with open(data_dir / '.subdir' / 'test.txt' , 'w') as f: f.write('bar\n' * 10) return data_dir
73
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
1
"""simple docstring""" import pytest _lowerCAmelCase = """__dummy_dataset1__""" _lowerCAmelCase = """ import json import os import datasets REPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\" URLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \"validation\": REPO_URL + \"wikiann-bn-validation.jsonl\"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { \"tokens\": datasets.Sequence(datasets.Value(\"string\")), \"ner_tags\": datasets.Sequence( datasets.features.ClassLabel( names=[ \"O\", \"B-PER\", \"I-PER\", \"B-ORG\", \"I-ORG\", \"B-LOC\", \"I-LOC\", ] ) ), \"langs\": datasets.Sequence(datasets.Value(\"string\")), \"spans\": datasets.Sequence(datasets.Value(\"string\")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={\"filepath\": dl_path[\"train\"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={\"filepath\": dl_path[\"validation\"]}), ] def _generate_examples(self, filepath): with open(filepath, \"r\", encoding=\"utf-8\") as f: for i, line in enumerate(f): yield i, json.loads(line) """ @pytest.fixture def lowerCamelCase__ ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def lowerCamelCase__ ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Optional[int] = dataset_loading_script_name _lowerCAmelCase : Union[str, Any] = tmp_path / 'datasets' / script_name script_dir.mkdir(parents=_lowerCamelCase ) _lowerCAmelCase : Any = script_dir / f"""{script_name}.py""" with open(_lowerCamelCase , 'w' ) as f: f.write(_lowerCamelCase ) return str(_lowerCamelCase )
16
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( a__ , unittest.TestCase ): _UpperCAmelCase = DanceDiffusionPipeline _UpperCAmelCase = UNCONDITIONAL_AUDIO_GENERATION_PARAMS _UpperCAmelCase = PipelineTesterMixin.required_optional_params - { "callback", "latents", "callback_steps", "output_type", "num_images_per_prompt", } _UpperCAmelCase = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS _UpperCAmelCase = False _UpperCAmelCase = False def __lowerCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = UNetaDModel( block_out_channels=(32, 32, 64) ,extra_in_channels=16 ,sample_size=512 ,sample_rate=1_6000 ,in_channels=2 ,out_channels=2 ,flip_sin_to_cos=_A ,use_timestep_embedding=_A ,time_embedding_type='fourier' ,mid_block_type='UNetMidBlock1D' ,down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D') ,up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip') ,) _lowerCAmelCase : int = IPNDMScheduler() _lowerCAmelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def __lowerCamelCase ( self ,_A ,_A=0 ): '''simple docstring''' if str(_A ).startswith('mps' ): _lowerCAmelCase : str = torch.manual_seed(_A ) else: _lowerCAmelCase : Optional[Any] = torch.Generator(device=_A ).manual_seed(_A ) _lowerCAmelCase : int = { 'batch_size': 1, 'generator': generator, 'num_inference_steps': 4, } return inputs def __lowerCamelCase ( self ): '''simple docstring''' _lowerCAmelCase : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator _lowerCAmelCase : int = self.get_dummy_components() _lowerCAmelCase : Optional[Any] = DanceDiffusionPipeline(**_A ) _lowerCAmelCase : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) _lowerCAmelCase : Union[str, Any] = self.get_dummy_inputs(_A ) _lowerCAmelCase : List[str] = pipe(**_A ) _lowerCAmelCase : List[Any] = output.audios _lowerCAmelCase : List[str] = audio[0, -3:, -3:] assert audio.shape == (1, 2, components["unet"].sample_size) _lowerCAmelCase : Optional[Any] = np.array([-0.7_2_6_5, 1.0_0_0_0, -0.8_3_8_8, 0.1_1_7_5, 0.9_4_9_8, -1.0_0_0_0] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def __lowerCamelCase ( self ): '''simple docstring''' return super().test_save_load_local() @skip_mps def __lowerCamelCase ( self ): '''simple docstring''' return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) @skip_mps def __lowerCamelCase ( self ): '''simple docstring''' return super().test_save_load_optional_components() @skip_mps def __lowerCamelCase ( self ): '''simple docstring''' return super().test_attention_slicing_forward_pass() def __lowerCamelCase ( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def __lowerCamelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): '''simple docstring''' _lowerCAmelCase : List[Any] = torch_device _lowerCAmelCase : int = DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k' ) _lowerCAmelCase : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) _lowerCAmelCase : Optional[int] = torch.manual_seed(0 ) _lowerCAmelCase : str = pipe(generator=_A ,num_inference_steps=100 ,audio_length_in_s=4.0_9_6 ) _lowerCAmelCase : str = output.audios _lowerCAmelCase : List[str] = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) _lowerCAmelCase : Union[str, Any] = np.array([-0.0_1_9_2, -0.0_2_3_1, -0.0_3_1_8, -0.0_0_5_9, 0.0_0_0_2, -0.0_0_2_0] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ): '''simple docstring''' _lowerCAmelCase : str = torch_device _lowerCAmelCase : Tuple = DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k' ,torch_dtype=torch.floataa ) _lowerCAmelCase : Optional[int] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) _lowerCAmelCase : Union[str, Any] = torch.manual_seed(0 ) _lowerCAmelCase : Optional[int] = pipe(generator=_A ,num_inference_steps=100 ,audio_length_in_s=4.0_9_6 ) _lowerCAmelCase : Union[str, Any] = output.audios _lowerCAmelCase : int = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) _lowerCAmelCase : List[str] = np.array([-0.0_3_6_7, -0.0_4_8_8, -0.0_7_7_1, -0.0_5_2_5, -0.0_4_4_4, -0.0_3_4_1] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1E-2
16
1
import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class _UpperCAmelCase : '''simple docstring''' def __init__( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[str, Any]=13 , UpperCamelCase__ : Tuple=7 , UpperCamelCase__ : Dict=6 , UpperCamelCase__ : Optional[int]=17 , UpperCamelCase__ : Optional[int]=23 , UpperCamelCase__ : List[Any]=11 , UpperCamelCase__ : Optional[Any]=True , ): A = parent A = batch_size A = seq_length A = act_dim A = state_dim A = hidden_size A = max_length A = is_training def UpperCamelCase ( self : str ): A = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) A = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) A = floats_tensor((self.batch_size, self.seq_length, 1) ) A = floats_tensor((self.batch_size, self.seq_length, 1) ) A = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) A = random_attention_mask((self.batch_size, self.seq_length) ) A = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def UpperCamelCase ( self : Any ): return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def UpperCamelCase ( self : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : int , ): A = DecisionTransformerModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() A = model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def UpperCamelCase ( self : str ): A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = { 'states': states, 'actions': actions, 'rewards': rewards, 'returns_to_go': returns_to_go, 'timesteps': timesteps, 'attention_mask': attention_mask, } return config, inputs_dict @require_torch class _UpperCAmelCase ( __lowercase , __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = (DecisionTransformerModel,) if is_torch_available() else () SCREAMING_SNAKE_CASE : int = () SCREAMING_SNAKE_CASE : Union[str, Any] = {'''feature-extraction''': DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids SCREAMING_SNAKE_CASE : str = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features SCREAMING_SNAKE_CASE : List[str] = False SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : str = False SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : int = False SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : Tuple = False SCREAMING_SNAKE_CASE : Any = False SCREAMING_SNAKE_CASE : str = False def UpperCamelCase ( self : Union[str, Any] ): A = DecisionTransformerModelTester(self ) A = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def UpperCamelCase ( self : Dict ): self.config_tester.run_common_tests() def UpperCamelCase ( self : Dict ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) @slow def UpperCamelCase ( self : List[Any] ): for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = DecisionTransformerModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def UpperCamelCase ( self : Dict ): A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(UpperCamelCase__ ) A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A = [*signature.parameters.keys()] A = [ 'states', 'actions', 'rewards', 'returns_to_go', 'timesteps', 'attention_mask', ] self.assertListEqual(arg_names[: len(UpperCamelCase__ )] , UpperCamelCase__ ) @require_torch class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase ( self : List[str] ): A = 2 # number of steps of autoregressive prediction we will perform A = 10 # defined by the RL environment, may be normalized A = DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-expert' ) A = model.to(UpperCamelCase__ ) A = model.config torch.manual_seed(0 ) A = torch.randn(1 , 1 , config.state_dim ).to(device=UpperCamelCase__ , dtype=torch.floataa ) # env.reset() A = torch.tensor( [[0.242_793, -0.28_693_074, 0.8_742_613], [0.67_815_274, -0.08_101_085, -0.12_952_147]] , device=UpperCamelCase__ ) A = torch.tensor(UpperCamelCase__ , device=UpperCamelCase__ , dtype=torch.floataa ).reshape(1 , 1 , 1 ) A = state A = torch.zeros(1 , 0 , config.act_dim , device=UpperCamelCase__ , dtype=torch.floataa ) A = torch.zeros(1 , 0 , device=UpperCamelCase__ , dtype=torch.floataa ) A = torch.tensor(0 , device=UpperCamelCase__ , dtype=torch.long ).reshape(1 , 1 ) for step in range(UpperCamelCase__ ): A = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=UpperCamelCase__ )] , dim=1 ) A = torch.cat([rewards, torch.zeros(1 , 1 , device=UpperCamelCase__ )] , dim=1 ) A = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): A , A , A = model( states=UpperCamelCase__ , actions=UpperCamelCase__ , rewards=UpperCamelCase__ , returns_to_go=UpperCamelCase__ , timesteps=UpperCamelCase__ , attention_mask=UpperCamelCase__ , return_dict=UpperCamelCase__ , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1e-4 ) ) A , A , A , A = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=UpperCamelCase__ , dtype=torch.floataa ), 1.0, False, {}, ) A = action_pred[0, -1] A = torch.cat([states, state] , dim=1 ) A = returns_to_go[0, -1] - reward A = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) A = torch.cat( [timesteps, torch.ones((1, 1) , device=UpperCamelCase__ , dtype=torch.long ) * (step + 1)] , dim=1 )
699
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] , UpperCamelCase__ : Collection[float] | None = None ): if components is None: A = [] A = list(UpperCamelCase__ ) def __len__( self : List[Any] ): return len(self.__components ) def __str__( self : str ): return "(" + ",".join(map(UpperCamelCase__ , self.__components ) ) + ")" def __add__( self : str , UpperCamelCase__ : Vector ): A = len(self ) if size == len(UpperCamelCase__ ): A = [self.__components[i] + other.component(UpperCamelCase__ ) for i in range(UpperCamelCase__ )] return Vector(UpperCamelCase__ ) else: raise Exception('must have the same size' ) def __sub__( self : Dict , UpperCamelCase__ : Vector ): A = len(self ) if size == len(UpperCamelCase__ ): A = [self.__components[i] - other.component(UpperCamelCase__ ) for i in range(UpperCamelCase__ )] return Vector(UpperCamelCase__ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self : Tuple , UpperCamelCase__ : float ): ... @overload def __mul__( self : Dict , UpperCamelCase__ : Vector ): ... def __mul__( self : Union[str, Any] , UpperCamelCase__ : float | Vector ): if isinstance(UpperCamelCase__ , (float, int) ): A = [c * other for c in self.__components] return Vector(UpperCamelCase__ ) elif isinstance(UpperCamelCase__ , UpperCamelCase__ ) and len(self ) == len(UpperCamelCase__ ): A = len(self ) A = [self.__components[i] * other.component(UpperCamelCase__ ) for i in range(UpperCamelCase__ )] return sum(UpperCamelCase__ ) else: # error case raise Exception('invalid operand!' ) def UpperCamelCase ( self : Union[str, Any] ): return Vector(self.__components ) def UpperCamelCase ( self : Optional[Any] , UpperCamelCase__ : int ): if isinstance(UpperCamelCase__ , UpperCamelCase__ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCamelCase ( self : Any , UpperCamelCase__ : int , UpperCamelCase__ : float ): assert -len(self.__components ) <= pos < len(self.__components ) A = value def UpperCamelCase ( self : str ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) A = [c**2 for c in self.__components] return math.sqrt(sum(UpperCamelCase__ ) ) def UpperCamelCase ( self : Any , UpperCamelCase__ : Vector , UpperCamelCase__ : bool = False ): A = self * other A = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def __UpperCamelCase (lowerCAmelCase : int ) -> Vector: assert isinstance(lowerCAmelCase, lowerCAmelCase ) return Vector([0] * dimension ) def __UpperCamelCase (lowerCAmelCase : int, lowerCAmelCase : int ) -> Vector: assert isinstance(lowerCAmelCase, lowerCAmelCase ) and (isinstance(lowerCAmelCase, lowerCAmelCase )) A = [0] * dimension A = 1 return Vector(lowerCAmelCase ) def __UpperCamelCase (lowerCAmelCase : float, lowerCAmelCase : Vector, lowerCAmelCase : Vector ) -> Vector: assert ( isinstance(lowerCAmelCase, lowerCAmelCase ) and isinstance(lowerCAmelCase, lowerCAmelCase ) and (isinstance(lowerCAmelCase, (int, float) )) ) return x * scalar + y def __UpperCamelCase (lowerCAmelCase : int, lowerCAmelCase : int, lowerCAmelCase : int ) -> Vector: random.seed(lowerCAmelCase ) A = [random.randint(lowerCAmelCase, lowerCAmelCase ) for _ in range(lowerCAmelCase )] return Vector(lowerCAmelCase ) class _UpperCAmelCase : '''simple docstring''' def __init__( self : List[str] , UpperCamelCase__ : list[list[float]] , UpperCamelCase__ : int , UpperCamelCase__ : int ): A = matrix A = w A = h def __str__( self : int ): A = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : Optional[Any] , UpperCamelCase__ : Matrix ): if self.__width == other.width() and self.__height == other.height(): A = [] for i in range(self.__height ): A = [ self.__matrix[i][j] + other.component(UpperCamelCase__ , UpperCamelCase__ ) for j in range(self.__width ) ] matrix.append(UpperCamelCase__ ) return Matrix(UpperCamelCase__ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self : Dict , UpperCamelCase__ : Matrix ): if self.__width == other.width() and self.__height == other.height(): A = [] for i in range(self.__height ): A = [ self.__matrix[i][j] - other.component(UpperCamelCase__ , UpperCamelCase__ ) for j in range(self.__width ) ] matrix.append(UpperCamelCase__ ) return Matrix(UpperCamelCase__ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self : int , UpperCamelCase__ : float ): ... @overload def __mul__( self : Union[str, Any] , UpperCamelCase__ : Vector ): ... def __mul__( self : Tuple , UpperCamelCase__ : float | Vector ): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # matrix-vector if len(UpperCamelCase__ ) == self.__width: A = zero_vector(self.__height ) for i in range(self.__height ): A = [ self.__matrix[i][j] * other.component(UpperCamelCase__ ) for j in range(self.__width ) ] ans.change_component(UpperCamelCase__ , sum(UpperCamelCase__ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(UpperCamelCase__ , (int, float) ): # matrix-scalar A = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(UpperCamelCase__ , self.__width , self.__height ) return None def UpperCamelCase ( self : Optional[int] ): return self.__height def UpperCamelCase ( self : List[Any] ): return self.__width def UpperCamelCase ( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : int ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCamelCase ( self : str , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : float ): if 0 <= x < self.__height and 0 <= y < self.__width: A = value else: raise Exception('change_component: indices out of bounds' ) def UpperCamelCase ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ): if self.__height != self.__width: raise Exception('Matrix is not square' ) A = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(UpperCamelCase__ ) ): A = minor[i][:y] + minor[i][y + 1 :] return Matrix(UpperCamelCase__ , self.__width - 1 , self.__height - 1 ).determinant() def UpperCamelCase ( self : str , UpperCamelCase__ : int , UpperCamelCase__ : int ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(UpperCamelCase__ , UpperCamelCase__ ) else: raise Exception('Indices out of bounds' ) def UpperCamelCase ( self : Tuple ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: A = [ self.__matrix[0][y] * self.cofactor(0 , UpperCamelCase__ ) for y in range(self.__width ) ] return sum(UpperCamelCase__ ) def __UpperCamelCase (lowerCAmelCase : int ) -> Matrix: A = [[0] * n for _ in range(lowerCAmelCase )] return Matrix(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ) def __UpperCamelCase (lowerCAmelCase : int, lowerCAmelCase : int, lowerCAmelCase : int, lowerCAmelCase : int ) -> Matrix: random.seed(lowerCAmelCase ) A = [ [random.randint(lowerCAmelCase, lowerCAmelCase ) for _ in range(lowerCAmelCase )] for _ in range(lowerCAmelCase ) ] return Matrix(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase )
699
1
'''simple docstring''' import pytest __lowercase = '''__dummy_dataset1__''' __lowercase = ''' import json import os import datasets REPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/" URLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ "O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", ] ) ), "langs": datasets.Sequence(datasets.Value("string")), "spans": datasets.Sequence(datasets.Value("string")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}), ] def _generate_examples(self, filepath): with open(filepath, "r", encoding="utf-8") as f: for i, line in enumerate(f): yield i, json.loads(line) ''' @pytest.fixture def SCREAMING_SNAKE_CASE__ ( ): return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def SCREAMING_SNAKE_CASE__ ( ): return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase_ : str =dataset_loading_script_name lowerCAmelCase_ : List[str] =tmp_path / '''datasets''' / script_name script_dir.mkdir(parents=_SCREAMING_SNAKE_CASE ) lowerCAmelCase_ : Optional[int] =script_dir / f'{script_name}.py' with open(_SCREAMING_SNAKE_CASE , '''w''' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return str(_SCREAMING_SNAKE_CASE )
305
'''simple docstring''' import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 __lowercase = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 1_28, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 50, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 10, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 10, '''exponential_decay_length_penalty''': (5, 1.01), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class _snake_case ( unittest.TestCase ): """simple docstring""" @classmethod def __A ( cls : List[str] ): lowerCAmelCase_ : str =TOKEN HfFolder.save_token(UpperCamelCase_ ) @classmethod def __A ( cls : Union[str, Any] ): try: delete_repo(token=cls._token , repo_id='''test-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-config-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-config''' ) except HTTPError: pass def __A ( self : Dict ): lowerCAmelCase_ : List[Any] =BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''test-config''' , use_auth_token=self._token ) lowerCAmelCase_ : List[str] =BertConfig.from_pretrained(F'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCamelCase_ , repo_id='''test-config''' , push_to_hub=UpperCamelCase_ , use_auth_token=self._token ) lowerCAmelCase_ : List[Any] =BertConfig.from_pretrained(F'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) def __A ( self : Tuple ): lowerCAmelCase_ : Optional[int] =BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''valid_org/test-config-org''' , use_auth_token=self._token ) lowerCAmelCase_ : Union[str, Any] =BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCamelCase_ , repo_id='''valid_org/test-config-org''' , push_to_hub=UpperCamelCase_ , use_auth_token=self._token ) lowerCAmelCase_ : int =BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) def __A ( self : str ): CustomConfig.register_for_auto_class() lowerCAmelCase_ : List[str] =CustomConfig(attribute=42 ) config.push_to_hub('''test-dynamic-config''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'''AutoConfig''': '''custom_configuration.CustomConfig'''} ) lowerCAmelCase_ : Optional[int] =AutoConfig.from_pretrained(F'{USER}/test-dynamic-config' , trust_remote_code=UpperCamelCase_ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , '''CustomConfig''' ) self.assertEqual(new_config.attribute , 42 ) class _snake_case ( unittest.TestCase ): """simple docstring""" def __A ( self : Dict ): lowerCAmelCase_ : int =GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated lowerCAmelCase_ : str =c.n_embd + 1 # int lowerCAmelCase_ : Tuple =c.resid_pdrop + 1.0 # float lowerCAmelCase_ : Optional[Any] =not c.scale_attn_weights # bool lowerCAmelCase_ : Union[str, Any] =c.summary_type + '''foo''' # str c.update_from_string( F'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(UpperCamelCase_ , c.n_embd , '''mismatch for key: n_embd''' ) self.assertEqual(UpperCamelCase_ , c.resid_pdrop , '''mismatch for key: resid_pdrop''' ) self.assertEqual(UpperCamelCase_ , c.scale_attn_weights , '''mismatch for key: scale_attn_weights''' ) self.assertEqual(UpperCamelCase_ , c.summary_type , '''mismatch for key: summary_type''' ) def __A ( self : Union[str, Any] ): lowerCAmelCase_ : Union[str, Any] =PretrainedConfig() lowerCAmelCase_ : Dict =[key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( UpperCamelCase_ , ['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version'''] ) lowerCAmelCase_ : Tuple =[key for key, value in config_common_kwargs.items() if value == getattr(UpperCamelCase_ , UpperCamelCase_ )] if len(UpperCamelCase_ ) > 0: raise ValueError( '''The following keys are set with the default values in''' ''' `test_configuration_common.config_common_kwargs` pick another value for them:''' F' {", ".join(UpperCamelCase_ )}.' ) def __A ( self : Optional[int] ): with self.assertRaises(UpperCamelCase_ ): # config is in subfolder, the following should not work without specifying the subfolder lowerCAmelCase_ : str =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' ) lowerCAmelCase_ : int =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' , subfolder='''bert''' ) self.assertIsNotNone(UpperCamelCase_ ) def __A ( self : List[Any] ): # A mock response for an HTTP head request to emulate server down lowerCAmelCase_ : List[str] =mock.Mock() lowerCAmelCase_ : List[str] =500 lowerCAmelCase_ : Tuple ={} lowerCAmelCase_ : Union[str, Any] =HTTPError lowerCAmelCase_ : Dict ={} # Download this model to make sure it's in the cache. lowerCAmelCase_ : Dict =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=UpperCamelCase_ ) as mock_head: lowerCAmelCase_ : List[str] =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() def __A ( self : Dict ): # This test is for deprecated behavior and can be removed in v5 lowerCAmelCase_ : Union[str, Any] =BertConfig.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json''' ) def __A ( self : int ): lowerCAmelCase_ : Union[str, Any] =AutoConfig.from_pretrained('''bert-base-cased''' ) lowerCAmelCase_ : Tuple =['''config.4.0.0.json'''] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(UpperCamelCase_ ) lowerCAmelCase_ : str =2 json.dump(configuration.to_dict() , open(os.path.join(UpperCamelCase_ , '''config.4.0.0.json''' ) , '''w''' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 lowerCAmelCase_ : Optional[Any] =AutoConfig.from_pretrained(UpperCamelCase_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 lowerCAmelCase_ : List[Any] =['''config.42.0.0.json'''] lowerCAmelCase_ : Optional[int] =768 configuration.save_pretrained(UpperCamelCase_ ) shutil.move(os.path.join(UpperCamelCase_ , '''config.4.0.0.json''' ) , os.path.join(UpperCamelCase_ , '''config.42.0.0.json''' ) ) lowerCAmelCase_ : int =AutoConfig.from_pretrained(UpperCamelCase_ ) self.assertEqual(new_configuration.hidden_size , 768 ) def __A ( self : int ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. lowerCAmelCase_ : Dict ='''hf-internal-testing/test-two-configs''' import transformers as new_transformers lowerCAmelCase_ : Tuple ='''v4.0.0''' lowerCAmelCase_ , lowerCAmelCase_ : int =new_transformers.models.auto.AutoConfig.from_pretrained( UpperCamelCase_ , return_unused_kwargs=UpperCamelCase_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(UpperCamelCase_ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers lowerCAmelCase_ : Optional[Any] ='''v3.0.0''' lowerCAmelCase_ : List[Any] =old_transformers.models.auto.AutoConfig.from_pretrained(UpperCamelCase_ ) self.assertEqual(old_configuration.hidden_size , 768 )
305
1
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class __lowerCamelCase ( _UpperCAmelCase ): """simple docstring""" def a ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Any: with open(_UpperCAmelCase , encoding="utf-8" ) as input_file: lowerCAmelCase__ = re.compile(r"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) lowerCAmelCase__ = input_file.read() lowerCAmelCase__ = regexp.search(_UpperCAmelCase ) return match def a ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: with open(_UpperCAmelCase , encoding="utf-8" ) as input_file: lowerCAmelCase__ = re.compile(r"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) lowerCAmelCase__ = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` lowerCAmelCase__ = regexp.finditer(_UpperCAmelCase ) lowerCAmelCase__ = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def a ( self : Any ) -> Tuple: lowerCAmelCase__ = Path("./datasets" ) lowerCAmelCase__ = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_UpperCAmelCase ) ): raise AssertionError(f'open(...) must use utf-8 encoding in {dataset}' ) def a ( self : Dict ) -> int: lowerCAmelCase__ = Path("./datasets" ) lowerCAmelCase__ = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(_UpperCAmelCase ) ): raise AssertionError(f'print statement found in {dataset}. Use datasets.logger/logging instead.' )
61
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase = 1_0 , __UpperCAmelCase = 2_2 ) -> int: lowercase__: Optional[Any] = range(1 , __UpperCAmelCase ) lowercase__: Any = range(1 , __UpperCAmelCase ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(1_0, 2_2) = }''')
586
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__: Optional[int] = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__: Any = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__: Optional[int] = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__: Union[str, Any] = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys lowerCAmelCase__: Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
720
import math def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE = 0.1 ) -> int: SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : Dict = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(SCREAMING_SNAKE_CASE ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
311
0
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : str=13 , UpperCamelCase__ : Any=7 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : str=True , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : str=32 , UpperCamelCase__ : str=5 , UpperCamelCase__ : Tuple=4 , UpperCamelCase__ : Any=37 , UpperCamelCase__ : str="gelu" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : List[str]=512 , UpperCamelCase__ : List[str]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : Union[str, Any]=4 , ): A = parent A = batch_size A = seq_length A = is_training A = use_attention_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_choices def UpperCamelCase ( self : List[str] ): A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A = None if self.use_attention_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A = RoFormerConfig( 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=UpperCamelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase ( self : List[Any] ): A = self.prepare_config_and_inputs() A , A , A , A = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class _UpperCAmelCase ( __lowercase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = True SCREAMING_SNAKE_CASE : int = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase ( self : Any ): A = FlaxRoFormerModelTester(self ) @slow def UpperCamelCase ( self : Dict ): for model_class_name in self.all_model_classes: A = model_class_name.from_pretrained('junnyu/roformer_chinese_small' , from_pt=UpperCamelCase__ ) A = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCamelCase__ ) @require_flax class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase ( self : List[str] ): A = FlaxRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' ) A = jnp.array([[0, 1, 2, 3, 4, 5]] ) A = model(UpperCamelCase__ )[0] A = 50000 A = (1, 6, vocab_size) self.assertEqual(output.shape , UpperCamelCase__ ) A = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1e-4 ) )
699
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, ) _UpperCAmelCase = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "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 _UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure)
699
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/config.json"} class SCREAMING_SNAKE_CASE ( _UpperCAmelCase ): """simple docstring""" A_ = "openai-gpt" A_ = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self: Optional[int] , __A: str=4_04_78 , __A: Optional[Any]=5_12 , __A: str=7_68 , __A: List[str]=12 , __A: Tuple=12 , __A: str="gelu" , __A: Union[str, Any]=0.1 , __A: str=0.1 , __A: Dict=0.1 , __A: int=1e-5 , __A: List[str]=0.02 , __A: Dict="cls_index" , __A: List[Any]=True , __A: int=None , __A: List[str]=True , __A: List[Any]=0.1 , **__A: List[Any] , ) -> str: _A = vocab_size _A = n_positions _A = n_embd _A = n_layer _A = n_head _A = afn _A = resid_pdrop _A = embd_pdrop _A = attn_pdrop _A = layer_norm_epsilon _A = initializer_range _A = summary_type _A = summary_use_proj _A = summary_activation _A = summary_first_dropout _A = summary_proj_to_labels super().__init__(**lowercase_ )
708
import itertools import string from collections.abc import Generator, Iterable def __A ( _lowercase , _lowercase ): '''simple docstring''' _A = iter(_lowercase ) while True: _A = tuple(itertools.islice(_lowercase , _lowercase ) ) if not chunk: return yield chunk def __A ( _lowercase ): '''simple docstring''' _A = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] ) _A = '''''' if len(_lowercase ) < 2: return dirty for i in range(len(_lowercase ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(_lowercase ) & 1: clean += "X" return clean def __A ( _lowercase ): '''simple docstring''' _A = '''ABCDEFGHIKLMNOPQRSTUVWXYZ''' # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler _A = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(_lowercase ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(_lowercase ) return table def __A ( _lowercase , _lowercase ): '''simple docstring''' _A = generate_table(_lowercase ) _A = prepare_input(_lowercase ) _A = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(_lowercase , 2 ): _A ,_A = divmod(table.index(_lowercase ) , 5 ) _A ,_A = divmod(table.index(_lowercase ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def __A ( _lowercase , _lowercase ): '''simple docstring''' _A = generate_table(_lowercase ) _A = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(_lowercase , 2 ): _A ,_A = divmod(table.index(_lowercase ) , 5 ) _A ,_A = divmod(table.index(_lowercase ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
62
0
"""simple docstring""" import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument __UpperCamelCase : List[Any] = { """/attention/""": """/0/SelfAttention/""", """/self_attention/""": """/0/SelfAttention/""", """/encoder_decoder_attention/""": """/1/EncDecAttention/""", """value""": """v""", """query""": """q""", """key""": """k""", """out""": """o""", """pre_self_attention_layer_norm""": """0/layer_norm""", """pre_cross_attention_layer_norm""": """1/layer_norm""", """pre_attention_layer_norm""": """0/layer_norm""", # previously 1, but seems wrong """token_embedder""": """shared""", """encoder_norm""": """final_layer_norm""", """decoder_norm""": """final_layer_norm""", """relpos_bias/rel_embedding""": """block/0/layer/0/SelfAttention/relative_attention_bias/weight""", """router/router_weights/w/""": """router/classifier/""", """roer/roer_weights/w/""": """router/classifier/""", """logits_dense""": """lm_head""", } def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Optional[int] ): lowerCAmelCase = list(s_dict.keys() ) for key in keys: lowerCAmelCase = R".*/layers_(\d+)" lowerCAmelCase = key if re.match(_UpperCAmelCase , _UpperCAmelCase ): lowerCAmelCase = re.sub(R'layers_(\d+)' , R'block/\1/layer' , _UpperCAmelCase ) lowerCAmelCase = R"(encoder|decoder)\/" if re.match(_UpperCAmelCase , _UpperCAmelCase ): lowerCAmelCase = re.match(_UpperCAmelCase , _UpperCAmelCase ).groups() if groups[0] == "encoder": lowerCAmelCase = re.sub(R'/mlp/' , R'/1/mlp/' , _UpperCAmelCase ) lowerCAmelCase = re.sub(R'/pre_mlp_layer_norm/' , R'/1/layer_norm/' , _UpperCAmelCase ) elif groups[0] == "decoder": lowerCAmelCase = re.sub(R'/mlp/' , R'/2/mlp/' , _UpperCAmelCase ) lowerCAmelCase = re.sub(R'/pre_mlp_layer_norm/' , R'/2/layer_norm/' , _UpperCAmelCase ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: lowerCAmelCase = new_key.replace(_UpperCAmelCase , _UpperCAmelCase ) print(F'{key} -> {new_key}' ) lowerCAmelCase = s_dict.pop(_UpperCAmelCase ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: lowerCAmelCase = s_dict[ "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: lowerCAmelCase = s_dict[ "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: lowerCAmelCase = s_dict[key].shape[0] lowerCAmelCase = s_dict[key] for idx in range(_UpperCAmelCase ): lowerCAmelCase = expert_weihts[idx] print(F'{key} -> {key.replace("expert/" , "nested fstring" )}' ) s_dict.pop(_UpperCAmelCase ) return s_dict __UpperCamelCase : Dict = { """NUM_ENCODER_LAYERS""": """num_layers""", """NUM_DECODER_LAYERS""": """num_decoder_layers""", """NUM_HEADS""": """num_heads""", """HEAD_DIM""": """d_kv""", """EMBED_DIM""": """d_model""", """MLP_DIM""": """d_ff""", """NUM_SELECTED_EXPERTS""": """num_selected_experts""", """NUM_ENCODER_SPARSE_LAYERS""": """num_sparse_encoder_layers""", """NUM_DECODER_SPARSE_LAYERS""": """num_sparse_decoder_layers""", """dense.MlpBlock.activations""": """feed_forward_proj""", } def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : List[str] , _UpperCAmelCase : Optional[Any] ): import regex as re with open(_UpperCAmelCase , 'r' ) as f: lowerCAmelCase = f.read() lowerCAmelCase = re.findall(R'(.*) = ([0-9.]*)' , _UpperCAmelCase ) lowerCAmelCase = {} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": lowerCAmelCase = float(_UpperCAmelCase ) if "." in value else int(_UpperCAmelCase ) lowerCAmelCase = re.findall(R'(.*activations) = \(\'(.*)\',\)' , _UpperCAmelCase )[0] lowerCAmelCase = str(activation[1] ) lowerCAmelCase = num_experts lowerCAmelCase = SwitchTransformersConfig(**_UpperCAmelCase ) return config def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Optional[int] , _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict=None , _UpperCAmelCase : List[Any]="./" , _UpperCAmelCase : Optional[int]=8 ): print(F'Loading flax weights from : {flax_checkpoint_path}' ) lowerCAmelCase = checkpoints.load_tax_checkpoint(_UpperCAmelCase ) if gin_file is not None: lowerCAmelCase = convert_gin_to_config(_UpperCAmelCase , _UpperCAmelCase ) else: lowerCAmelCase = SwitchTransformersConfig.from_pretrained(_UpperCAmelCase ) lowerCAmelCase = SwitchTransformersForConditionalGeneration(_UpperCAmelCase ) lowerCAmelCase = flax_params["target"] lowerCAmelCase = flatten_dict(_UpperCAmelCase , sep='/' ) lowerCAmelCase = rename_keys(_UpperCAmelCase ) lowerCAmelCase = unflatten_dict(_UpperCAmelCase , sep='/' ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(_UpperCAmelCase , _UpperCAmelCase ) print(F'Save PyTorch model to {pytorch_dump_path}' ) pt_model.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": __UpperCamelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--switch_t5x_checkpoint_path''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the''' ''' model architecture. If not provided, a `gin_file` has to be provided.''' ), ) parser.add_argument( '''--gin_file''', default=None, type=str, required=False, help='''Path to the gin config file. If not provided, a `config_file` has to be passed ''', ) parser.add_argument( '''--config_name''', default=None, type=str, required=False, help='''Config name of SwitchTransformers model.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output pytorch model.''' ) parser.add_argument('''--num_experts''', default=8, type=int, required=False, help='''Number of experts''') __UpperCamelCase : Union[str, Any] = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
4
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a : Optional[Any] = { """configuration_lxmert""": ["""LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LxmertConfig"""], """tokenization_lxmert""": ["""LxmertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : List[Any] = ["""LxmertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Tuple = [ """LxmertEncoder""", """LxmertForPreTraining""", """LxmertForQuestionAnswering""", """LxmertModel""", """LxmertPreTrainedModel""", """LxmertVisualFeatureEncoder""", """LxmertXLayer""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Dict = [ """TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLxmertForPreTraining""", """TFLxmertMainLayer""", """TFLxmertModel""", """TFLxmertPreTrainedModel""", """TFLxmertVisualFeatureEncoder""", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys a : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
218
0
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} lowerCamelCase_ = { "vocab_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json" }, "merges_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt" }, } lowerCamelCase_ = {"allegro/herbert-base-cased": 5_14} lowerCamelCase_ = {} class __A( _lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = HerbertTokenizer def __init__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( A__ , A__ , tokenizer_file=A__ , cls_token=A__ , unk_token=A__ , pad_token=A__ , mask_token=A__ , sep_token=A__ , **A__ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A__ , token_ids_a=A__ , already_has_special_tokens=A__ ) if token_ids_a is None: return [1] + ([0] * len(A__ )) + [1] return [1] + ([0] * len(A__ )) + [1] + ([0] * len(A__ )) + [1] def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase__ = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
700
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
0
def lowercase ( a , a = 0 ): '''simple docstring''' SCREAMING_SNAKE_CASE_ :List[str] = length or len(a ) SCREAMING_SNAKE_CASE_ :List[str] = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: SCREAMING_SNAKE_CASE_ :int = list_data[i + 1], list_data[i] SCREAMING_SNAKE_CASE_ :List[Any] = True return list_data if not swapped else bubble_sort(a , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
631
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging A = logging.get_logger(__name__) class a__ ( __magic_name__ ): lowercase_ = ["input_features", "is_longer"] def __init__( self : List[str] , UpperCamelCase_ : Dict=64 , UpperCamelCase_ : Tuple=48000 , UpperCamelCase_ : List[Any]=480 , UpperCamelCase_ : List[str]=10 , UpperCamelCase_ : str=1024 , UpperCamelCase_ : List[str]=0.0 , UpperCamelCase_ : Optional[int]=False , UpperCamelCase_ : float = 0 , UpperCamelCase_ : float = 14000 , UpperCamelCase_ : int = None , UpperCamelCase_ : str = "fusion" , UpperCamelCase_ : str = "repeatpad" , **UpperCamelCase_ : Optional[Any] , ): """simple docstring""" super().__init__( feature_size=UpperCamelCase_ , sampling_rate=UpperCamelCase_ , padding_value=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , **UpperCamelCase_ , ) __UpperCAmelCase : Union[str, Any] = top_db __UpperCAmelCase : Optional[Any] = truncation __UpperCAmelCase : str = padding __UpperCAmelCase : int = fft_window_size __UpperCAmelCase : str = (fft_window_size >> 1) + 1 __UpperCAmelCase : List[Any] = hop_length __UpperCAmelCase : Optional[Any] = max_length_s __UpperCAmelCase : Tuple = max_length_s * sampling_rate __UpperCAmelCase : str = sampling_rate __UpperCAmelCase : int = frequency_min __UpperCAmelCase : Optional[Any] = frequency_max __UpperCAmelCase : Any = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase_ , min_frequency=UpperCamelCase_ , max_frequency=UpperCamelCase_ , sampling_rate=UpperCamelCase_ , norm=UpperCamelCase_ , mel_scale="htk" , ) __UpperCAmelCase : Any = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase_ , min_frequency=UpperCamelCase_ , max_frequency=UpperCamelCase_ , sampling_rate=UpperCamelCase_ , norm="slaney" , mel_scale="slaney" , ) def a_ ( self : Dict): """simple docstring""" __UpperCAmelCase : Dict = copy.deepcopy(self.__dict__) __UpperCAmelCase : str = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def a_ ( self : int , UpperCamelCase_ : np.array , UpperCamelCase_ : Optional[np.array] = None): """simple docstring""" __UpperCAmelCase : List[Any] = spectrogram( UpperCamelCase_ , window_function(self.fft_window_size , "hann") , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase_ , log_mel="dB" , ) return log_mel_spectrogram.T def a_ ( self : List[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int): """simple docstring""" __UpperCAmelCase : Optional[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1)) , 3) if len(ranges[1]) == 0: # if the audio is too short, we just use the first chunk __UpperCAmelCase : str = [0] if len(ranges[2]) == 0: # if the audio is too short, we just use the first chunk __UpperCAmelCase : Dict = [0] # randomly choose index for each part __UpperCAmelCase : Dict = np.random.choice(ranges[0]) __UpperCAmelCase : List[str] = np.random.choice(ranges[1]) __UpperCAmelCase : List[Any] = np.random.choice(ranges[2]) __UpperCAmelCase : List[Any] = mel[idx_front : idx_front + chunk_frames, :] __UpperCAmelCase : List[str] = mel[idx_middle : idx_middle + chunk_frames, :] __UpperCAmelCase : List[str] = mel[idx_back : idx_back + chunk_frames, :] __UpperCAmelCase : Tuple = torch.tensor(mel[None, None, :]) __UpperCAmelCase : Union[str, Any] = torch.nn.functional.interpolate( UpperCamelCase_ , size=[chunk_frames, 64] , mode="bilinear" , align_corners=UpperCamelCase_) __UpperCAmelCase : Union[str, Any] = mel_shrink[0][0].numpy() __UpperCAmelCase : Optional[int] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0) return mel_fusion def a_ ( self : Optional[Any] , UpperCamelCase_ : np.array , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any]): """simple docstring""" if waveform.shape[0] > max_length: if truncation == "rand_trunc": __UpperCAmelCase : List[str] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad __UpperCAmelCase : List[Any] = len(UpperCamelCase_) - max_length __UpperCAmelCase : int = np.random.randint(0 , overflow + 1) __UpperCAmelCase : Union[str, Any] = waveform[idx : idx + max_length] __UpperCAmelCase : Union[str, Any] = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters_slaney)[None, :] elif truncation == "fusion": __UpperCAmelCase : Any = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters) __UpperCAmelCase : Dict = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed __UpperCAmelCase : Tuple = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. __UpperCAmelCase : List[str] = np.stack([mel, mel, mel, mel] , axis=0) __UpperCAmelCase : Any = False else: __UpperCAmelCase : List[str] = self._random_mel_fusion(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_) __UpperCAmelCase : Union[str, Any] = True else: raise NotImplementedError(F"data_truncating {truncation} not implemented") else: __UpperCAmelCase : Optional[Any] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": __UpperCAmelCase : Tuple = int(max_length / len(UpperCamelCase_)) __UpperCAmelCase : List[str] = np.stack(np.tile(UpperCamelCase_ , n_repeat + 1))[:max_length] if padding == "repeatpad": __UpperCAmelCase : Union[str, Any] = int(max_length / len(UpperCamelCase_)) __UpperCAmelCase : Optional[Any] = np.stack(np.tile(UpperCamelCase_ , UpperCamelCase_)) __UpperCAmelCase : int = np.pad(UpperCamelCase_ , (0, max_length - waveform.shape[0]) , mode="constant" , constant_values=0) if truncation == "fusion": __UpperCAmelCase : Any = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters) __UpperCAmelCase : List[Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0) else: __UpperCAmelCase : Optional[int] = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters_slaney)[None, :] return input_mel, longer def __call__( self : Dict , UpperCamelCase_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase_ : str = None , UpperCamelCase_ : Optional[str] = None , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : Optional[Union[str, TensorType]] = None , **UpperCamelCase_ : Any , ): """simple docstring""" __UpperCAmelCase : int = truncation if truncation is not None else self.truncation __UpperCAmelCase : Optional[Any] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a" F" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input" F" was sampled with {self.sampling_rate} and not {sampling_rate}.") else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug.") __UpperCAmelCase : List[str] = isinstance(UpperCamelCase_ , np.ndarray) and len(raw_speech.shape) > 1 if is_batched_numpy and len(raw_speech.shape) > 2: raise ValueError(F"Only mono-channel audio is supported for input to {self}") __UpperCAmelCase : str = is_batched_numpy or ( isinstance(UpperCamelCase_ , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list))) ) if is_batched: __UpperCAmelCase : Dict = [np.asarray(UpperCamelCase_ , dtype=np.floataa) for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase_ , np.ndarray): __UpperCAmelCase : Tuple = np.asarray(UpperCamelCase_ , dtype=np.floataa) elif isinstance(UpperCamelCase_ , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa): __UpperCAmelCase : Optional[int] = raw_speech.astype(np.floataa) # always return batch if not is_batched: __UpperCAmelCase : int = [np.asarray(UpperCamelCase_)] # convert to mel spectrogram, truncate and pad if needed. __UpperCAmelCase : Optional[int] = [ self._get_input_mel(UpperCamelCase_ , max_length if max_length else self.nb_max_samples , UpperCamelCase_ , UpperCamelCase_) for waveform in raw_speech ] __UpperCAmelCase : Tuple = [] __UpperCAmelCase : List[Any] = [] for mel, longer in padded_inputs: input_mel.append(UpperCamelCase_) is_longer.append(UpperCamelCase_) if truncation == "fusion" and sum(UpperCamelCase_) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer __UpperCAmelCase : Any = np.random.randint(0 , len(UpperCamelCase_)) __UpperCAmelCase : Optional[int] = True if isinstance(input_mel[0] , UpperCamelCase_): __UpperCAmelCase : Tuple = [np.asarray(UpperCamelCase_ , dtype=np.floataa) for feature in input_mel] # is_longer is a list of bool __UpperCAmelCase : List[str] = [[longer] for longer in is_longer] __UpperCAmelCase : Optional[int] = {"input_features": input_mel, "is_longer": is_longer} __UpperCAmelCase : Optional[int] = BatchFeature(UpperCamelCase_) if return_tensors is not None: __UpperCAmelCase : Any = input_features.convert_to_tensors(UpperCamelCase_) return input_features
77
0
import math def _snake_case ( SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" _lowerCAmelCase : str = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(SCREAMING_SNAKE_CASE ) def _snake_case ( SCREAMING_SNAKE_CASE = 1 / 12345 ) -> int: """simple docstring""" _lowerCAmelCase : Optional[int] = 0 _lowerCAmelCase : Union[str, Any] = 0 _lowerCAmelCase : str = 3 while True: _lowerCAmelCase : Dict = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(SCREAMING_SNAKE_CASE ): _lowerCAmelCase : List[str] = int(SCREAMING_SNAKE_CASE ) total_partitions += 1 if check_partition_perfect(SCREAMING_SNAKE_CASE ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(SCREAMING_SNAKE_CASE ) integer += 1 if __name__ == "__main__": print(f'''{solution() = }''')
710
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 __UpperCAmelCase = logging.get_logger(__name__) class A__ ( A ): """simple docstring""" _lowercase : List[Any] = ['''pixel_values'''] def __init__( self : Tuple , A_ : bool = True , A_ : Dict[str, int] = None , A_ : PILImageResampling = PILImageResampling.BILINEAR , A_ : bool = True , A_ : Union[int, float] = 1 / 2_5_5 , A_ : bool = True , A_ : Dict[str, int] = None , A_ : bool = True , **A_ : List[Any] , ): '''simple docstring''' super().__init__(**A_ ) _lowerCAmelCase : Optional[int] = size if size is not None else {"shortest_edge": 2_2_4} _lowerCAmelCase : Optional[int] = get_size_dict(A_ , default_to_square=A_ ) _lowerCAmelCase : Any = crop_size if crop_size is not None else {"height": 2_5_6, "width": 2_5_6} _lowerCAmelCase : str = get_size_dict(A_ , param_name="crop_size" ) _lowerCAmelCase : Any = do_resize _lowerCAmelCase : Optional[Any] = size _lowerCAmelCase : str = resample _lowerCAmelCase : Optional[Any] = do_rescale _lowerCAmelCase : Dict = rescale_factor _lowerCAmelCase : Any = do_center_crop _lowerCAmelCase : List[Any] = crop_size _lowerCAmelCase : List[Any] = do_flip_channel_order def __magic_name__ ( self : Tuple , A_ : np.ndarray , A_ : Dict[str, int] , A_ : PILImageResampling = PIL.Image.BILINEAR , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : Dict , ): '''simple docstring''' _lowerCAmelCase : Any = get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(F'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}''' ) _lowerCAmelCase : Union[str, Any] = get_resize_output_image_size(A_ , size=size["shortest_edge"] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def __magic_name__ ( self : Union[str, Any] , A_ : np.ndarray , A_ : Dict[str, int] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : List[str] , ): '''simple docstring''' _lowerCAmelCase : str = get_size_dict(A_ ) 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(A_ , size=(size["height"], size["width"]) , data_format=A_ , **A_ ) def __magic_name__ ( self : Tuple , A_ : np.ndarray , A_ : Union[int, float] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : Any , ): '''simple docstring''' return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def __magic_name__ ( self : Optional[Any] , A_ : np.ndarray , A_ : Optional[Union[str, ChannelDimension]] = None ): '''simple docstring''' return flip_channel_order(A_ , data_format=A_ ) def __magic_name__ ( self : List[Any] , A_ : ImageInput , A_ : bool = None , A_ : Dict[str, int] = None , A_ : PILImageResampling = None , A_ : bool = None , A_ : float = None , A_ : bool = None , A_ : Dict[str, int] = None , A_ : bool = None , A_ : Optional[Union[str, TensorType]] = None , A_ : ChannelDimension = ChannelDimension.FIRST , **A_ : Tuple , ): '''simple docstring''' _lowerCAmelCase : str = do_resize if do_resize is not None else self.do_resize _lowerCAmelCase : Dict = resample if resample is not None else self.resample _lowerCAmelCase : str = do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase : Tuple = do_center_crop if do_center_crop is not None else self.do_center_crop _lowerCAmelCase : str = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) _lowerCAmelCase : str = size if size is not None else self.size _lowerCAmelCase : str = get_size_dict(A_ , default_to_square=A_ ) _lowerCAmelCase : Optional[Any] = crop_size if crop_size is not None else self.crop_size _lowerCAmelCase : List[str] = get_size_dict(A_ , param_name="crop_size" ) _lowerCAmelCase : Dict = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_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. _lowerCAmelCase : Optional[int] = [to_numpy_array(A_ ) for image in images] if do_resize: _lowerCAmelCase : Any = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: _lowerCAmelCase : Tuple = [self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: _lowerCAmelCase : Any = [self.rescale(image=A_ , scale=A_ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: _lowerCAmelCase : Dict = [self.flip_channel_order(image=A_ ) for image in images] _lowerCAmelCase : Optional[Any] = [to_channel_dimension_format(A_ , A_ ) for image in images] _lowerCAmelCase : Tuple = {"pixel_values": images} return BatchFeature(data=A_ , tensor_type=A_ ) def __magic_name__ ( self : List[Any] , A_ : Union[str, Any] , A_ : List[Tuple] = None ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(A_ ): _lowerCAmelCase : Dict = target_sizes.numpy() _lowerCAmelCase : List[Any] = [] for idx in range(len(A_ ) ): _lowerCAmelCase : Tuple = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=A_ ) _lowerCAmelCase : Any = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: _lowerCAmelCase : Tuple = logits.argmax(dim=1 ) _lowerCAmelCase : Tuple = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
503
0
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __UpperCamelCase ( unittest.TestCase ): def UpperCamelCase( self ): _UpperCAmelCase = '''ylacombe/bark-small''' _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = '''en_speaker_1''' _UpperCAmelCase = '''This is a test string''' _UpperCAmelCase = '''speaker_embeddings_path.json''' _UpperCAmelCase = '''speaker_embeddings''' def UpperCamelCase( self , **_UpperCamelCase ): return AutoTokenizer.from_pretrained(self.checkpoint , **_UpperCamelCase ) def UpperCamelCase( self ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase( self ): _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BarkProcessor(tokenizer=_UpperCamelCase ) processor.save_pretrained(self.tmpdirname ) _UpperCAmelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase( self ): _UpperCAmelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _UpperCAmelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCAmelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase( self ): _UpperCAmelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _UpperCAmelCase = 35 _UpperCAmelCase = 2 _UpperCAmelCase = 8 _UpperCAmelCase = { '''semantic_prompt''': np.ones(_UpperCamelCase ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _UpperCAmelCase = processor(text=self.input_string , voice_preset=_UpperCamelCase ) _UpperCAmelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file _UpperCAmelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(_UpperCamelCase , **_UpperCamelCase ) _UpperCAmelCase = processor(text=self.input_string , voice_preset=_UpperCamelCase ) _UpperCAmelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub _UpperCAmelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase( self ): _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BarkProcessor(tokenizer=_UpperCamelCase ) _UpperCAmelCase = processor(text=self.input_string ) _UpperCAmelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=256 , add_special_tokens=_UpperCamelCase , return_attention_mask=_UpperCamelCase , return_token_type_ids=_UpperCamelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
32
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) UpperCAmelCase_ = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) UpperCAmelCase_ = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) UpperCAmelCase_ = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) UpperCAmelCase_ = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[str] = FLAX_MODEL_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModel) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Optional[Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[str] = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class __UpperCamelCase ( _BaseAutoModelClass ): __A : Dict = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[str] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Dict = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class __UpperCamelCase ( _BaseAutoModelClass ): __A : Union[str, Any] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class __UpperCamelCase ( _BaseAutoModelClass ): __A : Any = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Optional[int] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class __UpperCamelCase ( _BaseAutoModelClass ): __A : str = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
32
1
"""simple docstring""" a_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def UpperCAmelCase_ ( __a : Any ): '''simple docstring''' _lowerCamelCase : List[Any] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 10_00_00] number //= 10_00_00 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a_ = [None] * 10_00_00_00 a_ = True a_ = False def UpperCAmelCase_ ( __a : Any ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore _lowerCamelCase : Optional[int] = chain(next_number(__A ) ) _lowerCamelCase : int = number_chain while number < 10_00_00_00: _lowerCamelCase : Dict = number_chain number *= 10 return number_chain def UpperCAmelCase_ ( __a : Dict = 10_00_00_00 ): '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"{solution() = }")
715
"""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 UpperCAmelCase_ ( __a : Any ): '''simple docstring''' _lowerCamelCase : List[str] = tmp_path / 'file.csv' _lowerCamelCase : List[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 UpperCAmelCase_ ( __a : List[str] ): '''simple docstring''' _lowerCamelCase : Optional[Any] = tmp_path / 'malformed_file.csv' _lowerCamelCase : int = 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 UpperCAmelCase_ ( __a : Union[str, Any] , __a : Optional[Any] ): '''simple docstring''' _lowerCamelCase : Tuple = tmp_path / 'csv_with_image.csv' _lowerCamelCase : Tuple = textwrap.dedent( f"\\n image\n {image_file}\n " ) with open(__a , 'w' ) as f: f.write(__a ) return str(__a ) @pytest.fixture def UpperCAmelCase_ ( __a : Any ): '''simple docstring''' _lowerCamelCase : List[Any] = tmp_path / 'csv_with_label.csv' _lowerCamelCase : Union[str, 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 UpperCAmelCase_ ( __a : Tuple ): '''simple docstring''' _lowerCamelCase : str = tmp_path / 'csv_with_int_list.csv' _lowerCamelCase : int = 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 UpperCAmelCase_ ( __a : int , __a : Optional[Any] , __a : List[str] ): '''simple docstring''' _lowerCamelCase : int = Csv() _lowerCamelCase : 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 UpperCAmelCase_ ( __a : Optional[int] ): '''simple docstring''' with open(__a , encoding='utf-8' ) as f: _lowerCamelCase : Any = f.read().splitlines()[1] _lowerCamelCase : Tuple = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) _lowerCamelCase : int = csv._generate_tables([[csv_file_with_image]] ) _lowerCamelCase : Tuple = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() _lowerCamelCase : Union[str, Any] = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def UpperCAmelCase_ ( __a : Union[str, Any] ): '''simple docstring''' with open(__a , encoding='utf-8' ) as f: _lowerCamelCase : List[Any] = f.read().splitlines()[1:] _lowerCamelCase : Tuple = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) _lowerCamelCase : Any = csv._generate_tables([[csv_file_with_label]] ) _lowerCamelCase : Optional[int] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() _lowerCamelCase : str = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(__a ) for label in labels] def UpperCAmelCase_ ( __a : Optional[int] ): '''simple docstring''' _lowerCamelCase : Any = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda __a : [int(__a ) for i in x.split()]} ) _lowerCamelCase : Union[str, Any] = csv._generate_tables([[csv_file_with_int_list]] ) _lowerCamelCase : Any = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) _lowerCamelCase : Optional[Any] = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
349
0
from __future__ import annotations def A ( lowercase__ : int | float | str , lowercase__ : int | float | str ) -> list[str]: if nth_term == "": return [""] UpperCamelCase__ :Dict = int(lowercase__ ) UpperCamelCase__ :Union[str, Any] = int(lowercase__ ) UpperCamelCase__ :list[str] = [] for temp in range(int(lowercase__ ) ): series.append(f"""1 / {pow(temp + 1 , int(lowercase__ ) )}""" if series else """1""" ) return series if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase = int(input("Enter the last number (nth term) of the P-Series")) UpperCamelCase = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
45
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 lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {"""vocab_file""": """spiece.model"""} lowerCAmelCase__ = { """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""", } } lowerCAmelCase__ = { """AI-Sweden/gpt-sw3-126m""": 2_0_4_8, """AI-Sweden/gpt-sw3-350m""": 2_0_4_8, """AI-Sweden/gpt-sw3-1.6b""": 2_0_4_8, """AI-Sweden/gpt-sw3-6.7b""": 2_0_4_8, """AI-Sweden/gpt-sw3-20b""": 2_0_4_8, } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = ['input_ids', 'attention_mask'] def __init__( self , lowercase , lowercase=False , lowercase=False , lowercase=False , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase = None , **lowercase , ) -> None: '''simple docstring''' A__ = {} if sp_model_kwargs is None else sp_model_kwargs A__ = 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" ) A__ = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing A__ = "<|endoftext|>" if eos_token is None else eos_token A__ = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: A__ = unk_token if pad_token is None else pad_token A__ = eos_token if bos_token is None else bos_token else: A__ = "<pad>" if pad_token is None else pad_token A__ = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase , remove_space=lowercase , keep_accents=lowercase , bos_token=lowercase , eos_token=lowercase , unk_token=lowercase , pad_token=lowercase , sp_model_kwargs=self.sp_model_kwargs , **lowercase , ) A__ = do_lower_case A__ = remove_space A__ = keep_accents A__ = vocab_file A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase ) # Used for whitespace normalization in input texts # fmt : off A__ = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing A__ = re.compile( F'[{"".join(map(lowercase , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]' ) def __getstate__( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.__dict__.copy() A__ = None return state def __setstate__( self , lowercase ) -> List[Any]: '''simple docstring''' A__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): A__ = {} A__ = 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 UpperCamelCase ( self ) -> int: '''simple docstring''' return len(self.sp_model ) def UpperCamelCase ( self , lowercase ) -> str: '''simple docstring''' A__ = self.non_printing_characters_re.sub("" , lowercase ) # Normalize whitespaces A__ = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization A__ = unicodedata.normalize("NFC" , lowercase ) return text def UpperCamelCase ( self , lowercase , **lowercase ) -> List[str]: '''simple docstring''' A__ = self.preprocess_text(lowercase ) return self.sp_model.encode(lowercase , out_type=lowercase ) def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return self.sp_model.PieceToId(lowercase ) def UpperCamelCase ( self , lowercase ) -> str: '''simple docstring''' return self.sp_model.IdToPiece(lowercase ) @staticmethod def UpperCamelCase ( lowercase ) -> str: '''simple docstring''' return out_string def UpperCamelCase ( self , lowercase ) -> str: '''simple docstring''' A__ = [] A__ = "" A__ = 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(lowercase ) + token A__ = True A__ = [] else: current_sub_tokens.append(lowercase ) A__ = False out_string += self.sp_model.decode(lowercase ) return out_string def UpperCamelCase ( self ) -> Dict[str, int]: '''simple docstring''' A__ = {self.convert_ids_to_tokens(lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowercase ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ = os.path.join( lowercase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase ) elif not os.path.isfile(self.vocab_file ): with open(lowercase , "wb" ) as fi: A__ = self.sp_model.serialized_model_proto() fi.write(lowercase ) return (out_vocab_file,) def UpperCamelCase ( self , lowercase , lowercase = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = self.preprocess_text(lowercase ) A__ = self.sp_model.encode(lowercase ) else: A__ = [self.preprocess_text(lowercase ) for t in text] A__ = self.sp_model.encode(lowercase ) if return_tensors is True or return_tensors == "pt": A__ = torch.tensor(lowercase ) return token_ids def UpperCamelCase ( self , lowercase ) -> str: '''simple docstring''' return self.sp_model.decode(lowercase ) def UpperCamelCase ( self , lowercase ) -> List[int]: '''simple docstring''' A__ = [F'User: {text}' if is_user else F'Bot: {text}' for is_user, text in conversation.iter_texts()] A__ = ( F'{self.eos_token}{self.bos_token}' + F'{self.bos_token}'.join(lowercase ) + F'{self.bos_token}Bot:' ) return self.encode(text=lowercase )
514
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : Dict = logging.get_logger(__name__) lowercase : str = { """distilbert-base-uncased""": """https://huggingface.co/distilbert-base-uncased/resolve/main/config.json""", """distilbert-base-uncased-distilled-squad""": ( """https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json""" ), """distilbert-base-cased""": """https://huggingface.co/distilbert-base-cased/resolve/main/config.json""", """distilbert-base-cased-distilled-squad""": ( """https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json""" ), """distilbert-base-german-cased""": """https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json""", """distilbert-base-multilingual-cased""": ( """https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json""" ), """distilbert-base-uncased-finetuned-sst-2-english""": ( """https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json""" ), } class A__ ( __UpperCAmelCase ): """simple docstring""" __A : Union[str, Any] = '''distilbert''' __A : List[Any] = { '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self , lowercase=3_0522 , lowercase=512 , lowercase=False , lowercase=6 , lowercase=12 , lowercase=768 , lowercase=4 * 768 , lowercase=0.1 , lowercase=0.1 , lowercase="gelu" , lowercase=0.02 , lowercase=0.1 , lowercase=0.2 , lowercase=0 , **lowercase , ) -> List[str]: '''simple docstring''' a__ : List[Any] = vocab_size a__ : Optional[int] = max_position_embeddings a__ : Any = sinusoidal_pos_embds a__ : str = n_layers a__ : int = n_heads a__ : List[str] = dim a__ : Optional[Any] = hidden_dim a__ : List[str] = dropout a__ : Any = attention_dropout a__ : List[str] = activation a__ : str = initializer_range a__ : List[Any] = qa_dropout a__ : Any = seq_classif_dropout super().__init__(**lowercase , pad_token_id=lowercase) class A__ ( __UpperCAmelCase ): """simple docstring""" @property def __lowercase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": a__ : List[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a__ : List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ])
392
import math import random from typing import Any from .hill_climbing import SearchProblem def A_ ( A__ , A__ = True , A__ = math.inf , A__ = -math.inf , A__ = math.inf , A__ = -math.inf , A__ = False , A__ = 100 , A__ = 0.01 , A__ = 1 , ) -> Any: a__ : List[str] = False a__ : Optional[int] = search_prob a__ : Any = start_temperate a__ : Any = [] a__ : int = 0 a__ : Any = None while not search_end: a__ : Tuple = current_state.score() if best_state is None or current_score > best_state.score(): a__ : Optional[Any] = current_state scores.append(A__ ) iterations += 1 a__ : Union[str, Any] = None a__ : List[str] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to a__ : Optional[int] = random.randint(0 , len(A__ ) - 1 ) # picking a random neighbor a__ : List[str] = neighbors.pop(A__ ) a__ : List[Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: a__ : int = change * -1 # in case we are finding minimum if change > 0: # improves the solution a__ : Optional[Any] = picked_neighbor else: a__ : List[Any] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability a__ : Tuple = picked_neighbor a__ : Union[str, Any] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor a__ : int = True else: a__ : Union[str, Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(A__ ) , A__ ) plt.xlabel('Iterations' ) plt.ylabel('Function values' ) plt.show() return best_state if __name__ == "__main__": def A_ ( A__ , A__ ) -> Optional[Any]: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowercase : List[Any] = SearchProblem(x=1_2, y=4_7, step_size=1, function_to_optimize=test_fa) lowercase : int = simulated_annealing( prob, find_max=False, max_x=1_0_0, min_x=5, max_y=5_0, min_y=-5, visualization=True ) print( """The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowercase : List[str] = SearchProblem(x=1_2, y=4_7, step_size=1, function_to_optimize=test_fa) lowercase : List[Any] = simulated_annealing( prob, find_max=True, max_x=1_0_0, min_x=5, max_y=5_0, min_y=-5, visualization=True ) print( """The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def A_ ( A__ , A__ ) -> Optional[Any]: return (3 * x**2) - (6 * y) lowercase : Tuple = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowercase : Optional[Any] = simulated_annealing(prob, find_max=False, visualization=True) print( """The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ F"""{local_min.score()}""" ) lowercase : str = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowercase : List[Any] = simulated_annealing(prob, find_max=True, visualization=True) print( """The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ F"""{local_min.score()}""" )
392
1
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) __SCREAMING_SNAKE_CASE : List[str] = logging.getLogger() __SCREAMING_SNAKE_CASE : Dict = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( __snake_case ): def UpperCamelCase ( self , lowercase_ ): os.makedirs(lowercase_ , exist_ok=lowercase_ ) _snake_case : Tuple = {"source": "What is love ?", "target": "life"} _snake_case : List[str] = {"train": 12, "val": 2, "test": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: _snake_case : Dict = "\n".join([contents[field]] * n_lines[split] ) with open(os.path.join(lowercase_ , f"""{split}.{field}""" ) , "w" ) as f: f.write(lowercase_ ) def UpperCamelCase ( self , lowercase_ , lowercase_ = "pytorch" ): _snake_case : Any = self.get_auto_remove_tmp_dir() _snake_case : Tuple = os.path.join(lowercase_ , "output" ) _snake_case : List[str] = os.path.join(lowercase_ , "data" ) self._create_dummy_data(data_dir=lowercase_ ) _snake_case : str = f""" --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ """.split() if gpus > 0: testargs.append(f"""--gpus={gpus}""" ) if is_apex_available(): testargs.append("--fp16" ) else: testargs.append("--gpus=0" ) testargs.append("--distributed_backend=ddp_cpu" ) testargs.append("--num_processes=2" ) _snake_case : Optional[Any] = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(lowercase_ , env=self.get_env() ) _snake_case : str = os.path.join(lowercase_ , "metrics.json" ) with open(lowercase_ ) as f: _snake_case : Optional[int] = json.load(lowercase_ ) return result @require_torch_gpu def UpperCamelCase ( self ): _snake_case : Any = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu def UpperCamelCase ( self ): _snake_case : Optional[Any] = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_gpu @require_ray def UpperCamelCase ( self ): _snake_case : Dict = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu @require_ray def UpperCamelCase ( self ): _snake_case : List[str] = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 )
670
from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case (__lowercase ) -> Any: '''simple docstring''' if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(__lowercase ): return ext raise Exception( F"""Unable to determine file format from file extension {path}. """ F"""Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}""" ) def snake_case (__lowercase ) -> Any: '''simple docstring''' _snake_case : int = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) _snake_case : List[Any] = try_infer_format_from_ext(args.input ) if args.format == "infer" else args.format _snake_case : Optional[int] = PipelineDataFormat.from_str( format=__lowercase , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(__lowercase , __lowercase ) class lowercase_ ( __snake_case ): def __init__( self , lowercase_ , lowercase_ ): _snake_case : str = nlp _snake_case : str = reader @staticmethod def UpperCamelCase ( lowercase_ ): _snake_case : Dict = parser.add_parser("run" , help="Run a pipeline through the CLI" ) run_parser.add_argument("--task" , choices=get_supported_tasks() , help="Task to run" ) run_parser.add_argument("--input" , type=lowercase_ , help="Path to the file to use for inference" ) run_parser.add_argument("--output" , type=lowercase_ , help="Path to the file that will be used post to write results." ) run_parser.add_argument("--model" , type=lowercase_ , help="Name or path to the model to instantiate." ) run_parser.add_argument("--config" , type=lowercase_ , help="Name or path to the model's config to instantiate." ) run_parser.add_argument( "--tokenizer" , type=lowercase_ , help="Name of the tokenizer to use. (default: same as the model name)" ) run_parser.add_argument( "--column" , type=lowercase_ , help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)" , ) run_parser.add_argument( "--format" , type=lowercase_ , default="infer" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="Input format to read from" , ) run_parser.add_argument( "--device" , type=lowercase_ , default=-1 , help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)" , ) run_parser.add_argument("--overwrite" , action="store_true" , help="Allow overwriting the output file." ) run_parser.set_defaults(func=lowercase_ ) def UpperCamelCase ( self ): _snake_case ,_snake_case : Tuple = self._nlp, [] for entry in self._reader: _snake_case : Optional[Any] = nlp(**lowercase_ ) if self._reader.is_multi_columns else nlp(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): outputs.append(lowercase_ ) else: outputs += output # Saving data if self._nlp.binary_output: _snake_case : str = self._reader.save_binary(lowercase_ ) logger.warning(f"""Current pipeline requires output to be in binary format, saving at {binary_path}""" ) else: self._reader.save(lowercase_ )
670
1
'''simple docstring''' def A_ ( SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 7 , SCREAMING_SNAKE_CASE_ = 1_00_00_00 ) ->int: lowercase_ = 0 lowercase_ = 1 for current_denominator in range(1 , limit + 1 ): lowercase_ = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: lowercase_ = current_numerator lowercase_ = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=100_0000))
603
'''simple docstring''' # Lint as: python3 import itertools import os import re __snake_case = re.compile(r"""([A-Z]+)([A-Z][a-z])""") __snake_case = re.compile(r"""([a-z\d])([A-Z])""") __snake_case = re.compile(r"""(?<!_)_(?!_)""") __snake_case = re.compile(r"""(_{2,})""") __snake_case = r"""^\w+(\.\w+)*$""" __snake_case = r"""<>:/\|?*""" def A_ ( SCREAMING_SNAKE_CASE_ ) ->Union[str, Any]: lowercase_ = _uppercase_uppercase_re.sub(r"""\1_\2""" , SCREAMING_SNAKE_CASE_ ) lowercase_ = _lowercase_uppercase_re.sub(r"""\1_\2""" , SCREAMING_SNAKE_CASE_ ) return name.lower() def A_ ( SCREAMING_SNAKE_CASE_ ) ->List[Any]: lowercase_ = _single_underscore_re.split(SCREAMING_SNAKE_CASE_ ) lowercase_ = [_multiple_underscores_re.split(SCREAMING_SNAKE_CASE_ ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(SCREAMING_SNAKE_CASE_ ) if n != """""" ) def A_ ( SCREAMING_SNAKE_CASE_ ) ->Any: if os.path.basename(SCREAMING_SNAKE_CASE_ ) != name: raise ValueError(f"""Should be a dataset name, not a path: {name}""" ) return camelcase_to_snakecase(SCREAMING_SNAKE_CASE_ ) def A_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->Any: if os.path.basename(SCREAMING_SNAKE_CASE_ ) != name: raise ValueError(f"""Should be a dataset name, not a path: {name}""" ) if not re.match(_split_re , SCREAMING_SNAKE_CASE_ ): raise ValueError(f"""Split name should match '{_split_re}'' but got '{split}'.""" ) return f"""{filename_prefix_for_name(SCREAMING_SNAKE_CASE_ )}-{split}""" def A_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) ->Tuple: lowercase_ = filename_prefix_for_split(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if filetype_suffix: prefix += f""".{filetype_suffix}""" lowercase_ = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return f"""{filepath}*""" def A_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ) ->Optional[Any]: lowercase_ = filename_prefix_for_split(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase_ = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if shard_lengths: lowercase_ = len(SCREAMING_SNAKE_CASE_ ) lowercase_ = [f"""{prefix}-{shard_id:05d}-of-{num_shards:05d}""" for shard_id in range(SCREAMING_SNAKE_CASE_ )] if filetype_suffix: lowercase_ = [filename + f""".{filetype_suffix}""" for filename in filenames] return filenames else: lowercase_ = prefix if filetype_suffix: filename += f""".{filetype_suffix}""" return [filename]
603
1
"""simple docstring""" from jiwer import compute_measures import datasets _lowerCAmelCase : Optional[Any] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' _lowerCAmelCase : Optional[int] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' _lowerCAmelCase : Tuple = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def _lowercase ( self: Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { "predictions": datasets.Value("string" ,id="sequence" ), "references": datasets.Value("string" ,id="sequence" ), } ) ,codebase_urls=["https://github.com/jitsi/jiwer/"] ,reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] ,) def _lowercase ( self: List[Any] ,__lowerCAmelCase: List[str]=None ,__lowerCAmelCase: Optional[Any]=None ,__lowerCAmelCase: Union[str, Any]=False ): '''simple docstring''' if concatenate_texts: return compute_measures(__lowerCAmelCase ,__lowerCAmelCase )["wer"] else: _lowerCamelCase : List[Any] = 0 _lowerCamelCase : Tuple = 0 for prediction, reference in zip(__lowerCAmelCase ,__lowerCAmelCase ): _lowerCamelCase : str = compute_measures(__lowerCAmelCase ,__lowerCAmelCase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
46
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : Any = logging.get_logger(__name__) _UpperCAmelCase : Dict = { '''google/pix2struct-textcaps-base''': ( '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json''' ), } class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct_text_model' UpperCamelCase__ = ['past_key_values'] UpperCamelCase__ = { 'hidden_size': 'hidden_size', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , snake_case_=5_02_44 , snake_case_=7_68 , snake_case_=64 , snake_case_=20_48 , snake_case_=12 , snake_case_=12 , snake_case_=32 , snake_case_=1_28 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=1.0 , snake_case_="gelu_new" , snake_case_=0 , snake_case_=False , snake_case_=0 , snake_case_=1 , snake_case_=False , snake_case_=True , **snake_case_ , ): lowercase =vocab_size lowercase =hidden_size lowercase =d_kv lowercase =d_ff lowercase =num_layers lowercase =num_heads lowercase =relative_attention_num_buckets lowercase =relative_attention_max_distance lowercase =dropout_rate lowercase =layer_norm_epsilon lowercase =initializer_factor lowercase =use_cache lowercase =eos_token_id lowercase =decoder_start_token_id # for backwards compatibility lowercase =dense_act_fn super().__init__( pad_token_id=snake_case_ , eos_token_id=snake_case_ , decoder_start_token_id=snake_case_ , tie_word_embeddings=snake_case_ , is_decoder=snake_case_ , **snake_case_ , ) @classmethod def _A( cls , snake_case_ , **snake_case_ ): cls._set_token_in_kwargs(snake_case_ ) lowercase , lowercase =cls.get_config_dict(snake_case_ , **snake_case_ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase =config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case_ , **snake_case_ ) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct_vision_model' def __init__( self , snake_case_=7_68 , snake_case_=7_68 , snake_case_=20_48 , snake_case_=64 , snake_case_=12 , snake_case_=12 , snake_case_="gelu_new" , snake_case_=1E-6 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=1E-10 , snake_case_=1.0 , snake_case_=40_96 , snake_case_=32 , snake_case_=1_28 , **snake_case_ , ): super().__init__(**snake_case_ ) lowercase =hidden_size lowercase =patch_embed_hidden_size lowercase =d_ff lowercase =dropout_rate lowercase =num_hidden_layers lowercase =num_attention_heads lowercase =initializer_range lowercase =initializer_factor lowercase =attention_dropout lowercase =layer_norm_eps lowercase =dense_act_fn lowercase =seq_len lowercase =relative_attention_num_buckets lowercase =relative_attention_max_distance lowercase =d_kv @classmethod def _A( cls , snake_case_ , **snake_case_ ): cls._set_token_in_kwargs(snake_case_ ) lowercase , lowercase =cls.get_config_dict(snake_case_ , **snake_case_ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase =config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case_ , **snake_case_ ) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct' UpperCamelCase__ = True def __init__( self , snake_case_=None , snake_case_=None , snake_case_=1.0 , snake_case_=0.02 , snake_case_=False , snake_case_=False , snake_case_=True , **snake_case_ , ): super().__init__(tie_word_embeddings=snake_case_ , is_encoder_decoder=snake_case_ , **snake_case_ ) if text_config is None: lowercase ={} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase ={} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase =PixaStructTextConfig(**snake_case_ ) lowercase =PixaStructVisionConfig(**snake_case_ ) lowercase =self.text_config.decoder_start_token_id lowercase =self.text_config.pad_token_id lowercase =self.text_config.eos_token_id lowercase =initializer_factor lowercase =initializer_range lowercase =self.initializer_range lowercase =self.initializer_range lowercase =is_vqa @classmethod def _A( cls , snake_case_ , snake_case_ , **snake_case_ ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case_ ) def _A( self ): lowercase =copy.deepcopy(self.__dict__ ) lowercase =self.text_config.to_dict() lowercase =self.vision_config.to_dict() lowercase =self.__class__.model_type return output
72
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "google/switch-base-8": "https://huggingface.co/google/switch-base-8/blob/main/config.json", } class a ( __magic_name__ ): _snake_case = '''switch_transformers''' _snake_case = ['''past_key_values'''] _snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any], SCREAMING_SNAKE_CASE_ : Tuple=3_21_28, SCREAMING_SNAKE_CASE_ : List[Any]=7_68, SCREAMING_SNAKE_CASE_ : Dict=64, SCREAMING_SNAKE_CASE_ : int=20_48, SCREAMING_SNAKE_CASE_ : int=64, SCREAMING_SNAKE_CASE_ : str=12, SCREAMING_SNAKE_CASE_ : str=3, SCREAMING_SNAKE_CASE_ : str=12, SCREAMING_SNAKE_CASE_ : List[Any]=3, SCREAMING_SNAKE_CASE_ : str=12, SCREAMING_SNAKE_CASE_ : Dict=8, SCREAMING_SNAKE_CASE_ : Any=False, SCREAMING_SNAKE_CASE_ : str=0.01, SCREAMING_SNAKE_CASE_ : Tuple="float32", SCREAMING_SNAKE_CASE_ : Optional[Any]=False, SCREAMING_SNAKE_CASE_ : str=32, SCREAMING_SNAKE_CASE_ : str=1_28, SCREAMING_SNAKE_CASE_ : int=0.1, SCREAMING_SNAKE_CASE_ : List[str]=1e-6, SCREAMING_SNAKE_CASE_ : Tuple=0.001, SCREAMING_SNAKE_CASE_ : Optional[int]=0.001, SCREAMING_SNAKE_CASE_ : List[Any]=1.0, SCREAMING_SNAKE_CASE_ : Optional[Any]="relu", SCREAMING_SNAKE_CASE_ : List[str]=True, SCREAMING_SNAKE_CASE_ : Tuple=False, SCREAMING_SNAKE_CASE_ : str=True, SCREAMING_SNAKE_CASE_ : Union[str, Any]=0, SCREAMING_SNAKE_CASE_ : int=1, **SCREAMING_SNAKE_CASE_ : Dict, ): snake_case : int = vocab_size snake_case : Dict = d_model snake_case : Tuple = d_kv snake_case : Optional[int] = d_ff snake_case : Tuple = num_sparse_encoder_layers snake_case : List[Any] = num_layers snake_case : str = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry snake_case : Union[str, Any] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: snake_case : List[Any] = self.num_layers // self.num_sparse_encoder_layers else: snake_case : List[str] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: snake_case : Optional[Any] = self.num_decoder_layers // self.num_sparse_decoder_layers else: snake_case : Tuple = self.num_decoder_layers # HACK: this will create 0 sparse layers snake_case : Optional[Any] = num_heads snake_case : int = num_experts snake_case : Dict = expert_capacity snake_case : Optional[int] = router_bias snake_case : Any = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) snake_case : int = router_dtype snake_case : Dict = router_ignore_padding_tokens snake_case : Optional[Any] = relative_attention_num_buckets snake_case : Dict = relative_attention_max_distance snake_case : Tuple = dropout_rate snake_case : Union[str, Any] = layer_norm_epsilon snake_case : Optional[int] = initializer_factor snake_case : Optional[Any] = feed_forward_proj snake_case : Dict = use_cache snake_case : List[Any] = add_router_probs snake_case : List[str] = router_z_loss_coef snake_case : List[str] = router_aux_loss_coef snake_case : Dict = self.feed_forward_proj.split('''-''' ) snake_case : int = act_info[-1] snake_case : Tuple = act_info[0] == '''gated''' if len(SCREAMING_SNAKE_CASE_ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE_ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": snake_case : List[Any] = '''gelu_new''' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_, eos_token_id=SCREAMING_SNAKE_CASE_, is_encoder_decoder=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, )
555
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) UpperCAmelCase = logging.getLogger() def A ( ): snake_case : Dict = argparse.ArgumentParser() parser.add_argument('''-f''' ) snake_case : Any = parser.parse_args() return args.f def A ( A_ : str ): snake_case : str = {} snake_case : Union[str, Any] = os.path.join(A_ , '''all_results.json''' ) if os.path.exists(A_ ): with open(A_ , '''r''' ) as f: snake_case : List[str] = json.load(A_ ) else: raise ValueError(F"""can't find {path}""" ) return results def A ( ): snake_case : Any = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class a ( __magic_name__ ): @classmethod def __snake_case ( cls : Tuple ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU snake_case : int = tempfile.mkdtemp() snake_case : Optional[Any] = os.path.join(cls.tmpdir, '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) snake_case : Tuple = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __snake_case ( cls : Optional[int] ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : Any ): snake_case : Any = self.get_auto_remove_tmp_dir() snake_case : Optional[Any] = F""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append('''--fp16''' ) run_command(self._launch_args + testargs ) snake_case : int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''], 0.75 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : Tuple ): snake_case : int = self.get_auto_remove_tmp_dir() snake_case : str = F""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) snake_case : List[str] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''perplexity'''], 1_00 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : List[Any] ): snake_case : Union[str, Any] = self.get_auto_remove_tmp_dir() snake_case : int = F""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) snake_case : List[Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''perplexity'''], 42 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : Dict ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu snake_case : Any = 7 if get_gpu_count() > 1 else 2 snake_case : Optional[int] = self.get_auto_remove_tmp_dir() snake_case : str = F""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) snake_case : Optional[int] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''], 0.75 ) self.assertLess(result['''train_loss'''], 0.5 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : Tuple ): snake_case : Tuple = self.get_auto_remove_tmp_dir() snake_case : Optional[int] = F""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) snake_case : str = get_results(SCREAMING_SNAKE_CASE_ ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['''eval_f1'''], 28 ) self.assertGreaterEqual(result['''eval_exact'''], 28 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : Optional[int] ): snake_case : Any = self.get_auto_remove_tmp_dir() snake_case : List[Any] = F""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) snake_case : Union[str, Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''], 0.8 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : str ): snake_case : str = self.get_auto_remove_tmp_dir() snake_case : Any = F""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) snake_case : str = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_rouge1'''], 10 ) self.assertGreaterEqual(result['''eval_rouge2'''], 2 ) self.assertGreaterEqual(result['''eval_rougeL'''], 7 ) self.assertGreaterEqual(result['''eval_rougeLsum'''], 7 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : int ): snake_case : Any = self.get_auto_remove_tmp_dir() snake_case : Optional[int] = F""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) snake_case : Optional[int] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_bleu'''], 30 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''translation_no_trainer''' ) ) ) @slow def __snake_case ( self : Union[str, Any] ): snake_case : Any = logging.StreamHandler(sys.stdout ) logger.addHandler(SCREAMING_SNAKE_CASE_ ) snake_case : Union[str, Any] = self.get_auto_remove_tmp_dir() snake_case : Dict = F""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) snake_case : List[Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_overall_accuracy'''], 0.10 ) @mock.patch.dict(os.environ, {'''WANDB_MODE''': '''offline'''} ) def __snake_case ( self : Union[str, Any] ): snake_case : str = self.get_auto_remove_tmp_dir() snake_case : Optional[Any] = F""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append('''--fp16''' ) run_command(self._launch_args + testargs ) snake_case : Tuple = get_results(SCREAMING_SNAKE_CASE_ ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''], 0.6 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_, '''image_classification_no_trainer''' ) ) )
555
1
from typing import Dict from .base import GenericTensor, Pipeline class UpperCAmelCase__ ( snake_case__ ): def snake_case_ ( self , A__=None , A__=None , A__=None , **A__ ): """simple docstring""" if tokenize_kwargs is None: UpperCAmelCase_: Tuple = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( "truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)" ) UpperCAmelCase_: int = truncation UpperCAmelCase_: Optional[Any] = tokenize_kwargs UpperCAmelCase_: Optional[int] = {} if return_tensors is not None: UpperCAmelCase_: Optional[int] = return_tensors return preprocess_params, {}, postprocess_params def snake_case_ ( self , A__ , **A__ ): """simple docstring""" UpperCAmelCase_: Union[str, Any] = self.framework UpperCAmelCase_: Tuple = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return model_inputs def snake_case_ ( self , A__ ): """simple docstring""" UpperCAmelCase_: str = self.model(**_SCREAMING_SNAKE_CASE ) return model_outputs def snake_case_ ( self , A__ , A__=False ): """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self , *A__ , **A__ ): """simple docstring""" return super().__call__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
137
'''simple docstring''' import argparse import copy def lowercase__ ( __UpperCamelCase )-> Union[str, Any]: UpperCamelCase = {} with open(__UpperCamelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: UpperCamelCase = [] _list.append([line.split()[1], line.split()[2]] ) UpperCamelCase = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: UpperCamelCase = [] _list.append([line.split()[0], line.split()[2]] ) UpperCamelCase = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Union[str, Any]: with open(__UpperCamelCase ) as f: UpperCamelCase = f.read(1 ) UpperCamelCase = start_node UpperCamelCase = [] UpperCamelCase = start_node UpperCamelCase = 0 while visiting not in first_solution: UpperCamelCase = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__UpperCamelCase ) and k[0] not in first_solution: UpperCamelCase = k[1] UpperCamelCase = k[0] first_solution.append(__UpperCamelCase ) UpperCamelCase = distance_of_first_solution + int(__UpperCamelCase ) UpperCamelCase = best_node first_solution.append(__UpperCamelCase ) UpperCamelCase = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 UpperCamelCase = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List[Any]: UpperCamelCase = [] for n in solution[1:-1]: UpperCamelCase = solution.index(__UpperCamelCase ) for kn in solution[1:-1]: UpperCamelCase = solution.index(__UpperCamelCase ) if n == kn: continue UpperCamelCase = copy.deepcopy(__UpperCamelCase ) UpperCamelCase = kn UpperCamelCase = n UpperCamelCase = 0 for k in _tmp[:-1]: UpperCamelCase = _tmp[_tmp.index(__UpperCamelCase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: UpperCamelCase = distance + int(i[1] ) _tmp.append(__UpperCamelCase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) UpperCamelCase = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __UpperCamelCase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Union[str, Any]: UpperCamelCase = 1 UpperCamelCase = first_solution UpperCamelCase = [] UpperCamelCase = distance_of_first_solution UpperCamelCase = solution while count <= iters: UpperCamelCase = find_neighborhood(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase = 0 UpperCamelCase = neighborhood[index_of_best_solution] UpperCamelCase = len(__UpperCamelCase ) - 1 UpperCamelCase = False while not found: UpperCamelCase = 0 while i < len(__UpperCamelCase ): if best_solution[i] != solution[i]: UpperCamelCase = best_solution[i] UpperCamelCase = solution[i] break UpperCamelCase = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) UpperCamelCase = True UpperCamelCase = best_solution[:-1] UpperCamelCase = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: UpperCamelCase = cost UpperCamelCase = solution else: UpperCamelCase = index_of_best_solution + 1 UpperCamelCase = neighborhood[index_of_best_solution] if len(__UpperCamelCase ) >= size: tabu_list.pop(0 ) UpperCamelCase = count + 1 return best_solution_ever, best_cost def lowercase__ ( __UpperCamelCase=None )-> Tuple: UpperCamelCase = generate_neighbours(args.File ) UpperCamelCase ,UpperCamelCase = generate_first_solution( args.File , __UpperCamelCase ) UpperCamelCase ,UpperCamelCase = tabu_search( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , args.Iterations , args.Size , ) print(F"Best solution: {best_sol}, with total distance: {best_cost}." ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser(description='Tabu Search') parser.add_argument( '-f', '--File', type=str, help='Path to the file containing the data', required=True, ) parser.add_argument( '-i', '--Iterations', type=int, help='How many iterations the algorithm should perform', required=True, ) parser.add_argument( '-s', '--Size', type=int, help='Size of the tabu list', required=True ) # Pass the arguments to main method main(parser.parse_args())
301
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase = { '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ '''SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Swinv2ForImageClassification''', '''Swinv2ForMaskedImageModeling''', '''Swinv2Model''', '''Swinv2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCamelCase = { '''configuration_altclip''': [ '''ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AltCLIPConfig''', '''AltCLIPTextConfig''', '''AltCLIPVisionConfig''', ], '''processing_altclip''': ['''AltCLIPProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ '''ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AltCLIPPreTrainedModel''', '''AltCLIPModel''', '''AltCLIPTextModel''', '''AltCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
478
0
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType lowerCAmelCase : Tuple = logging.get_logger(__name__) lowerCAmelCase : int = { 'openai/imagegpt-small': '', 'openai/imagegpt-medium': '', 'openai/imagegpt-large': '', } class SCREAMING_SNAKE_CASE__ ( snake_case_): lowerCAmelCase_ = """imagegpt""" lowerCAmelCase_ = ["""past_key_values"""] lowerCAmelCase_ = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , A_=512 + 1 , A_=32 * 32 , A_=512 , A_=24 , A_=8 , A_=None , A_="quick_gelu" , A_=0.1 , A_=0.1 , A_=0.1 , A_=1e-5 , A_=0.02 , A_=True , A_=True , A_=False , A_=False , A_=False , **A_ , )-> str: '''simple docstring''' UpperCamelCase = vocab_size UpperCamelCase = n_positions UpperCamelCase = n_embd UpperCamelCase = n_layer UpperCamelCase = n_head UpperCamelCase = n_inner UpperCamelCase = activation_function UpperCamelCase = resid_pdrop UpperCamelCase = embd_pdrop UpperCamelCase = attn_pdrop UpperCamelCase = layer_norm_epsilon UpperCamelCase = initializer_range UpperCamelCase = scale_attn_weights UpperCamelCase = use_cache UpperCamelCase = scale_attn_by_inverse_layer_idx UpperCamelCase = reorder_and_upcast_attn UpperCamelCase = tie_word_embeddings super().__init__(tie_word_embeddings=A_ , **A_ ) class SCREAMING_SNAKE_CASE__ ( snake_case_): @property def UpperCAmelCase_ ( self )-> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ] ) def UpperCAmelCase_ ( self , A_ , A_ = 1 , A_ = -1 , A_ = False , A_ = None , A_ = 3 , A_ = 32 , A_ = 32 , )-> Mapping[str, Any]: '''simple docstring''' UpperCamelCase = self._generate_dummy_images(A_ , A_ , A_ , A_ ) UpperCamelCase = dict(preprocessor(images=A_ , return_tensors=A_ ) ) return inputs
3
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def UpperCamelCase ( __lowerCamelCase : int = 8 ): snake_case : int = ascii_letters + digits + punctuation return "".join(secrets.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : int ): # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(__lowerCamelCase ) snake_case : Any = i // 3 snake_case : Optional[int] = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case : Tuple = ( chars_incl + random(__lowerCamelCase , quotient + remainder ) + random(__lowerCamelCase , __lowerCamelCase ) + random(__lowerCamelCase , __lowerCamelCase ) ) snake_case : Optional[Any] = list(__lowerCamelCase ) shuffle(__lowerCamelCase ) return "".join(__lowerCamelCase ) # random is a generalised function for letters, characters and numbers def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : int ): return "".join(secrets.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) def UpperCamelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : str ): pass # Put your code here... def UpperCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ): pass # Put your code here... def UpperCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : List[Any] ): pass # Put your code here... def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : int = 8 ): if len(__lowerCamelCase ) < min_length: # Your Password must be at least 8 characters long return False snake_case : Dict = any(char in ascii_uppercase for char in password ) snake_case : Optional[int] = any(char in ascii_lowercase for char in password ) snake_case : str = any(char in digits for char in password ) snake_case : str = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def UpperCamelCase ( ): snake_case : int = int(input("Please indicate the max length of your password: " ).strip() ) snake_case : Union[str, Any] = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:" , password_generator(__lowerCamelCase ) ) print( "Alternative Password generated:" , alternative_password_generator(__lowerCamelCase , __lowerCamelCase ) , ) print("[If you are thinking of using this passsword, You better save it.]" ) if __name__ == "__main__": main()
204
0
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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class __magic_name__ ( unittest.TestCase): def __init__( self : Any ,__SCREAMING_SNAKE_CASE : str ,__SCREAMING_SNAKE_CASE : str=7 ,__SCREAMING_SNAKE_CASE : Dict=3 ,__SCREAMING_SNAKE_CASE : str=1_8 ,__SCREAMING_SNAKE_CASE : int=3_0 ,__SCREAMING_SNAKE_CASE : List[str]=4_0_0 ,__SCREAMING_SNAKE_CASE : int=True ,__SCREAMING_SNAKE_CASE : int=None ,__SCREAMING_SNAKE_CASE : Union[str, Any]=True ,__SCREAMING_SNAKE_CASE : Dict=None ,__SCREAMING_SNAKE_CASE : str=True ,__SCREAMING_SNAKE_CASE : Optional[int]=[0.4814_5466, 0.457_8275, 0.4082_1073] ,__SCREAMING_SNAKE_CASE : int=[0.2686_2954, 0.2613_0258, 0.2757_7711] ,__SCREAMING_SNAKE_CASE : Union[str, Any]=True ,): UpperCAmelCase = size if size is not None else {"height": 2_2_4, "width": 2_2_4} UpperCAmelCase = crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = image_size UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_center_crop UpperCAmelCase = crop_size UpperCAmelCase = do_normalize UpperCAmelCase = image_mean UpperCAmelCase = image_std UpperCAmelCase = do_convert_rgb def _UpperCAmelCase ( self : List[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def _UpperCAmelCase ( self : str ,__SCREAMING_SNAKE_CASE : List[str]=False ,__SCREAMING_SNAKE_CASE : List[str]=False ,__SCREAMING_SNAKE_CASE : Optional[Any]=False ): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: UpperCAmelCase = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 2_5_5 ,size=(self.num_channels, self.max_resolution, self.max_resolution) ,dtype=np.uinta ) ) else: UpperCAmelCase = [] for i in range(self.batch_size ): UpperCAmelCase , UpperCAmelCase = np.random.choice(np.arange(self.min_resolution ,self.max_resolution ) ,2 ) image_inputs.append(np.random.randint(2_5_5 ,size=(self.num_channels, width, height) ,dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension UpperCAmelCase = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE ,0 ,-1 ) ) for x in image_inputs] if torchify: UpperCAmelCase = [torch.from_numpy(__SCREAMING_SNAKE_CASE ) for x in image_inputs] return image_inputs @require_torch @require_vision class __magic_name__ ( _a , unittest.TestCase): _UpperCAmelCase : Dict = ChineseCLIPImageProcessor if is_vision_available() else None def _UpperCAmelCase ( self : Any ): UpperCAmelCase = ChineseCLIPImageProcessingTester(self ,do_center_crop=__SCREAMING_SNAKE_CASE ) @property def _UpperCAmelCase ( self : Any ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self : Tuple ): UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_resize" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"size" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_center_crop" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"center_crop" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_normalize" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"image_mean" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"image_std" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_convert_rgb" ) ) def _UpperCAmelCase ( self : str ): UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 2_2_4, "width": 2_2_4} ) self.assertEqual(image_processor.crop_size ,{"height": 1_8, "width": 1_8} ) UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ,size=4_2 ,crop_size=8_4 ) self.assertEqual(image_processor.size ,{"shortest_edge": 4_2} ) self.assertEqual(image_processor.crop_size ,{"height": 8_4, "width": 8_4} ) def _UpperCAmelCase ( self : Union[str, Any] ): pass def _UpperCAmelCase ( self : Union[str, Any] ): # Initialize image_processing UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE ,Image.Image ) # Test not batched input UpperCAmelCase = 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 UpperCAmelCase = image_processing(__SCREAMING_SNAKE_CASE ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) def _UpperCAmelCase ( self : Optional[Any] ): # Initialize image_processing UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=__SCREAMING_SNAKE_CASE ,numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE ,np.ndarray ) # Test not batched input UpperCAmelCase = image_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 UpperCAmelCase = image_processing(__SCREAMING_SNAKE_CASE ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) def _UpperCAmelCase ( self : Any ): # Initialize image_processing UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=__SCREAMING_SNAKE_CASE ,torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE ,torch.Tensor ) # Test not batched input UpperCAmelCase = image_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 UpperCAmelCase = image_processing(__SCREAMING_SNAKE_CASE ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) @require_torch @require_vision class __magic_name__ ( _a , unittest.TestCase): _UpperCAmelCase : Tuple = ChineseCLIPImageProcessor if is_vision_available() else None def _UpperCAmelCase ( self : List[Any] ): UpperCAmelCase = ChineseCLIPImageProcessingTester(self ,num_channels=4 ,do_center_crop=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = 3 @property def _UpperCAmelCase ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self : Any ): UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_resize" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"size" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_center_crop" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"center_crop" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_normalize" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"image_mean" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"image_std" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_convert_rgb" ) ) def _UpperCAmelCase ( self : Union[str, Any] ): pass def _UpperCAmelCase ( self : Optional[Any] ): # Initialize image_processing UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE ,Image.Image ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) # Test batched UpperCAmelCase = image_processing(__SCREAMING_SNAKE_CASE ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,)
405
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _a): @require_torch def _UpperCAmelCase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched UpperCAmelCase = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache UpperCAmelCase = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(__SCREAMING_SNAKE_CASE ) BertModel.from_pretrained(__SCREAMING_SNAKE_CASE ) BertTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) pipeline(task="fill-mask" ,model=__SCREAMING_SNAKE_CASE ) # baseline - just load from_pretrained with normal network UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed UpperCAmelCase = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCAmelCase = "1" UpperCAmelCase = subprocess.run(__SCREAMING_SNAKE_CASE ,env=__SCREAMING_SNAKE_CASE ,check=__SCREAMING_SNAKE_CASE ,capture_output=__SCREAMING_SNAKE_CASE ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) @require_torch def _UpperCAmelCase ( self : Optional[int] ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched UpperCAmelCase = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache UpperCAmelCase = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(__SCREAMING_SNAKE_CASE ) BertModel.from_pretrained(__SCREAMING_SNAKE_CASE ) BertTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) pipeline(task="fill-mask" ,model=__SCREAMING_SNAKE_CASE ) # baseline - just load from_pretrained with normal network UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed UpperCAmelCase = self.get_env() UpperCAmelCase = subprocess.run(__SCREAMING_SNAKE_CASE ,env=__SCREAMING_SNAKE_CASE ,check=__SCREAMING_SNAKE_CASE ,capture_output=__SCREAMING_SNAKE_CASE ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) @require_torch def _UpperCAmelCase ( self : str ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched UpperCAmelCase = "\nfrom transformers import BertConfig, BertModel, BertTokenizer\n " UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n " UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " # baseline - just load from_pretrained with normal network UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run] )] # should succeed UpperCAmelCase = self.get_env() UpperCAmelCase = subprocess.run(__SCREAMING_SNAKE_CASE ,env=__SCREAMING_SNAKE_CASE ,check=__SCREAMING_SNAKE_CASE ,capture_output=__SCREAMING_SNAKE_CASE ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) # next emulate no network UpperCAmelCase = [sys.executable, "-c", "\n".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCAmelCase = "1" UpperCAmelCase = subprocess.run(__SCREAMING_SNAKE_CASE ,env=__SCREAMING_SNAKE_CASE ,check=__SCREAMING_SNAKE_CASE ,capture_output=__SCREAMING_SNAKE_CASE ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) @require_torch def _UpperCAmelCase ( self : Dict ): UpperCAmelCase = "\nfrom transformers import pipeline\n " UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n " UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " UpperCAmelCase = self.get_env() UpperCAmelCase = "1" UpperCAmelCase = [sys.executable, "-c", "\n".join([load, mock, run] )] UpperCAmelCase = subprocess.run(__SCREAMING_SNAKE_CASE ,env=__SCREAMING_SNAKE_CASE ,check=__SCREAMING_SNAKE_CASE ,capture_output=__SCREAMING_SNAKE_CASE ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( "You cannot infer task automatically within `pipeline` when using offline mode" ,result.stderr.decode().replace("\n" ,"" ) ,) @require_torch def _UpperCAmelCase ( self : Any ): UpperCAmelCase = "\nfrom transformers import AutoModel\n " UpperCAmelCase = "\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n " # baseline - just load from_pretrained with normal network UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run] )] # should succeed UpperCAmelCase = self.get_env() UpperCAmelCase = subprocess.run(__SCREAMING_SNAKE_CASE ,env=__SCREAMING_SNAKE_CASE ,check=__SCREAMING_SNAKE_CASE ,capture_output=__SCREAMING_SNAKE_CASE ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCAmelCase = "1" UpperCAmelCase = subprocess.run(__SCREAMING_SNAKE_CASE ,env=__SCREAMING_SNAKE_CASE ,check=__SCREAMING_SNAKE_CASE ,capture_output=__SCREAMING_SNAKE_CASE ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() )
405
1
"""simple docstring""" def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = 0 UpperCAmelCase_ = len(lowerCAmelCase__ ) for i in range(n - 1 ): for j in range(i + 1 , lowerCAmelCase__ ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def a__ ( lowerCAmelCase__ ): if len(lowerCAmelCase__ ) <= 1: return arr, 0 UpperCAmelCase_ = len(lowerCAmelCase__ ) // 2 UpperCAmelCase_ = arr[0:mid] UpperCAmelCase_ = arr[mid:] UpperCAmelCase_ , UpperCAmelCase_ = count_inversions_recursive(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = count_inversions_recursive(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = _count_cross_inversions(lowerCAmelCase__ , lowerCAmelCase__ ) UpperCAmelCase_ = inversion_p + inversions_q + cross_inversions return c, num_inversions def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase_ = [] UpperCAmelCase_ = UpperCAmelCase_ = UpperCAmelCase_ = 0 while i < len(lowerCAmelCase__ ) and j < len(lowerCAmelCase__ ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(lowerCAmelCase__ ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(lowerCAmelCase__ ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def a__ ( ): UpperCAmelCase_ = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) UpperCAmelCase_ = count_inversions_bf(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = count_inversions_recursive(lowerCAmelCase__ ) assert num_inversions_bf == num_inversions_recursive == 8 print("number of inversions = " , lowerCAmelCase__ ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() UpperCAmelCase_ = count_inversions_bf(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = count_inversions_recursive(lowerCAmelCase__ ) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = " , lowerCAmelCase__ ) # an empty list should also have zero inversions UpperCAmelCase_ = [] UpperCAmelCase_ = count_inversions_bf(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = count_inversions_recursive(lowerCAmelCase__ ) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = " , lowerCAmelCase__ ) if __name__ == "__main__": main()
82
def lowercase_ ( _UpperCamelCase ): '''simple docstring''' __lowercase = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) __lowercase = hex_num[0] == '''-''' if is_negative: __lowercase = hex_num[1:] try: __lowercase = int(_UpperCamelCase , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) __lowercase = '''''' while int_num > 0: __lowercase = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
639
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase : str = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' warnings.warn( 'The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use SegformerImageProcessor instead.' , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
293
"""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 UpperCamelCase : Optional[int] = logging.get_logger(__name__) UpperCamelCase : int = { "EleutherAI/gpt-j-6B": "https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): lowercase = "gptj" lowercase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , __UpperCAmelCase=5_0400 , __UpperCAmelCase=2048 , __UpperCAmelCase=4096 , __UpperCAmelCase=28 , __UpperCAmelCase=16 , __UpperCAmelCase=64 , __UpperCAmelCase=None , __UpperCAmelCase="gelu_new" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=0.0_2 , __UpperCAmelCase=True , __UpperCAmelCase=5_0256 , __UpperCAmelCase=5_0256 , __UpperCAmelCase=False , **__UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = vocab_size __UpperCamelCase = n_positions __UpperCamelCase = n_embd __UpperCamelCase = n_layer __UpperCamelCase = n_head __UpperCamelCase = n_inner __UpperCamelCase = rotary_dim __UpperCamelCase = activation_function __UpperCamelCase = resid_pdrop __UpperCamelCase = embd_pdrop __UpperCamelCase = attn_pdrop __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = initializer_range __UpperCamelCase = use_cache __UpperCamelCase = bos_token_id __UpperCamelCase = eos_token_id super().__init__( bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , tie_word_embeddings=__UpperCAmelCase , **__UpperCAmelCase ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase = "default" , __UpperCAmelCase = None , __UpperCAmelCase = 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 = 0 @property def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='inputs' ) __UpperCamelCase = {0: 'batch', 1: 'past_sequence + sequence'} else: __UpperCamelCase = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase ( self ): '''simple docstring''' return self._config.n_layer @property def UpperCAmelCase ( self ): '''simple docstring''' return self._config.n_head def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = -1 , __UpperCAmelCase = -1 , __UpperCAmelCase = False , __UpperCAmelCase = None , ): '''simple docstring''' __UpperCamelCase = 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 = 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 = common_inputs['input_ids'].shape # Not using the same length for past_key_values __UpperCamelCase = seqlen + 2 __UpperCamelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __UpperCamelCase = [ (torch.zeros(__UpperCAmelCase ), torch.zeros(__UpperCAmelCase )) for _ in range(self.num_layers ) ] __UpperCamelCase = common_inputs['attention_mask'] if self.use_past: __UpperCamelCase = ordered_inputs['attention_mask'].dtype __UpperCamelCase = torch.cat( [ordered_inputs['attention_mask'], torch.ones(__UpperCAmelCase , __UpperCAmelCase , dtype=__UpperCAmelCase )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase ( self ): '''simple docstring''' return 13
293
1
'''simple docstring''' from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("""socket.socket""" ) @patch("""builtins.open""" ) def lowerCamelCase__ ( __lowercase , __lowercase ): # ===== initialization ===== snake_case : str = Mock() snake_case : Tuple = conn, Mock() snake_case : Optional[Any] = iter([1, None] ) snake_case : Optional[Any] = lambda __lowercase : next(__lowercase ) # ===== invoke ===== send_file(filename="""mytext.txt""" , testing=__lowercase ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
116
'''simple docstring''' from ..utils import DummyObject, requires_backends class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Any = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Tuple: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Tuple: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Dict: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Optional[int] = ["""flax"""] def __init__( self ,*__a ,**__a ) -> List[Any]: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> List[str]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> str: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Any = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Any: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> List[Any]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Any: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : List[str] = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Optional[Any]: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Dict: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> int: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : int = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Optional[int]: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Optional[Any]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> List[str]: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Dict = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Optional[Any]: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> List[Any]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> int: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Union[str, Any] = ["""flax"""] def __init__( self ,*__a ,**__a ) -> List[str]: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Optional[Any]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> str: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Optional[Any] = ["""flax"""] def __init__( self ,*__a ,**__a ) -> str: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> str: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Union[str, Any]: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : List[Any] = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Union[str, Any]: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Any: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Optional[Any]: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Dict = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Dict: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> List[str]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Optional[Any]: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : List[str] = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Tuple: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Tuple: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Optional[int]: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Tuple = ["""flax"""] def __init__( self ,*__a ,**__a ) -> List[str]: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Union[str, Any]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> Dict: requires_backends(cls ,["""flax"""] ) class _a (metaclass=a__ ): '''simple docstring''' lowerCAmelCase_ : Tuple = ["""flax"""] def __init__( self ,*__a ,**__a ) -> Tuple: requires_backends(self ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> List[str]: requires_backends(cls ,["""flax"""] ) @classmethod def snake_case_ ( cls ,*__a ,**__a ) -> int: requires_backends(cls ,["""flax"""] )
116
1
from pathlib import Path import numpy as np from PIL import Image def _A (UpperCamelCase : int ) ->str: '''simple docstring''' lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ : Tuple = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2_989 * r + 0.5_870 * g + 0.1_140 * b def _A (UpperCamelCase : Optional[int] ) ->Optional[Any]: '''simple docstring''' return (gray > 127) & (gray <= 255) def _A (UpperCamelCase : Optional[int] , UpperCamelCase : Dict ) ->str: '''simple docstring''' lowerCamelCase__ : List[Any] = np.zeros_like(A_ ) lowerCamelCase__ : Tuple = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image lowerCamelCase__ : str = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): lowerCamelCase__ : Tuple = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() lowerCamelCase__ : List[Any] = int(summation > 0 ) return output if __name__ == "__main__": # read original image _lowercase = Path(__file__).resolve().parent / 'image_data' / 'lena.jpg' _lowercase = np.array(Image.open(lena_path)) # kernel to be applied _lowercase = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) _lowercase = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image _lowercase = Image.fromarray(output).convert('''RGB''') pil_img.save('''result_dilation.png''')
710
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask _lowercase = logging.getLogger(__name__) class __A ( A_ ): UpperCamelCase :Optional[int] = '''token-classification''' def __init__(self , __magic_name__ ): if type(__magic_name__ ) == dict: lowerCamelCase__ : Any = Namespace(**__magic_name__ ) lowerCamelCase__ : str = import_module("""tasks""" ) try: lowerCamelCase__ : Optional[Any] = getattr(__magic_name__ , hparams.task_type ) lowerCamelCase__ : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) lowerCamelCase__ : Any = self.token_classification_task.get_labels(hparams.labels ) lowerCamelCase__ : Tuple = CrossEntropyLoss().ignore_index super().__init__(__magic_name__ , len(self.labels ) , self.mode ) def _snake_case (self , **__magic_name__ ): return self.model(**__magic_name__ ) def _snake_case (self , __magic_name__ , __magic_name__ ): lowerCamelCase__ : Tuple = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": lowerCamelCase__ : Union[str, Any] = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids lowerCamelCase__ : List[str] = self(**__magic_name__ ) lowerCamelCase__ : Dict = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def _snake_case (self ): lowerCamelCase__ : Dict = self.hparams for mode in ["train", "dev", "test"]: lowerCamelCase__ : List[str] = self._feature_file(__magic_name__ ) if os.path.exists(__magic_name__ ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , __magic_name__ ) lowerCamelCase__ : Union[str, Any] = torch.load(__magic_name__ ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) lowerCamelCase__ : int = self.token_classification_task.read_examples_from_file(args.data_dir , __magic_name__ ) lowerCamelCase__ : Tuple = self.token_classification_task.convert_examples_to_features( __magic_name__ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["""xlnet"""] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["""xlnet"""] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(self.config.model_type in ["""xlnet"""] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("""Saving features into cached file %s""" , __magic_name__ ) torch.save(__magic_name__ , __magic_name__ ) def _snake_case (self , __magic_name__ , __magic_name__ , __magic_name__ = False ): lowerCamelCase__ : Any = self._feature_file(__magic_name__ ) logger.info("""Loading features from cached file %s""" , __magic_name__ ) lowerCamelCase__ : Optional[Any] = torch.load(__magic_name__ ) lowerCamelCase__ : Tuple = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) lowerCamelCase__ : Optional[Any] = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: lowerCamelCase__ : str = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: lowerCamelCase__ : int = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) lowerCamelCase__ : Any = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) , batch_size=__magic_name__ ) def _snake_case (self , __magic_name__ , __magic_name__ ): """Compute validation""" "" lowerCamelCase__ : Optional[int] = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": lowerCamelCase__ : Tuple = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids lowerCamelCase__ : str = self(**__magic_name__ ) lowerCamelCase__ ,lowerCamelCase__ : List[Any] = outputs[:2] lowerCamelCase__ : List[Any] = logits.detach().cpu().numpy() lowerCamelCase__ : Dict = inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _snake_case (self , __magic_name__ ): lowerCamelCase__ : List[str] = torch.stack([x["""val_loss"""] for x in outputs] ).mean() lowerCamelCase__ : Optional[int] = np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) lowerCamelCase__ : List[str] = np.argmax(__magic_name__ , axis=2 ) lowerCamelCase__ : Optional[Any] = np.concatenate([x["""target"""] for x in outputs] , axis=0 ) lowerCamelCase__ : Optional[int] = dict(enumerate(self.labels ) ) lowerCamelCase__ : List[str] = [[] for _ in range(out_label_ids.shape[0] )] lowerCamelCase__ : Any = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) lowerCamelCase__ : Tuple = { """val_loss""": val_loss_mean, """accuracy_score""": accuracy_score(__magic_name__ , __magic_name__ ), """precision""": precision_score(__magic_name__ , __magic_name__ ), """recall""": recall_score(__magic_name__ , __magic_name__ ), """f1""": fa_score(__magic_name__ , __magic_name__ ), } lowerCamelCase__ : Dict = dict(results.items() ) lowerCamelCase__ : str = results return ret, preds_list, out_label_list def _snake_case (self , __magic_name__ ): # when stable lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ : str = self._eval_end(__magic_name__ ) lowerCamelCase__ : Union[str, Any] = ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _snake_case (self , __magic_name__ ): # updating to test_epoch_end instead of deprecated test_end lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ : Union[str, Any] = self._eval_end(__magic_name__ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 lowerCamelCase__ : List[Any] = ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _snake_case (__magic_name__ , __magic_name__ ): # Add NER specific options BaseTransformer.add_model_specific_args(__magic_name__ , __magic_name__ ) parser.add_argument( """--task_type""" , default="""NER""" , type=__magic_name__ , help="""Task type to fine tune in training (e.g. NER, POS, etc)""" ) parser.add_argument( """--max_seq_length""" , default=128 , type=__magic_name__ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--labels""" , default="""""" , type=__magic_name__ , help="""Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.""" , ) parser.add_argument( """--gpus""" , default=0 , type=__magic_name__ , 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 if __name__ == "__main__": _lowercase = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) _lowercase = NERTransformer.add_model_specific_args(parser, os.getcwd()) _lowercase = parser.parse_args() _lowercase = NERTransformer(args) _lowercase = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 _lowercase = sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True)) _lowercase = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
96
0
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( lowercase__ , unittest.TestCase ): A__ = XLNetTokenizer A__ = XLNetTokenizerFast A__ = True A__ = True def __magic_name__( self ): super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ : Any = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__( self ): lowerCAmelCase__ : List[Any] = '<s>' lowerCAmelCase__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def __magic_name__( self ): lowerCAmelCase__ : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<eod>''' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1006 ) def __magic_name__( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def __magic_name__( self ): lowerCAmelCase__ : Optional[Any] = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ : int = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ : List[str] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) lowerCAmelCase__ : List[str] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ : List[Any] = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def __magic_name__( self ): lowerCAmelCase__ : Union[str, Any] = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ : List[str] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + '''''', '''i''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''▁he''', '''ll''', '''o'''] ) def __magic_name__( self ): lowerCAmelCase__ : Tuple = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) @slow def __magic_name__( self ): lowerCAmelCase__ : Optional[int] = XLNetTokenizer.from_pretrained('''xlnet-base-cased''' ) lowerCAmelCase__ : Any = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ : Dict = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ : int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ : Dict = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def __magic_name__( self ): # fmt: off lowerCAmelCase__ : Optional[Any] = {'input_ids': [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2178, 27, 1064, 22, 956, 13, 1_1101, 1429, 5854, 2_4313, 1_8953, 40, 422, 2_4366, 68, 1758, 37, 1_0483, 1_4257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 1_3894, 3380, 23, 95, 18, 1_7634, 2288, 9, 4, 3]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='''xlnet-base-cased''' , revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' , )
678
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , ) -> Optional[int]: a_ : Any = parent a_ : Tuple = 1_3 a_ : Any = 7 a_ : Any = True a_ : Tuple = True a_ : List[str] = True a_ : List[Any] = True a_ : Dict = True a_ : Union[str, Any] = False a_ : Tuple = False a_ : Union[str, Any] = False a_ : List[str] = 2 a_ : Union[str, Any] = 9_9 a_ : Any = 0 a_ : Dict = 3_2 a_ : Dict = 2 a_ : int = 4 a_ : List[str] = 0.1 a_ : str = 0.1 a_ : Optional[Any] = 5_1_2 a_ : Optional[Any] = 1_6 a_ : Optional[Any] = 2 a_ : str = 0.02 a_ : Tuple = 3 a_ : List[str] = 4 a_ : List[Any] = 'last' a_ : Tuple = True a_ : str = None a_ : Optional[Any] = 0 def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Dict = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) a_ : Tuple = None if self.use_input_lengths: a_ : List[Any] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length a_ : Optional[int] = None if self.use_token_type_ids: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) a_ : str = None a_ : Any = None a_ : Optional[Any] = None if self.use_labels: a_ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : Optional[Any] = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : str = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] , ) -> int: a_ : str = TFFlaubertModel(config=SCREAMING_SNAKE_CASE__ ) a_ : str = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} a_ : str = model(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = [input_ids, input_mask] a_ : List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , ) -> List[Any]: a_ : Tuple = TFFlaubertWithLMHeadModel(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} a_ : List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> List[str]: a_ : Optional[Any] = TFFlaubertForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE__ ) a_ : Any = {'input_ids': input_ids, 'lengths': input_lengths} a_ : List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> List[Any]: a_ : List[str] = TFFlaubertForSequenceClassification(SCREAMING_SNAKE_CASE__ ) a_ : Dict = {'input_ids': input_ids, 'lengths': input_lengths} a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Optional[Any]: a_ : str = self.num_labels a_ : Optional[int] = TFFlaubertForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) a_ : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} a_ : str = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Dict: a_ : Tuple = self.num_choices a_ : List[Any] = TFFlaubertForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) a_ : List[str] = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) a_ : List[str] = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) a_ : List[Any] = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } a_ : Tuple = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Any = config_and_inputs a_ : Union[str, Any] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'langs': token_type_ids, 'lengths': input_lengths, } return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : List[Any] = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) snake_case__ : Dict = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable snake_case__ : List[Any] = ( { '''feature-extraction''': TFFlaubertModel, '''fill-mask''': TFFlaubertWithLMHeadModel, '''question-answering''': TFFlaubertForQuestionAnsweringSimple, '''text-classification''': TFFlaubertForSequenceClassification, '''token-classification''': TFFlaubertForTokenClassification, '''zero-shot''': TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) snake_case__ : Any = False snake_case__ : Optional[Any] = False def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Dict: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: a_ : Tuple = TFFlaubertModelTester(self ) a_ : Any = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , emb_dim=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : Any = TFFlaubertModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_tf @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> str: a_ : List[str] = TFFlaubertModel.from_pretrained('jplu/tf-flaubert-small-cased' ) a_ : Optional[Any] = tf.convert_to_tensor( [[0, 1_5_8, 7_3_5, 2_5_9_2, 1_4_2_4, 6_7_2_7, 8_2, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" a_ : Tuple = model(SCREAMING_SNAKE_CASE__ )[0] a_ : List[Any] = tf.TensorShape((1, 8, 5_1_2) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. a_ : int = tf.convert_to_tensor( [ [ [-1.8768773, -1.566555, 0.27072418], [-1.6920038, -0.5873505, 1.9329599], [-2.9563985, -1.6993835, 1.7972052], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
570
0
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class __snake_case( __A ): def __init__( self ): '''simple docstring''' self.test() def A ( self ): '''simple docstring''' _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = False while not completed: if counter == 1: self.reset() _SCREAMING_SNAKE_CASE = self.advance() if not self.does_advance(A_ ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.update(A_ ) counter += 1 if counter > 10_000: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def A ( self ): '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A ( self , A_ ): '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A ( self , A_ ): '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A ( self ): '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A ( self ): '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A ( self , A_=False ): '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class __snake_case( __A ): def __init__( self , A_ ): '''simple docstring''' super(A_ , self ).__init__() if not isinstance(A_ , A_ ) or len(A_ ) == 0: raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(A_ , A_ ) or token_id < 0) for token_id in token_ids ): raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) _SCREAMING_SNAKE_CASE = token_ids _SCREAMING_SNAKE_CASE = len(self.token_ids ) _SCREAMING_SNAKE_CASE = -1 # the index of the currently fulfilled step _SCREAMING_SNAKE_CASE = False def A ( self ): '''simple docstring''' if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def A ( self , A_ ): '''simple docstring''' if not isinstance(A_ , A_ ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(A_ )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def A ( self , A_ ): '''simple docstring''' if not isinstance(A_ , A_ ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(A_ )}''' ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False if self.does_advance(A_ ): self.fulfilled_idx += 1 _SCREAMING_SNAKE_CASE = True if self.fulfilled_idx == (self.seqlen - 1): _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = completed else: # failed to make progress. _SCREAMING_SNAKE_CASE = True self.reset() return stepped, completed, reset def A ( self ): '''simple docstring''' _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = 0 def A ( self ): '''simple docstring''' return self.seqlen - (self.fulfilled_idx + 1) def A ( self , A_=False ): '''simple docstring''' _SCREAMING_SNAKE_CASE = PhrasalConstraint(self.token_ids ) if stateful: _SCREAMING_SNAKE_CASE = self.seqlen _SCREAMING_SNAKE_CASE = self.fulfilled_idx _SCREAMING_SNAKE_CASE = self.completed return new_constraint class __snake_case: def __init__( self , A_ , A_=True ): '''simple docstring''' _SCREAMING_SNAKE_CASE = max([len(A_ ) for one in nested_token_ids] ) _SCREAMING_SNAKE_CASE = {} for token_ids in nested_token_ids: _SCREAMING_SNAKE_CASE = root for tidx, token_id in enumerate(A_ ): if token_id not in level: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = level[token_id] if no_subsets and self.has_subsets(A_ , A_ ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' F''' {nested_token_ids}.''' ) _SCREAMING_SNAKE_CASE = root def A ( self , A_ ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.trie for current_token in current_seq: _SCREAMING_SNAKE_CASE = start[current_token] _SCREAMING_SNAKE_CASE = list(start.keys() ) return next_tokens def A ( self , A_ ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.next_tokens(A_ ) return len(A_ ) == 0 def A ( self , A_ ): '''simple docstring''' _SCREAMING_SNAKE_CASE = list(root.values() ) if len(A_ ) == 0: return 1 else: return sum([self.count_leaves(A_ ) for nn in next_nodes] ) def A ( self , A_ , A_ ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.count_leaves(A_ ) return len(A_ ) != leaf_count class __snake_case( __A ): def __init__( self , A_ ): '''simple docstring''' super(A_ , self ).__init__() if not isinstance(A_ , A_ ) or len(A_ ) == 0: raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(A_ , A_ ) for token_ids in nested_token_ids ): raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(A_ , A_ ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) _SCREAMING_SNAKE_CASE = DisjunctiveTrie(A_ ) _SCREAMING_SNAKE_CASE = nested_token_ids _SCREAMING_SNAKE_CASE = self.trie.max_height _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = False def A ( self ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.trie.next_tokens(self.current_seq ) if len(A_ ) == 0: return None else: return token_list def A ( self , A_ ): '''simple docstring''' if not isinstance(A_ , A_ ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(A_ )}''' ) _SCREAMING_SNAKE_CASE = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def A ( self , A_ ): '''simple docstring''' if not isinstance(A_ , A_ ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(A_ )}''' ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False if self.does_advance(A_ ): self.current_seq.append(A_ ) _SCREAMING_SNAKE_CASE = True else: _SCREAMING_SNAKE_CASE = True self.reset() _SCREAMING_SNAKE_CASE = self.trie.reached_leaf(self.current_seq ) _SCREAMING_SNAKE_CASE = completed return stepped, completed, reset def A ( self ): '''simple docstring''' _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = [] def A ( self ): '''simple docstring''' if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def A ( self , A_=False ): '''simple docstring''' _SCREAMING_SNAKE_CASE = DisjunctiveConstraint(self.token_ids ) if stateful: _SCREAMING_SNAKE_CASE = self.seqlen _SCREAMING_SNAKE_CASE = self.current_seq _SCREAMING_SNAKE_CASE = self.completed return new_constraint class __snake_case: def __init__( self , A_ ): '''simple docstring''' _SCREAMING_SNAKE_CASE = constraints # max # of steps required to fulfill a given constraint _SCREAMING_SNAKE_CASE = max([c.seqlen for c in constraints] ) _SCREAMING_SNAKE_CASE = len(A_ ) _SCREAMING_SNAKE_CASE = False self.init_state() def A ( self ): '''simple docstring''' _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = [constraint.copy(stateful=A_ ) for constraint in self.constraints] def A ( self ): '''simple docstring''' _SCREAMING_SNAKE_CASE = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def A ( self ): '''simple docstring''' _SCREAMING_SNAKE_CASE = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" _SCREAMING_SNAKE_CASE = constraint.advance() if isinstance(A_ , A_ ): token_list.append(A_ ) elif isinstance(A_ , A_ ): token_list.extend(A_ ) else: _SCREAMING_SNAKE_CASE = self.inprogress_constraint.advance() if isinstance(A_ , A_ ): token_list.append(A_ ) elif isinstance(A_ , A_ ): token_list.extend(A_ ) if len(A_ ) == 0: return None else: return token_list def A ( self , A_ ): '''simple docstring''' self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.add(A_ ) # the entire list of constraints are fulfilled if self.completed: break def A ( self , A_ ): '''simple docstring''' if not isinstance(A_ , A_ ): raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False, False if self.completed: _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.inprogress_constraint.update(A_ ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=A_ ) ) _SCREAMING_SNAKE_CASE = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) _SCREAMING_SNAKE_CASE = None if len(self.pending_constraints ) == 0: # we're done! _SCREAMING_SNAKE_CASE = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(A_ ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = pending_constraint.update(A_ ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(A_ ) _SCREAMING_SNAKE_CASE = None if not complete and stepped: _SCREAMING_SNAKE_CASE = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". _SCREAMING_SNAKE_CASE = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. _SCREAMING_SNAKE_CASE = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def A ( self , A_=True ): '''simple docstring''' _SCREAMING_SNAKE_CASE = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: _SCREAMING_SNAKE_CASE = [ constraint.copy(stateful=A_ ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: _SCREAMING_SNAKE_CASE = self.inprogress_constraint.copy(stateful=A_ ) _SCREAMING_SNAKE_CASE = [constraint.copy() for constraint in self.pending_constraints] return new_state
168
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def A__ ( UpperCamelCase__ ): '''simple docstring''' if ( (cp >= 0x4E00 and cp <= 0x9FFF) or (cp >= 0x3400 and cp <= 0x4DBF) # or (cp >= 0x20000 and cp <= 0x2A6DF) # or (cp >= 0x2A700 and cp <= 0x2B73F) # or (cp >= 0x2B740 and cp <= 0x2B81F) # or (cp >= 0x2B820 and cp <= 0x2CEAF) # or (cp >= 0xF900 and cp <= 0xFAFF) or (cp >= 0x2F800 and cp <= 0x2FA1F) # ): # return True return False def A__ ( UpperCamelCase__ ): '''simple docstring''' for char in word: _SCREAMING_SNAKE_CASE = ord(UpperCamelCase__ ) if not _is_chinese_char(UpperCamelCase__ ): return 0 return 1 def A__ ( UpperCamelCase__ ): '''simple docstring''' _SCREAMING_SNAKE_CASE = set() for token in tokens: _SCREAMING_SNAKE_CASE = len(UpperCamelCase__ ) > 1 and is_chinese(UpperCamelCase__ ) if chinese_word: word_set.add(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = list(UpperCamelCase__ ) return word_list def A__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if not chinese_word_set: return bert_tokens _SCREAMING_SNAKE_CASE = max([len(UpperCamelCase__ ) for w in chinese_word_set] ) _SCREAMING_SNAKE_CASE = bert_tokens _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0, len(UpperCamelCase__ ) while start < end: _SCREAMING_SNAKE_CASE = True if is_chinese(bert_word[start] ): _SCREAMING_SNAKE_CASE = min(end - start , UpperCamelCase__ ) for i in range(UpperCamelCase__ , 1 , -1 ): _SCREAMING_SNAKE_CASE = ''''''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _SCREAMING_SNAKE_CASE = '''##''' + bert_word[j] _SCREAMING_SNAKE_CASE = start + i _SCREAMING_SNAKE_CASE = False break if single_word: start += 1 return bert_word def A__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _SCREAMING_SNAKE_CASE = [] for i in range(0 , len(UpperCamelCase__ ) , 100 ): _SCREAMING_SNAKE_CASE = ltp_tokenizer.pipeline(lines[i : i + 100] , tasks=['''cws'''] ).cws _SCREAMING_SNAKE_CASE = [get_chinese_word(UpperCamelCase__ ) for r in res] ltp_res.extend(UpperCamelCase__ ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = [] for i in range(0 , len(UpperCamelCase__ ) , 100 ): _SCREAMING_SNAKE_CASE = bert_tokenizer(lines[i : i + 100] , add_special_tokens=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=512 ) bert_res.extend(res['''input_ids'''] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = [] for input_ids, chinese_word in zip(UpperCamelCase__ , UpperCamelCase__ ): _SCREAMING_SNAKE_CASE = [] for id in input_ids: _SCREAMING_SNAKE_CASE = bert_tokenizer._convert_id_to_token(UpperCamelCase__ ) input_tokens.append(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = add_sub_symbol(UpperCamelCase__ , UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(UpperCamelCase__ ): if token[:2] == "##": _SCREAMING_SNAKE_CASE = token[2:] # save chinese tokens' pos if len(UpperCamelCase__ ) == 1 and _is_chinese_char(ord(UpperCamelCase__ ) ): ref_id.append(UpperCamelCase__ ) ref_ids.append(UpperCamelCase__ ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) return ref_ids def A__ ( UpperCamelCase__ ): '''simple docstring''' with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f: _SCREAMING_SNAKE_CASE = f.readlines() _SCREAMING_SNAKE_CASE = [line.strip() for line in data if len(UpperCamelCase__ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _SCREAMING_SNAKE_CASE = LTP(args.ltp ) # faster in GPU device _SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained(args.bert ) _SCREAMING_SNAKE_CASE = prepare_ref(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f: _SCREAMING_SNAKE_CASE = [json.dumps(UpperCamelCase__ ) + '''\n''' for ref in ref_ids] f.writelines(UpperCamelCase__ ) if __name__ == "__main__": lowerCamelCase : Optional[Any] = argparse.ArgumentParser(description="""prepare_chinese_ref""") parser.add_argument( """--file_name""", required=False, type=str, default="""./resources/chinese-demo.txt""", help="""file need process, same as training data in lm""", ) parser.add_argument( """--ltp""", required=False, type=str, default="""./resources/ltp""", help="""resources for LTP tokenizer, usually a path""", ) parser.add_argument( """--bert""", required=False, type=str, default="""./resources/robert""", help="""resources for Bert tokenizer""", ) parser.add_argument( """--save_path""", required=False, type=str, default="""./resources/ref.txt""", help="""path to save res""", ) lowerCamelCase : str = parser.parse_args() main(args)
168
1
'''simple docstring''' from __future__ import annotations def _UpperCamelCase (_lowerCamelCase : int , _lowerCamelCase : int )-> list[str]: '''simple docstring''' if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __snake_case = number_of_bytes // partitions __snake_case = [] for i in range(_lowerCamelCase ): __snake_case = i * bytes_per_partition + 1 __snake_case = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
24
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class lowerCAmelCase ( __lowerCAmelCase , unittest.TestCase): __lowercase : int = BarthezTokenizer __lowercase : Any = BarthezTokenizerFast __lowercase : Dict = True __lowercase : Optional[int] = True def lowerCAmelCase ( self ) -> Dict: '''simple docstring''' super().setUp() __snake_case = BarthezTokenizerFast.from_pretrained('''moussaKam/mbarthez''' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=__SCREAMING_SNAKE_CASE ) __snake_case = tokenizer def lowerCAmelCase ( self ) -> Dict: '''simple docstring''' __snake_case = '''<pad>''' __snake_case = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> Optional[int]: '''simple docstring''' __snake_case = 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(__SCREAMING_SNAKE_CASE ) , 10_1122 ) def lowerCAmelCase ( self ) -> Any: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 10_1122 ) @require_torch def lowerCAmelCase ( self ) -> Tuple: '''simple docstring''' __snake_case = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] __snake_case = [0, 57, 3018, 7_0307, 91, 2] __snake_case = self.tokenizer( __SCREAMING_SNAKE_CASE , max_length=len(__SCREAMING_SNAKE_CASE ) , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) __snake_case = batch.input_ids.tolist()[0] self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' if not self.test_rust_tokenizer: return __snake_case = self.get_tokenizer() __snake_case = self.get_rust_tokenizer() __snake_case = '''I was born in 92000, and this is falsé.''' __snake_case = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) __snake_case = rust_tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __snake_case = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) __snake_case = rust_tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __snake_case = self.get_rust_tokenizer() __snake_case = tokenizer.encode(__SCREAMING_SNAKE_CASE ) __snake_case = rust_tokenizer.encode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @slow def lowerCAmelCase ( self ) -> int: '''simple docstring''' __snake_case = {'''input_ids''': [[0, 490, 1_4328, 4507, 354, 47, 4_3669, 95, 25, 7_8117, 2_0215, 1_9779, 190, 22, 400, 4, 3_5343, 8_0310, 603, 86, 2_4937, 105, 3_3438, 9_4762, 196, 3_9642, 7, 15, 1_5933, 173, 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], [0, 1_0534, 87, 25, 66, 3358, 196, 5_5289, 8, 8_2961, 81, 2204, 7_5203, 7, 15, 763, 1_2956, 216, 178, 1_4328, 9595, 1377, 6_9693, 7, 448, 7_1021, 196, 1_8106, 1437, 1_3974, 108, 9083, 4, 4_9315, 7, 39, 86, 1326, 2793, 4_6333, 4, 448, 196, 7_4588, 7, 4_9315, 7, 39, 21, 822, 3_8470, 74, 21, 6_6723, 6_2480, 8, 2_2050, 5, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 # moussaKam/mbarthez is a french model. So we also use french texts. __snake_case = [ '''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=__SCREAMING_SNAKE_CASE , model_name='''moussaKam/mbarthez''' , revision='''c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6''' , sequences=__SCREAMING_SNAKE_CASE , )
24
1
'''simple docstring''' import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class _snake_case ( unittest.TestCase ): @require_torch def __UpperCamelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE:Optional[int] = pipeline( task="zero-shot-audio-classification" ,model="hf-internal-testing/tiny-clap-htsat-unfused" ) SCREAMING_SNAKE_CASE:Optional[int] = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE:Union[str, Any] = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE:Union[str, Any] = audio_classifier(SCREAMING_SNAKE_CASE__ ,candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}] ,) @unittest.skip("No models are available in TF" ) def __UpperCamelCase ( self : Tuple ): pass @slow @require_torch def __UpperCamelCase ( self : Tuple ): SCREAMING_SNAKE_CASE:Any = pipeline( task="zero-shot-audio-classification" ,model="laion/clap-htsat-unfused" ,) # This is an audio of a dog SCREAMING_SNAKE_CASE:str = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE:List[str] = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE:Any = audio_classifier(SCREAMING_SNAKE_CASE__ ,candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ] ,) SCREAMING_SNAKE_CASE:Tuple = audio_classifier([audio] * 5 ,candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5 ,) SCREAMING_SNAKE_CASE:int = audio_classifier( [audio] * 5 ,candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ,batch_size=5 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5 ,) @unittest.skip("No models are available in TF" ) def __UpperCamelCase ( self : str ): pass
465
'''simple docstring''' from ....utils import logging A_ = logging.get_logger(__name__) class _snake_case ( _a ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_048 ): SCREAMING_SNAKE_CASE:int = config.__dict__ SCREAMING_SNAKE_CASE:List[str] = modal_hidden_size if num_labels: SCREAMING_SNAKE_CASE:str = num_labels
465
1
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function __A : List[Any] = 1.0_5457_1817e-34 # unit of ℏ : J * s __A : List[str] = 3e8 # unit of c : m * s^-1 def __a ( A__ : float , A__ : float , A__ : float ): if (force, area, distance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if force < 0: raise ValueError("Magnitude of force can not be negative" ) if distance < 0: raise ValueError("Distance can not be negative" ) if area < 0: raise ValueError("Area can not be negative" ) if force == 0: SCREAMING_SNAKE_CASE = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: SCREAMING_SNAKE_CASE = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: SCREAMING_SNAKE_CASE = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("One and only one argument must be 0" ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
16
def __a ( A__ : float , A__ : float ): if mass < 0: raise ValueError("The mass of a body cannot be negative" ) return 0.5 * mass * abs(A__ ) * abs(A__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
16
1
from collections import namedtuple UpperCamelCase__ = namedtuple("from_to", "from_ to") UpperCamelCase__ = { "cubicmeter": from_to(1, 1), "litre": from_to(0.001, 10_00), "kilolitre": from_to(1, 1), "gallon": from_to(0.00_454, 264.172), "cubicyard": from_to(0.76_455, 1.30_795), "cubicfoot": from_to(0.028, 35.3_147), "cup": from_to(0.000_236_588, 4_226.75), } def UpperCAmelCase__ ( lowercase__ , lowercase__ , lowercase__ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + """, """.join(lowercase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + """, """.join(lowercase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
634
import random def UpperCAmelCase__ ( lowercase__ , lowercase__ , lowercase__ = False ) -> dict: __lowercase = {i: [] for i in range(lowercase__ )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(lowercase__ ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(lowercase__ ): for j in range(i + 1 , lowercase__ ): if random.random() < probability: graph[i].append(lowercase__ ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(lowercase__ ) return graph def UpperCAmelCase__ ( lowercase__ ) -> dict: return { i: [j for j in range(lowercase__ ) if i != j] for i in range(lowercase__ ) } if __name__ == "__main__": import doctest doctest.testmod()
634
1
'''simple docstring''' import warnings from functools import wraps from typing import Callable def __UpperCAmelCase ( lowerCamelCase_) -> Callable: @wraps(lowerCamelCase_) def _inner_fn(*lowerCamelCase_ , **lowerCamelCase_): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , lowerCamelCase_ , ) return fn(*lowerCamelCase_ , **lowerCamelCase_) return _inner_fn
596
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('--user', type=str, default='ubuntu') parser.add_argument('--host', type=str, default='localhost') parser.add_argument('--key_path', type=str, default=None) parser.add_argument('--instance', type=str, default='V100:1') parser.add_argument('--provider', type=str, default='cheapest') parser.add_argument('--use_spot', type=bool, default=False) parser.add_argument('--example', type=str, default='pytorch/text-generation/run_generation.py') lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('Cannot specify both BYO and on-demand cluster args') lowerCAmelCase__ = rh.cluster( name='rh-cluster', ips=[args.host], ssh_creds={'ssh_user': args.user, 'ssh_private_key': args.key_path} ) else: lowerCAmelCase__ = rh.cluster( name='rh-cluster', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowerCAmelCase__ = args.example.rsplit('/', 1)[0] # Set up remote environment cluster.install_packages(['pip:./']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f'''pip install -r transformers/examples/{example_dir}/requirements.txt''']) cluster.run(['pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f'''python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}''']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
596
1
'''simple docstring''' from __future__ import annotations from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self , a_ ) -> None: lowercase : int = num_of_nodes lowercase : Any = [] lowercase : Tuple = {} def a__ ( self , a_ , a_ , a_ ) -> None: self.m_edges.append([u_node, v_node, weight] ) def a__ ( self , a_ ) -> int: if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def a__ ( self , a_ ) -> None: if self.m_component[u_node] != u_node: for k in self.m_component: lowercase : str = self.find_component(_SCREAMING_SNAKE_CASE ) def a__ ( self , a_ , a_ , a_ ) -> None: if component_size[u_node] <= component_size[v_node]: lowercase : int = v_node component_size[v_node] += component_size[u_node] self.set_component(_SCREAMING_SNAKE_CASE ) elif component_size[u_node] >= component_size[v_node]: lowercase : str = self.find_component(_SCREAMING_SNAKE_CASE ) component_size[u_node] += component_size[v_node] self.set_component(_SCREAMING_SNAKE_CASE ) def a__ ( self ) -> None: lowercase : List[Any] = [] lowercase : int = 0 lowercase : int = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) lowercase : Tuple = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: lowercase , lowercase , lowercase : str = edge lowercase : List[Any] = self.m_component[u] lowercase : Optional[Any] = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): lowercase : int = [u, v, w] for edge in minimum_weight_edge: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowercase , lowercase , lowercase : str = edge lowercase : Optional[int] = self.m_component[u] lowercase : Any = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(F'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 lowercase : Tuple = [-1] * self.m_num_of_nodes print(F'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def _A ( ) -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
713
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
425
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class _lowercase ( unittest.TestCase ): '''simple docstring''' def __init__( self , lowerCamelCase__ , lowerCamelCase__=7 , lowerCamelCase__=3 , lowerCamelCase__=30 , lowerCamelCase__=400 , lowerCamelCase__=True , lowerCamelCase__=None , lowerCamelCase__=True , lowerCamelCase__=[0.5, 0.5, 0.5] , lowerCamelCase__=[0.5, 0.5, 0.5] , lowerCamelCase__=True , lowerCamelCase__=1 / 255 , lowerCamelCase__=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowerCAmelCase_: Dict = size if size is not None else {"shortest_edge": 18, "longest_edge": 1_333} lowerCAmelCase_: Optional[int] = parent lowerCAmelCase_: Optional[Any] = batch_size lowerCAmelCase_: Optional[Any] = num_channels lowerCAmelCase_: Optional[int] = min_resolution lowerCAmelCase_: Tuple = max_resolution lowerCAmelCase_: Optional[Any] = do_resize lowerCAmelCase_: List[str] = size lowerCAmelCase_: Dict = do_normalize lowerCAmelCase_: Tuple = image_mean lowerCAmelCase_: Optional[int] = image_std lowerCAmelCase_: Union[str, Any] = do_rescale lowerCAmelCase_: Optional[int] = rescale_factor lowerCAmelCase_: List[Any] = do_pad def _a ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _a ( self , lowerCamelCase__ , lowerCamelCase__=False ): if not batched: lowerCAmelCase_: Optional[Any] = image_inputs[0] if isinstance(lowerCamelCase__ , Image.Image ): lowerCAmelCase_ , lowerCAmelCase_: Dict = image.size else: lowerCAmelCase_ , lowerCAmelCase_: Any = image.shape[1], image.shape[2] if w < h: lowerCAmelCase_: List[Any] = int(self.size["shortest_edge"] * h / w ) lowerCAmelCase_: Any = self.size["shortest_edge"] elif w > h: lowerCAmelCase_: int = self.size["shortest_edge"] lowerCAmelCase_: Dict = int(self.size["shortest_edge"] * w / h ) else: lowerCAmelCase_: Optional[int] = self.size["shortest_edge"] lowerCAmelCase_: List[str] = self.size["shortest_edge"] else: lowerCAmelCase_: int = [] for image in image_inputs: lowerCAmelCase_ , lowerCAmelCase_: Tuple = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCAmelCase_: Optional[Any] = max(lowerCamelCase__ , key=lambda lowerCamelCase__ : item[0] )[0] lowerCAmelCase_: List[str] = max(lowerCamelCase__ , key=lambda lowerCamelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _lowercase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE: str = DetaImageProcessor if is_vision_available() else None def _a ( self ): lowerCAmelCase_: Union[str, Any] = DetaImageProcessingTester(self ) @property def _a ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _a ( self ): lowerCAmelCase_: Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase__ , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_pad" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "size" ) ) def _a ( self ): lowerCAmelCase_: List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1_333} ) self.assertEqual(image_processor.do_pad , lowerCamelCase__ ) def _a ( self ): pass def _a ( self ): # Initialize image_processing lowerCAmelCase_: Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase_: Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , Image.Image ) # Test not batched input lowerCAmelCase_: str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase_ , lowerCAmelCase_: Any = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase_ , lowerCAmelCase_: Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) lowerCAmelCase_: Tuple = image_processing(lowerCamelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self ): # Initialize image_processing lowerCAmelCase_: str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase_: str = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , numpify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , np.ndarray ) # Test not batched input lowerCAmelCase_: str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase_ , lowerCAmelCase_: List[str] = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase_: List[str] = image_processing(lowerCamelCase__ , return_tensors="pt" ).pixel_values lowerCAmelCase_ , lowerCAmelCase_: List[str] = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self ): # Initialize image_processing lowerCAmelCase_: Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase_: Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , torchify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , torch.Tensor ) # Test not batched input lowerCAmelCase_: Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCAmelCase_ , lowerCAmelCase_: Any = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase_: List[Any] = image_processing(lowerCamelCase__ , return_tensors="pt" ).pixel_values lowerCAmelCase_ , lowerCAmelCase_: Dict = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _a ( self ): # prepare image and target lowerCAmelCase_: Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: lowerCAmelCase_: List[Any] = json.loads(f.read() ) lowerCAmelCase_: int = {"image_id": 39_769, "annotations": target} # encode them lowerCAmelCase_: List[str] = DetaImageProcessor() lowerCAmelCase_: List[Any] = image_processing(images=lowerCamelCase__ , annotations=lowerCamelCase__ , return_tensors="pt" ) # verify pixel values lowerCAmelCase_: Union[str, Any] = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase__ ) lowerCAmelCase_: int = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase__ , atol=1E-4 ) ) # verify area lowerCAmelCase_: Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase__ ) ) # verify boxes lowerCAmelCase_: Union[str, Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase__ ) lowerCAmelCase_: Tuple = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase__ , atol=1E-3 ) ) # verify image_id lowerCAmelCase_: Optional[int] = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase__ ) ) # verify is_crowd lowerCAmelCase_: int = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase__ ) ) # verify class_labels lowerCAmelCase_: List[Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase__ ) ) # verify orig_size lowerCAmelCase_: Optional[int] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase__ ) ) # verify size lowerCAmelCase_: Union[str, Any] = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase__ ) ) @slow def _a ( self ): # prepare image, target and masks_path lowerCAmelCase_: Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: lowerCAmelCase_: List[Any] = json.loads(f.read() ) lowerCAmelCase_: Optional[Any] = {"file_name": "000000039769.png", "image_id": 39_769, "segments_info": target} lowerCAmelCase_: Union[str, Any] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them lowerCAmelCase_: Union[str, Any] = DetaImageProcessor(format="coco_panoptic" ) lowerCAmelCase_: List[Any] = image_processing(images=lowerCamelCase__ , annotations=lowerCamelCase__ , masks_path=lowerCamelCase__ , return_tensors="pt" ) # verify pixel values lowerCAmelCase_: Tuple = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase__ ) lowerCAmelCase_: str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase__ , atol=1E-4 ) ) # verify area lowerCAmelCase_: Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase__ ) ) # verify boxes lowerCAmelCase_: Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase__ ) lowerCAmelCase_: int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase__ , atol=1E-3 ) ) # verify image_id lowerCAmelCase_: Union[str, Any] = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase__ ) ) # verify is_crowd lowerCAmelCase_: List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase__ ) ) # verify class_labels lowerCAmelCase_: Dict = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase__ ) ) # verify masks lowerCAmelCase_: Optional[int] = 822_873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase__ ) # verify orig_size lowerCAmelCase_: Any = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase__ ) ) # verify size lowerCAmelCase_: Union[str, Any] = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase__ ) )
613
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class _lowercase ( UpperCAmelCase__ ): '''simple docstring''' def _a ( self ): lowerCAmelCase_: Optional[int] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase__ , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase__ , "num_attention_heads" ) ) class _lowercase : '''simple docstring''' def __init__( self , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=64 , lowerCamelCase__=3 , lowerCamelCase__=3 , lowerCamelCase__=2 , lowerCamelCase__=1 , lowerCamelCase__=16 , lowerCamelCase__=[128, 256, 384] , lowerCamelCase__=[4, 6, 8] , lowerCamelCase__=[2, 3, 4] , lowerCamelCase__=[16, 16, 16] , lowerCamelCase__=0 , lowerCamelCase__=[2, 2, 2] , lowerCamelCase__=[2, 2, 2] , lowerCamelCase__=0.0_2 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=2 , ): lowerCAmelCase_: int = parent lowerCAmelCase_: Tuple = batch_size lowerCAmelCase_: List[str] = image_size lowerCAmelCase_: Tuple = num_channels lowerCAmelCase_: Optional[int] = kernel_size lowerCAmelCase_: int = stride lowerCAmelCase_: Optional[int] = padding lowerCAmelCase_: Tuple = hidden_sizes lowerCAmelCase_: Union[str, Any] = num_attention_heads lowerCAmelCase_: Tuple = depths lowerCAmelCase_: Optional[int] = key_dim lowerCAmelCase_: Optional[Any] = drop_path_rate lowerCAmelCase_: List[str] = patch_size lowerCAmelCase_: Any = attention_ratio lowerCAmelCase_: Tuple = mlp_ratio lowerCAmelCase_: Any = initializer_range lowerCAmelCase_: List[str] = [ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] lowerCAmelCase_: Any = is_training lowerCAmelCase_: Optional[int] = use_labels lowerCAmelCase_: Dict = num_labels lowerCAmelCase_: Any = initializer_range def _a ( self ): lowerCAmelCase_: Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase_: Tuple = None if self.use_labels: lowerCAmelCase_: int = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase_: Tuple = self.get_config() return config, pixel_values, labels def _a ( self ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _a ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCAmelCase_: int = LevitModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowerCAmelCase_: Optional[Any] = model(lowerCamelCase__ ) lowerCAmelCase_: Tuple = (self.image_size, self.image_size) lowerCAmelCase_ , lowerCAmelCase_: Optional[int] = image_size[0], image_size[1] for _ in range(4 ): lowerCAmelCase_: Union[str, Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) lowerCAmelCase_: str = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def _a ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCAmelCase_: Tuple = self.num_labels lowerCAmelCase_: str = LevitForImageClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowerCAmelCase_: Optional[Any] = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self ): lowerCAmelCase_: Union[str, Any] = self.prepare_config_and_inputs() lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_: Dict = config_and_inputs lowerCAmelCase_: Tuple = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _lowercase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE: Any = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) SCREAMING_SNAKE_CASE: int = ( { 'feature-extraction': LevitModel, 'image-classification': (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE: Optional[int] = False SCREAMING_SNAKE_CASE: Optional[Any] = False SCREAMING_SNAKE_CASE: str = False SCREAMING_SNAKE_CASE: str = False SCREAMING_SNAKE_CASE: List[Any] = False def _a ( self ): lowerCAmelCase_: List[str] = LevitModelTester(self ) lowerCAmelCase_: Union[str, Any] = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=37 ) def _a ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ): return @unittest.skip(reason="Levit does not use inputs_embeds" ) def _a ( self ): pass @unittest.skip(reason="Levit does not support input and output embeddings" ) def _a ( self ): pass @unittest.skip(reason="Levit does not output attentions" ) def _a ( self ): pass def _a ( self ): lowerCAmelCase_ , lowerCAmelCase_: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_: List[str] = model_class(lowerCamelCase__ ) lowerCAmelCase_: Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase_: Any = [*signature.parameters.keys()] lowerCAmelCase_: str = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def _a ( self ): def check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCAmelCase_: int = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() with torch.no_grad(): lowerCAmelCase_: Dict = model(**self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) ) lowerCAmelCase_: str = outputs.hidden_states lowerCAmelCase_: List[Any] = len(self.model_tester.depths ) + 1 self.assertEqual(len(lowerCamelCase__ ) , lowerCamelCase__ ) lowerCAmelCase_: List[Any] = (self.model_tester.image_size, self.model_tester.image_size) lowerCAmelCase_ , lowerCAmelCase_: int = image_size[0], image_size[1] for _ in range(4 ): lowerCAmelCase_: Tuple = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) lowerCAmelCase_: Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) lowerCAmelCase_ , lowerCAmelCase_: str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_: int = True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase_: Union[str, Any] = True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _a ( self ): pass def _a ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ): lowerCAmelCase_: List[str] = super()._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _a ( self ): lowerCAmelCase_: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def _a ( self ): lowerCAmelCase_: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ ) def _a ( self ): if not self.model_tester.is_training: return lowerCAmelCase_ , lowerCAmelCase_: Tuple = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase_: int = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowerCamelCase__ ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue lowerCAmelCase_: Tuple = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.train() lowerCAmelCase_: Optional[int] = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) lowerCAmelCase_: Tuple = model(**lowerCamelCase__ ).loss loss.backward() def _a ( self ): lowerCAmelCase_ , lowerCAmelCase_: List[str] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return lowerCAmelCase_: Any = False lowerCAmelCase_: Tuple = True for model_class in self.all_model_classes: if model_class in get_values(lowerCamelCase__ ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue lowerCAmelCase_: Any = model_class(lowerCamelCase__ ) model.gradient_checkpointing_enable() model.to(lowerCamelCase__ ) model.train() lowerCAmelCase_: str = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) lowerCAmelCase_: List[str] = model(**lowerCamelCase__ ).loss loss.backward() def _a ( self ): lowerCAmelCase_ , lowerCAmelCase_: int = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase_: Optional[int] = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowerCamelCase__ ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type["title"]}''' ): lowerCAmelCase_: Tuple = problem_type["title"] lowerCAmelCase_: Optional[Any] = problem_type["num_labels"] lowerCAmelCase_: List[str] = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.train() lowerCAmelCase_: List[Any] = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) if problem_type["num_labels"] > 1: lowerCAmelCase_: List[str] = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) lowerCAmelCase_: List[Any] = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowerCamelCase__ ) as warning_list: lowerCAmelCase_: Dict = model(**lowerCamelCase__ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def _a ( self ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase_: Optional[int] = LevitModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def snake_case__ ( ): lowerCAmelCase_: Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): '''simple docstring''' @cached_property def _a ( self ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _a ( self ): lowerCAmelCase_: Any = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( lowerCamelCase__ ) lowerCAmelCase_: str = self.default_image_processor lowerCAmelCase_: int = prepare_img() lowerCAmelCase_: Optional[int] = image_processor(images=lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): lowerCAmelCase_: Tuple = model(**lowerCamelCase__ ) # verify the logits lowerCAmelCase_: str = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) lowerCAmelCase_: Union[str, Any] = torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase__ , atol=1E-4 ) )
613
1
from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, require_torch_neuroncore, ) from transformers.training_args import ParallelMode from transformers.utils import logging __lowerCAmelCase = logging.get_logger(__name__) if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset from transformers import Trainer class __SCREAMING_SNAKE_CASE ( lowercase): def __init__( self : List[str] , __UpperCamelCase : int = 101 ): _UpperCAmelCase = length def __len__( self : Dict ): return self.length def __getitem__( self : List[Any] , __UpperCamelCase : List[str] ): return i class __SCREAMING_SNAKE_CASE : def __call__( self : Any , __UpperCamelCase : str ): return {"input_ids": torch.tensor(__UpperCamelCase ), "labels": torch.tensor(__UpperCamelCase )} class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Optional[Any] ): super().__init__() # Add some (unused) params otherwise DDP will complain. _UpperCAmelCase = nn.Linear(120 , 80 ) def UpperCAmelCase__ ( self : int , __UpperCamelCase : Tuple , __UpperCamelCase : str=None ): if labels is not None: return torch.tensor(0.0 , device=input_ids.device ), input_ids else: return input_ids class __SCREAMING_SNAKE_CASE ( lowercase): @require_torch_neuroncore def UpperCAmelCase__ ( self : Dict ): _UpperCAmelCase = F'''--nproc_per_node=2 --master_port={get_torch_dist_unique_port()} {self.test_file_dir}/test_trainer_distributed.py '''.split() _UpperCAmelCase = self.get_auto_remove_tmp_dir() _UpperCAmelCase = F'''--output_dir {output_dir}'''.split() _UpperCAmelCase = ["torchrun"] + distributed_args + args execute_subprocess_async(__UpperCamelCase , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call class __SCREAMING_SNAKE_CASE ( lowercase): @require_torch_multi_gpu def UpperCAmelCase__ ( self : str ): _UpperCAmelCase = F'''--nproc_per_node={torch.cuda.device_count()} --master_port={get_torch_dist_unique_port()} {self.test_file_dir}/test_trainer_distributed.py '''.split() _UpperCAmelCase = self.get_auto_remove_tmp_dir() _UpperCAmelCase = F'''--output_dir {output_dir}'''.split() _UpperCAmelCase = ["torchrun"] + distributed_args + args execute_subprocess_async(__UpperCamelCase , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call if __name__ == "__main__": # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: # # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py __lowerCAmelCase = HfArgumentParser((TrainingArguments,)) __lowerCAmelCase = parser.parse_args_into_dataclasses()[0] logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, ''' F'''distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}''' ) # Essentially, what we want to verify in the distributed case is that we get all samples back, # in the right order. (this is crucial for prediction for instance) for dataset_length in [1_0_1, 4_0, 7]: __lowerCAmelCase = DummyDataset(dataset_length) def __lowerCamelCase ( _lowerCAmelCase ) -> Dict: _UpperCAmelCase = list(range(len(_lowerCAmelCase ) ) ) _UpperCAmelCase = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential if not success and training_args.local_rank == 0: logger.warning( "Predictions and/or labels do not match expected results:\n - predictions: " F'''{p.predictions.tolist()}\n - labels: {p.label_ids.tolist()}\n - expected: {sequential}''' ) return {"success": success} __lowerCAmelCase = Trainer( model=DummyModel(), args=training_args, data_collator=DummyDataCollator(), eval_dataset=dataset, compute_metrics=compute_metrics, ) __lowerCAmelCase = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) __lowerCAmelCase = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) __lowerCAmelCase = 2 __lowerCAmelCase = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) __lowerCAmelCase = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) __lowerCAmelCase = None
129
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = r"\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n or scores for each vocabulary token after SoftMax.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional stopping criteria specific kwargs.\n\n Return:\n `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n" class __SCREAMING_SNAKE_CASE ( lowercase): @add_start_docstrings(__UpperCamelCase ) def __call__( self : Optional[int] , __UpperCamelCase : torch.LongTensor , __UpperCamelCase : torch.FloatTensor , **__UpperCamelCase : str ): raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class __SCREAMING_SNAKE_CASE ( lowercase): def __init__( self : Optional[Any] , __UpperCamelCase : int , __UpperCamelCase : Optional[int] = None ): _UpperCAmelCase = max_length _UpperCAmelCase = max_position_embeddings @add_start_docstrings(__UpperCamelCase ) def __call__( self : Union[str, Any] , __UpperCamelCase : torch.LongTensor , __UpperCamelCase : torch.FloatTensor , **__UpperCamelCase : Any ): _UpperCAmelCase = input_ids.shape[-1] _UpperCAmelCase = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F'''maximum length ({self.max_position_embeddings}). Depending on the model, you may observe ''' "exceptions, performance degradation, or nothing at all." ) return is_done class __SCREAMING_SNAKE_CASE ( lowercase): def __init__( self : Tuple , __UpperCamelCase : int , __UpperCamelCase : int ): warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F'''Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` ''' "with `max_length = start_length + max_new_tokens` instead." , __UpperCamelCase , ) _UpperCAmelCase = start_length _UpperCAmelCase = max_new_tokens _UpperCAmelCase = start_length + max_new_tokens @add_start_docstrings(__UpperCamelCase ) def __call__( self : Union[str, Any] , __UpperCamelCase : torch.LongTensor , __UpperCamelCase : torch.FloatTensor , **__UpperCamelCase : List[str] ): return input_ids.shape[-1] >= self.max_length class __SCREAMING_SNAKE_CASE ( lowercase): def __init__( self : Union[str, Any] , __UpperCamelCase : float , __UpperCamelCase : Optional[float] = None ): _UpperCAmelCase = max_time _UpperCAmelCase = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(__UpperCamelCase ) def __call__( self : Union[str, Any] , __UpperCamelCase : torch.LongTensor , __UpperCamelCase : torch.FloatTensor , **__UpperCamelCase : Any ): return time.time() - self.initial_timestamp > self.max_time class __SCREAMING_SNAKE_CASE ( lowercase): @add_start_docstrings(__UpperCamelCase ) def __call__( self : int , __UpperCamelCase : torch.LongTensor , __UpperCamelCase : torch.FloatTensor , **__UpperCamelCase : Optional[Any] ): return any(criteria(__UpperCamelCase , __UpperCamelCase ) for criteria in self ) @property def UpperCAmelCase__ ( self : Dict ): for stopping_criterium in self: if isinstance(__UpperCamelCase , __UpperCamelCase ): return stopping_criterium.max_length elif isinstance(__UpperCamelCase , __UpperCamelCase ): return stopping_criterium.max_length return None def __lowerCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> StoppingCriteriaList: _UpperCAmelCase = stopping_criteria.max_length _UpperCAmelCase = deepcopy(_lowerCAmelCase ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , _lowerCAmelCase ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=_lowerCAmelCase ) ) return new_stopping_criteria
129
1
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __magic_name__ : Optional[Any] = logging.get_logger(__name__) __magic_name__ : Tuple = { '''b0''': efficientnet.EfficientNetBa, '''b1''': efficientnet.EfficientNetBa, '''b2''': efficientnet.EfficientNetBa, '''b3''': efficientnet.EfficientNetBa, '''b4''': efficientnet.EfficientNetBa, '''b5''': efficientnet.EfficientNetBa, '''b6''': efficientnet.EfficientNetBa, '''b7''': efficientnet.EfficientNetBa, } __magic_name__ : Dict = { '''b0''': { '''hidden_dim''': 1280, '''width_coef''': 1.0, '''depth_coef''': 1.0, '''image_size''': 224, '''dropout_rate''': 0.2, '''dw_padding''': [], }, '''b1''': { '''hidden_dim''': 1280, '''width_coef''': 1.0, '''depth_coef''': 1.1, '''image_size''': 240, '''dropout_rate''': 0.2, '''dw_padding''': [16], }, '''b2''': { '''hidden_dim''': 1408, '''width_coef''': 1.1, '''depth_coef''': 1.2, '''image_size''': 260, '''dropout_rate''': 0.3, '''dw_padding''': [5, 8, 16], }, '''b3''': { '''hidden_dim''': 1536, '''width_coef''': 1.2, '''depth_coef''': 1.4, '''image_size''': 300, '''dropout_rate''': 0.3, '''dw_padding''': [5, 18], }, '''b4''': { '''hidden_dim''': 1792, '''width_coef''': 1.4, '''depth_coef''': 1.8, '''image_size''': 380, '''dropout_rate''': 0.4, '''dw_padding''': [6], }, '''b5''': { '''hidden_dim''': 2048, '''width_coef''': 1.6, '''depth_coef''': 2.2, '''image_size''': 456, '''dropout_rate''': 0.4, '''dw_padding''': [13, 27], }, '''b6''': { '''hidden_dim''': 2304, '''width_coef''': 1.8, '''depth_coef''': 2.6, '''image_size''': 528, '''dropout_rate''': 0.5, '''dw_padding''': [31], }, '''b7''': { '''hidden_dim''': 2560, '''width_coef''': 2.0, '''depth_coef''': 3.1, '''image_size''': 600, '''dropout_rate''': 0.5, '''dw_padding''': [18], }, } def lowercase__ ( _UpperCamelCase) -> List[Any]: """simple docstring""" UpperCamelCase = EfficientNetConfig() UpperCamelCase = CONFIG_MAP[model_name]['hidden_dim'] UpperCamelCase = CONFIG_MAP[model_name]['width_coef'] UpperCamelCase = CONFIG_MAP[model_name]['depth_coef'] UpperCamelCase = CONFIG_MAP[model_name]['image_size'] UpperCamelCase = CONFIG_MAP[model_name]['dropout_rate'] UpperCamelCase = CONFIG_MAP[model_name]['dw_padding'] UpperCamelCase = 'huggingface/label-files' UpperCamelCase = 'imagenet-1k-id2label.json' UpperCamelCase = 10_00 UpperCamelCase = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='dataset') , 'r')) UpperCamelCase = {int(_lowercase): v for k, v in idalabel.items()} UpperCamelCase = idalabel UpperCamelCase = {v: k for k, v in idalabel.items()} return config def lowercase__ ( ) -> List[str]: """simple docstring""" UpperCamelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' UpperCamelCase = Image.open(requests.get(_lowercase , stream=_lowercase).raw) return im def lowercase__ ( _UpperCamelCase) -> int: """simple docstring""" UpperCamelCase = CONFIG_MAP[model_name]['image_size'] UpperCamelCase = EfficientNetImageProcessor( size={'height': size, 'width': size} , image_mean=[0.4_8_5, 0.4_5_6, 0.4_0_6] , image_std=[0.4_7_8_5_3_9_4_4, 0.4_7_3_2_8_6_4, 0.4_7_4_3_4_1_6_3] , do_center_crop=_lowercase , ) return preprocessor def lowercase__ ( _UpperCamelCase) -> int: """simple docstring""" UpperCamelCase = [v.split('_')[0].split('block')[1] for v in original_param_names if v.startswith('block')] UpperCamelCase = sorted(set(_lowercase)) UpperCamelCase = len(_lowercase) UpperCamelCase = {b: str(_lowercase) for b, i in zip(_lowercase , range(_lowercase))} UpperCamelCase = [] rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight')) rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight')) rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias')) rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean')) rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var')) for b in block_names: UpperCamelCase = block_name_mapping[b] rename_keys.append((F'block{b}_expand_conv/kernel:0', F'encoder.blocks.{hf_b}.expansion.expand_conv.weight')) rename_keys.append((F'block{b}_expand_bn/gamma:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.weight')) rename_keys.append((F'block{b}_expand_bn/beta:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.bias')) rename_keys.append( (F'block{b}_expand_bn/moving_mean:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_mean')) rename_keys.append( (F'block{b}_expand_bn/moving_variance:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_var')) rename_keys.append( (F'block{b}_dwconv/depthwise_kernel:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight')) rename_keys.append((F'block{b}_bn/gamma:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight')) rename_keys.append((F'block{b}_bn/beta:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias')) rename_keys.append( (F'block{b}_bn/moving_mean:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean')) rename_keys.append( (F'block{b}_bn/moving_variance:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var')) rename_keys.append((F'block{b}_se_reduce/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.weight')) rename_keys.append((F'block{b}_se_reduce/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.bias')) rename_keys.append((F'block{b}_se_expand/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.weight')) rename_keys.append((F'block{b}_se_expand/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.bias')) rename_keys.append( (F'block{b}_project_conv/kernel:0', F'encoder.blocks.{hf_b}.projection.project_conv.weight')) rename_keys.append((F'block{b}_project_bn/gamma:0', F'encoder.blocks.{hf_b}.projection.project_bn.weight')) rename_keys.append((F'block{b}_project_bn/beta:0', F'encoder.blocks.{hf_b}.projection.project_bn.bias')) rename_keys.append( (F'block{b}_project_bn/moving_mean:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_mean')) rename_keys.append( (F'block{b}_project_bn/moving_variance:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_var')) rename_keys.append(('top_conv/kernel:0', 'encoder.top_conv.weight')) rename_keys.append(('top_bn/gamma:0', 'encoder.top_bn.weight')) rename_keys.append(('top_bn/beta:0', 'encoder.top_bn.bias')) rename_keys.append(('top_bn/moving_mean:0', 'encoder.top_bn.running_mean')) rename_keys.append(('top_bn/moving_variance:0', 'encoder.top_bn.running_var')) UpperCamelCase = {} for item in rename_keys: if item[0] in original_param_names: UpperCamelCase = 'efficientnet.' + item[1] UpperCamelCase = 'classifier.weight' UpperCamelCase = 'classifier.bias' return key_mapping def lowercase__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase) -> Any: """simple docstring""" for key, value in tf_params.items(): if "normalization" in key: continue UpperCamelCase = key_mapping[key] if "_conv" in key and "kernel" in key: UpperCamelCase = torch.from_numpy(_lowercase).permute(3 , 2 , 0 , 1) elif "depthwise_kernel" in key: UpperCamelCase = torch.from_numpy(_lowercase).permute(2 , 3 , 0 , 1) elif "kernel" in key: UpperCamelCase = torch.from_numpy(np.transpose(_lowercase)) else: UpperCamelCase = torch.from_numpy(_lowercase) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(_lowercase) @torch.no_grad() def lowercase__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase) -> Optional[int]: """simple docstring""" UpperCamelCase = model_classes[model_name]( include_top=_lowercase , weights='imagenet' , input_tensor=_lowercase , input_shape=_lowercase , pooling=_lowercase , classes=10_00 , classifier_activation='softmax' , ) UpperCamelCase = original_model.trainable_variables UpperCamelCase = original_model.non_trainable_variables UpperCamelCase = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: UpperCamelCase = param.numpy() UpperCamelCase = list(tf_params.keys()) # Load HuggingFace model UpperCamelCase = get_efficientnet_config(_lowercase) UpperCamelCase = EfficientNetForImageClassification(_lowercase).eval() UpperCamelCase = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('Converting parameters...') UpperCamelCase = rename_keys(_lowercase) replace_params(_lowercase , _lowercase , _lowercase) # Initialize preprocessor and preprocess input image UpperCamelCase = convert_image_processor(_lowercase) UpperCamelCase = preprocessor(images=prepare_img() , return_tensors='pt') # HF model inference hf_model.eval() with torch.no_grad(): UpperCamelCase = hf_model(**_lowercase) UpperCamelCase = outputs.logits.detach().numpy() # Original model inference UpperCamelCase = False UpperCamelCase = CONFIG_MAP[model_name]['image_size'] UpperCamelCase = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST) UpperCamelCase = image.img_to_array(_lowercase) UpperCamelCase = np.expand_dims(_lowercase , axis=0) UpperCamelCase = original_model.predict(_lowercase) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(_lowercase , _lowercase , atol=1e-3), "The predicted logits are not the same." print('Model outputs match!') if save_model: # Create folder to save model if not os.path.isdir(_lowercase): os.mkdir(_lowercase) # Save converted model and image processor hf_model.save_pretrained(_lowercase) preprocessor.save_pretrained(_lowercase) if push_to_hub: # Push model and image processor to hub print(F'Pushing converted {model_name} to the hub...') UpperCamelCase = F'efficientnet-{model_name}' preprocessor.push_to_hub(_lowercase) hf_model.push_to_hub(_lowercase) if __name__ == "__main__": __magic_name__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''b0''', type=str, help='''Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''hf_model''', type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--save_model''', action='''store_true''', help='''Save model to local''') parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') __magic_name__ : str = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
280
"""simple docstring""" import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'): lowercase_ = True from torch.cuda.amp import autocast lowercase_ = logging.getLogger(__name__) def UpperCAmelCase ( _lowercase : Optional[Any]=None , _lowercase : str=None ) -> List[str]: """simple docstring""" return field(default_factory=lambda: default , metadata=_lowercase ) @dataclass class __a : lowerCamelCase : str =field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowerCamelCase : Optional[str] =field( default=__snake_case , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) lowerCamelCase : Optional[bool] =field( default=__snake_case , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={'help': 'The dropout ratio for the attention probabilities.'} ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'} ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={ 'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.' } , ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'} , ) lowerCamelCase : Optional[float] =field( default=0.05 , metadata={ 'help': ( 'Propability of each feature vector along the time axis to be chosen as the start of the vector' 'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature' 'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.' ) } , ) lowerCamelCase : Optional[float] =field(default=0.0 , metadata={'help': 'The LayerDrop probability.'} ) @dataclass class __a : lowerCamelCase : Optional[str] =field( default=__snake_case , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) lowerCamelCase : Optional[str] =field( default='train+validation' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) lowerCamelCase : bool =field( default=__snake_case , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) lowerCamelCase : Optional[int] =field( default=__snake_case , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) lowerCamelCase : Optional[int] =field( default=__snake_case , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) lowerCamelCase : Optional[int] =field( default=__snake_case , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of validation examples to this ' 'value if set.' ) } , ) lowerCamelCase : List[str] =list_field( default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�'] , metadata={'help': 'A list of characters to remove from the transcripts.'} , ) @dataclass class __a : lowerCamelCase : WavaVecaProcessor lowerCamelCase : Union[bool, str] =True lowerCamelCase : Optional[int] =None lowerCamelCase : Optional[int] =None lowerCamelCase : Optional[int] =None lowerCamelCase : Optional[int] =None def __call__( self , UpperCAmelCase ): '''simple docstring''' lowerCAmelCase_ = [{'''input_values''': feature['''input_values''']} for feature in features] lowerCAmelCase_ = [{'''input_ids''': feature['''labels''']} for feature in features] lowerCAmelCase_ = self.processor.pad( UpperCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) lowerCAmelCase_ = self.processor.pad( labels=UpperCAmelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='''pt''' , ) # replace padding with -100 to ignore loss correctly lowerCAmelCase_ = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 ) lowerCAmelCase_ = labels return batch class __a ( __snake_case ): def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase ): '''simple docstring''' model.train() lowerCAmelCase_ = self._prepare_inputs(UpperCAmelCase ) if self.use_amp: with autocast(): lowerCAmelCase_ = self.compute_loss(UpperCAmelCase , UpperCAmelCase ) else: lowerCAmelCase_ = self.compute_loss(UpperCAmelCase , UpperCAmelCase ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": lowerCAmelCase_ = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowerCAmelCase_ = loss.sum() / (inputs['''labels'''] >= 0).sum() else: raise ValueError(F"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" ) if self.args.gradient_accumulation_steps > 1: lowerCAmelCase_ = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(UpperCAmelCase ).backward() elif self.use_apex: with amp.scale_loss(UpperCAmelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(UpperCAmelCase ) else: loss.backward() return loss.detach() def UpperCAmelCase ( ) -> Tuple: """simple docstring""" lowerCAmelCase_ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowerCAmelCase_ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowerCAmelCase_ = 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: 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.''' ) # 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 )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # 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}""" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , _lowercase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: lowerCAmelCase_ = datasets.load_dataset( '''common_voice''' , data_args.dataset_config_name , split=data_args.train_split_name ) lowerCAmelCase_ = datasets.load_dataset('''common_voice''' , data_args.dataset_config_name , split='''test''' ) # Create and save tokenizer lowerCAmelCase_ = F"""[{"".join(data_args.chars_to_ignore )}]""" def remove_special_characters(_lowercase : List[str] ): lowerCAmelCase_ = re.sub(_lowercase , '''''' , batch['''sentence'''] ).lower() + ''' ''' return batch lowerCAmelCase_ = train_dataset.map(_lowercase , remove_columns=['''sentence'''] ) lowerCAmelCase_ = eval_dataset.map(_lowercase , remove_columns=['''sentence'''] ) def extract_all_chars(_lowercase : str ): lowerCAmelCase_ = ''' '''.join(batch['''text'''] ) lowerCAmelCase_ = list(set(_lowercase ) ) return {"vocab": [vocab], "all_text": [all_text]} lowerCAmelCase_ = train_dataset.map( _lowercase , batched=_lowercase , batch_size=-1 , keep_in_memory=_lowercase , remove_columns=train_dataset.column_names , ) lowerCAmelCase_ = train_dataset.map( _lowercase , batched=_lowercase , batch_size=-1 , keep_in_memory=_lowercase , remove_columns=eval_dataset.column_names , ) lowerCAmelCase_ = list(set(vocab_train['''vocab'''][0] ) | set(vocab_test['''vocab'''][0] ) ) lowerCAmelCase_ = {v: k for k, v in enumerate(_lowercase )} lowerCAmelCase_ = vocab_dict[''' '''] del vocab_dict[" "] lowerCAmelCase_ = len(_lowercase ) lowerCAmelCase_ = len(_lowercase ) with open('''vocab.json''' , '''w''' ) as vocab_file: json.dump(_lowercase , _lowercase ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase_ = WavaVecaCTCTokenizer( '''vocab.json''' , unk_token='''[UNK]''' , pad_token='''[PAD]''' , word_delimiter_token='''|''' , ) lowerCAmelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0.0 , do_normalize=_lowercase , return_attention_mask=_lowercase ) lowerCAmelCase_ = WavaVecaProcessor(feature_extractor=_lowercase , tokenizer=_lowercase ) lowerCAmelCase_ = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='''mean''' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: lowerCAmelCase_ = min(len(_lowercase ) , data_args.max_train_samples ) lowerCAmelCase_ = train_dataset.select(range(_lowercase ) ) if data_args.max_val_samples is not None: lowerCAmelCase_ = eval_dataset.select(range(data_args.max_val_samples ) ) lowerCAmelCase_ = torchaudio.transforms.Resample(4_8_0_0_0 , 1_6_0_0_0 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(_lowercase : Union[str, Any] ): lowerCAmelCase_ , lowerCAmelCase_ = torchaudio.load(batch['''path'''] ) lowerCAmelCase_ = resampler(_lowercase ).squeeze().numpy() lowerCAmelCase_ = 1_6_0_0_0 lowerCAmelCase_ = batch['''text'''] return batch lowerCAmelCase_ = train_dataset.map( _lowercase , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) lowerCAmelCase_ = eval_dataset.map( _lowercase , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(_lowercase : str ): # check that all files have the correct sampling rate assert ( len(set(batch['''sampling_rate'''] ) ) == 1 ), F"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.""" lowerCAmelCase_ = processor( audio=batch['''speech'''] , text=batch['''target_text'''] , sampling_rate=batch['''sampling_rate'''][0] ) batch.update(_lowercase ) return batch lowerCAmelCase_ = train_dataset.map( _lowercase , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowercase , num_proc=data_args.preprocessing_num_workers , ) lowerCAmelCase_ = eval_dataset.map( _lowercase , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowercase , num_proc=data_args.preprocessing_num_workers , ) # Metric lowerCAmelCase_ = datasets.load_metric('''wer''' ) def compute_metrics(_lowercase : Optional[int] ): lowerCAmelCase_ = pred.predictions lowerCAmelCase_ = np.argmax(_lowercase , axis=-1 ) lowerCAmelCase_ = processor.tokenizer.pad_token_id lowerCAmelCase_ = processor.batch_decode(_lowercase ) # we do not want to group tokens when computing the metrics lowerCAmelCase_ = processor.batch_decode(pred.label_ids , group_tokens=_lowercase ) lowerCAmelCase_ = wer_metric.compute(predictions=_lowercase , references=_lowercase ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator lowerCAmelCase_ = DataCollatorCTCWithPadding(processor=_lowercase , padding=_lowercase ) # Initialize our Trainer lowerCAmelCase_ = CTCTrainer( model=_lowercase , data_collator=_lowercase , args=_lowercase , compute_metrics=_lowercase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: lowerCAmelCase_ = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): lowerCAmelCase_ = model_args.model_name_or_path else: lowerCAmelCase_ = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) lowerCAmelCase_ = trainer.train(resume_from_checkpoint=_lowercase ) trainer.save_model() lowerCAmelCase_ = train_result.metrics lowerCAmelCase_ = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowercase ) ) lowerCAmelCase_ = min(_lowercase , len(_lowercase ) ) trainer.log_metrics('''train''' , _lowercase ) trainer.save_metrics('''train''' , _lowercase ) trainer.save_state() # Evaluation lowerCAmelCase_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowerCAmelCase_ = trainer.evaluate() lowerCAmelCase_ = data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowercase ) lowerCAmelCase_ = min(_lowercase , len(_lowercase ) ) trainer.log_metrics('''eval''' , _lowercase ) trainer.save_metrics('''eval''' , _lowercase ) return results if __name__ == "__main__": main()
552
0
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : Dict = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : str = XLMProphetNetTokenizer _A : List[Any] = False _A : Tuple = True def UpperCamelCase_ ( self ) -> Any: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XLMProphetNetTokenizer(snake_case__ , keep_accents=snake_case__ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = """[PAD]""" UpperCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__ ) , snake_case__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__ ) , snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """[PAD]""" ) self.assertEqual(vocab_keys[1] , """[CLS]""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(snake_case__ ) , 10_12 ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_12 ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = XLMProphetNetTokenizer(snake_case__ , keep_accents=snake_case__ ) UpperCAmelCase = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(snake_case__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) UpperCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( snake_case__ , [ 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(snake_case__ ) self.assertListEqual( snake_case__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(snake_case__ ) self.assertListEqual( snake_case__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """[UNK]""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """[UNK]""", """.""", ] , ) @cached_property def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" return XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased""" ) @slow def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = """Hello World!""" UpperCAmelCase = [3_53_89, 66_72, 49, 2] self.assertListEqual(snake_case__ , self.big_tokenizer.encode(snake_case__ ) ) @slow def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = {"""input_ids""": [[1_10_73, 8_27_83, 18, 26, 8_27_83, 5_49, 5_15_40, 2_48, 1_72_09, 13_01, 2_17, 20, 21_51_86, 13_25, 1_47, 1_72_09, 13_01, 2_17, 20, 5_63_70, 53, 12_20_20, 20, 1_64_77, 27, 8_73_55, 45_48, 20, 47_28, 7_83_92, 17, 15_99_69, 18, 26, 2_44_91, 6_29, 15, 5_38, 2_27_04, 54_39, 15, 27_88, 2_44_91, 98_85, 15, 4_35_34, 6_05, 15, 8_14, 1_84_03, 3_32_00, 29, 15, 4_35_34, 2_44_58, 1_24_10, 1_11, 2_49_66, 8_36_69, 96_37, 14_40_68, 26, 8_50, 2_23_46, 27, 1_47, 2_49_66, 8_36_69, 8_34_90, 26, 3_91_13, 7_35, 27, 6_89, 6_56, 28_00, 13_39, 46_00, 53, 12_20_20, 11_57_85, 34, 8_16, 13_39, 4_68_87, 18, 1_47, 5_39_05, 19_51, 4_22_38, 4_11_70, 1_77_32, 8_34, 4_36, 15, 2_75_23, 9_87_33, 2_17, 1_47, 55_42, 49_81, 9_30, 1_73_47, 16, 2], [2_00_91, 6_29, 94, 8_27_86, 58, 4_90, 20, 15_28, 84, 5_39_05, 3_44, 8_05_92, 11_01_28, 1_88_22, 52_67, 13_06, 62, 15_25_37, 3_08, 79_97, 4_01, 12_44_27, 5_49, 3_54_42, 2_25, 1_09, 1_50_55, 2_57_48, 1_47, 71_19, 4_37_12, 34, 7_67, 13_53_66, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_92, 6_37_84, 11_94_66, 17, 14_78_08, 8_82_14, 18, 6_56, 81, 32, 32_96, 1_02_80, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=snake_case__ , model_name="""microsoft/xprophetnet-large-wiki100-cased""" , revision="""1acad1643ddd54a44df6a1b797ada8373685d90e""" , )
378
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : Any = logging.get_logger(__name__) lowerCAmelCase_ : Any = { '''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.json''', # See all CANINE models at https://huggingface.co/models?filter=canine } class UpperCamelCase_ ( a_ ): _A : Tuple = 'canine' def __init__( self , snake_case__=7_68 , snake_case__=12 , snake_case__=12 , snake_case__=30_72 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=1_63_84 , snake_case__=16 , snake_case__=0.02 , snake_case__=1e-12 , snake_case__=0 , snake_case__=0xE_0_0_0 , snake_case__=0xE_0_0_1 , snake_case__=4 , snake_case__=4 , snake_case__=8 , snake_case__=1_63_84 , snake_case__=1_28 , **snake_case__ , ) -> int: """simple docstring""" super().__init__(pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ ) UpperCAmelCase = max_position_embeddings 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 = type_vocab_size UpperCAmelCase = layer_norm_eps # Character config: UpperCAmelCase = downsampling_rate UpperCAmelCase = upsampling_kernel_size UpperCAmelCase = num_hash_functions UpperCAmelCase = num_hash_buckets UpperCAmelCase = local_transformer_stride
378
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { 'RWKV/rwkv-4-169m-pile': 'https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json', 'RWKV/rwkv-4-430m-pile': 'https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json', 'RWKV/rwkv-4-1b5-pile': 'https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json', 'RWKV/rwkv-4-3b-pile': 'https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json', 'RWKV/rwkv-4-7b-pile': 'https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json', 'RWKV/rwkv-4-14b-pile': 'https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json', 'RWKV/rwkv-raven-1b5': 'https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json', 'RWKV/rwkv-raven-3b': 'https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json', 'RWKV/rwkv-raven-7b': 'https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json', 'RWKV/rwkv-raven-14b': 'https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json', } class UpperCamelCase ( snake_case_ ): UpperCamelCase : Any = '''rwkv''' UpperCamelCase : Optional[int] = {'''max_position_embeddings''': '''context_length'''} def __init__( self : List[Any] , UpperCAmelCase__ : Optional[int]=50277 , UpperCAmelCase__ : List[Any]=1024 , UpperCAmelCase__ : Dict=4096 , UpperCAmelCase__ : Optional[Any]=32 , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=1E-5 , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : Any=6 , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=True , **UpperCAmelCase__ : List[Any] , ) -> Optional[int]: _a : Dict = vocab_size _a : List[Any] = context_length _a : int = hidden_size _a : Dict = num_hidden_layers _a : List[Any] = attention_hidden_size if attention_hidden_size is not None else hidden_size _a : Any = intermediate_size if intermediate_size is not None else 4 * hidden_size _a : int = layer_norm_epsilon _a : List[str] = rescale_every _a : List[str] = use_cache _a : List[str] = bos_token_id _a : Optional[int] = eos_token_id super().__init__( tie_word_embeddings=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ )
389
"""simple docstring""" def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = 0 for i in range(1 , 1_0_0_1 ): total += i**i return str(UpperCamelCase__ )[-1_0:] if __name__ == "__main__": print(solution())
389
1
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' def _UpperCamelCase ( self ) -> str: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def _UpperCamelCase ( self ) -> Optional[int]: snake_case_ = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} return Dataset.from_dict(a ) def _UpperCamelCase ( self ) -> Tuple: snake_case_ = self._create_example_records() snake_case_ = Dataset.from_list(a ) self.assertListEqual(dset.column_names , ['col_1', 'col_2'] ) for i, r in enumerate(a ): self.assertDictEqual(a , example_records[i] ) def _UpperCamelCase ( self ) -> List[Any]: snake_case_ = self._create_example_records() snake_case_ = Dataset.from_list(a ) snake_case_ = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def _UpperCamelCase ( self ) -> str: # checks what happens with missing columns snake_case_ = [{'col_1': 1}, {'col_2': 'x'}] snake_case_ = Dataset.from_list(a ) self.assertDictEqual(dset[0] , {'col_1': 1} ) self.assertDictEqual(dset[1] , {'col_1': None} ) # NB: first record is used for columns def _UpperCamelCase ( self ) -> Optional[int]: # checks if the type can be inferred from the second record snake_case_ = [{'col_1': []}, {'col_1': [1, 2]}] snake_case_ = Dataset.from_list(a ) self.assertEqual(dset.info.features['col_1'] , Sequence(Value('int64' ) ) ) def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = Dataset.from_list([] ) self.assertEqual(len(a ) , 0 ) self.assertListEqual(dset.column_names , [] )
718
class UpperCamelCase_ : '''simple docstring''' def __init__( self , a ) -> None: snake_case_ = set_counts snake_case_ = max(a ) snake_case_ = len(a ) snake_case_ = [1] * num_sets snake_case_ = list(range(a ) ) def _UpperCamelCase ( self , a , a ) -> bool: snake_case_ = self.get_parent(a ) snake_case_ = self.get_parent(a ) 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] snake_case_ = 0 snake_case_ = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 snake_case_ = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] snake_case_ = 0 snake_case_ = src_parent snake_case_ = self.set_counts[src_parent] snake_case_ = max(self.max_set , a ) return True def _UpperCamelCase ( self , a ) -> int: if self.parents[disj_set] == disj_set: return disj_set snake_case_ = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
607
0
import importlib.metadata import operator import re import sys from typing import Optional from packaging import version a : Optional[int] = { "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt, } def lowerCamelCase__ ( __lowerCamelCase : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : str ): if got_ver is None or want_ver is None: raise ValueError( f"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" f""" reinstalling {pkg}.""" ) if not ops[op](version.parse(__lowerCamelCase ) , version.parse(__lowerCamelCase ) ): raise ImportError( f"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def lowerCamelCase__ ( __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): __UpperCAmelCase : Optional[int] = f"""\n{hint}""" if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __lowerCamelCase ): __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = requirement, None, None else: __UpperCAmelCase : Optional[int] = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" f""" got {requirement}""" ) __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = match[0] __UpperCAmelCase : str = want_full.split(""",""" ) # there could be multiple requirements __UpperCAmelCase : Dict = {} for w in want_range: __UpperCAmelCase : Optional[int] = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" f""" but got {requirement}""" ) __UpperCAmelCase , __UpperCAmelCase : List[str] = match[0] __UpperCAmelCase : Optional[Any] = want_ver if op not in ops: raise ValueError(f"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": __UpperCAmelCase : Optional[Any] = """.""".join([str(__lowerCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return # check if any version is installed try: __UpperCAmelCase : Union[str, Any] = importlib.metadata.version(__lowerCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( f"""The '{requirement}' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : List[Any] ): __UpperCAmelCase : Union[str, Any] = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__lowerCamelCase , __lowerCamelCase )
63
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int) -> int: '''simple docstring''' __UpperCamelCase : Tuple = 1 for i in range(1 , num + 1): fact *= i return fact def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int) -> int: '''simple docstring''' __UpperCamelCase : Dict = 0 while number > 0: __UpperCamelCase : List[Any] = number % 10 sum_of_digits += last_digit __UpperCamelCase : List[Any] = number // 10 # Removing the last_digit from the given number return sum_of_digits def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 100) -> int: '''simple docstring''' __UpperCamelCase : Optional[Any] = factorial(_lowerCamelCase) __UpperCamelCase : Tuple = split_and_add(_lowerCamelCase) return result if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
557
0
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase__ ( _a : List[str] ): snake_case_ : int = filter(lambda _a : p.requires_grad , model.parameters() ) snake_case_ : str = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowercase : List[str] = logging.getLogger(__name__) def lowerCAmelCase__ ( _a : Dict , _a : List[str] ): if metric == "rouge2": snake_case_ : List[str] = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": snake_case_ : Any = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": snake_case_ : List[str] = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' " function." ) snake_case_ : Optional[int] = ModelCheckpoint( dirpath=_a , filename=_a , monitor=F'''val_{metric}''' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def lowerCAmelCase__ ( _a : Optional[int] , _a : str ): return EarlyStopping( monitor=F'''val_{metric}''' , mode="min" if "loss" in metric else "max" , patience=_a , verbose=_a , ) class UpperCAmelCase_ ( pl.Callback ): '''simple docstring''' def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ : int = {f'''lr_group_{i}''': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_SCREAMING_SNAKE_CASE ) @rank_zero_only def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True ) -> None: logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) snake_case_ : Any = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results snake_case_ : str = Path(pl_module.hparams.output_dir ) if type_path == "test": snake_case_ : Union[str, Any] = od / "test_results.txt" snake_case_ : Tuple = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. snake_case_ : Optional[int] = od / f'''{type_path}_results/{trainer.global_step:05d}.txt''' snake_case_ : Optional[int] = od / f'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) generations_file.parent.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , "a+" ) as writer: for key in sorted(_SCREAMING_SNAKE_CASE ): if key in ["log", "progress_bar", "preds"]: continue snake_case_ : Union[str, Any] = metrics[key] if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): snake_case_ : Dict = val.item() snake_case_ : Union[str, Any] = f'''{key}: {val:.6f}\n''' writer.write(_SCREAMING_SNAKE_CASE ) if not save_generations: return if "preds" in metrics: snake_case_ : Optional[Any] = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_SCREAMING_SNAKE_CASE ) @rank_zero_only def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: try: snake_case_ : Optional[Any] = pl_module.model.model.num_parameters() except AttributeError: snake_case_ : Optional[Any] = pl_module.model.num_parameters() snake_case_ : List[str] = count_trainable_parameters(_SCREAMING_SNAKE_CASE ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , "test" ) @rank_zero_only def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
708
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available lowercase : int = { '''configuration_audio_spectrogram_transformer''': [ '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ASTConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ASTForAudioClassification''', '''ASTModel''', '''ASTPreTrainedModel''', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[int] = ['''ASTFeatureExtractor'''] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys lowercase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
114
0
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _a ( snake_case_ , snake_case_ ): """simple docstring""" @register_to_config def __init__( self : Any , UpperCAmelCase : int = 768 , ): super().__init__() A_ = nn.Parameter(torch.zeros(1 , UpperCAmelCase ) ) A_ = nn.Parameter(torch.ones(1 , UpperCAmelCase ) ) def __A ( self : Optional[Any] , UpperCAmelCase : Optional[Union[str, torch.device]] = None , UpperCAmelCase : Optional[torch.dtype] = None , ): A_ = nn.Parameter(self.mean.to(UpperCAmelCase ).to(UpperCAmelCase ) ) A_ = nn.Parameter(self.std.to(UpperCAmelCase ).to(UpperCAmelCase ) ) return self def __A ( self : Any , UpperCAmelCase : int ): A_ = (embeds - self.mean) * 1.0 / self.std return embeds def __A ( self : Dict , UpperCAmelCase : int ): A_ = (embeds * self.std) + self.mean return embeds
86
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class _SCREAMING_SNAKE_CASE ( A , A , unittest.TestCase ): __SCREAMING_SNAKE_CASE = IFPipeline __SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} __SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE = PipelineTesterMixin.required_optional_params - {'''latents'''} def __snake_case( self ): return self._get_dummy_components() def __snake_case( self , A_ , A_=0 ): if str(A_ ).startswith("""mps""" ): _UpperCAmelCase : Tuple = torch.manual_seed(A_ ) else: _UpperCAmelCase : Optional[Any] = torch.Generator(device=A_ ).manual_seed(A_ ) _UpperCAmelCase : Any = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def __snake_case( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __snake_case( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __snake_case( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __snake_case( self ): self._test_save_load_local() def __snake_case( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @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 ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __snake_case( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case( self ): # if _UpperCAmelCase : List[str] = IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa ) _UpperCAmelCase : Dict = IFSuperResolutionPipeline.from_pretrained( """DeepFloyd/IF-II-L-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa , text_encoder=A_ , tokenizer=A_ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("""cuda""" ) _UpperCAmelCase,_UpperCAmelCase : Dict = pipe_a.encode_prompt("""anime turtle""" , device="""cuda""" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() _UpperCAmelCase : List[Any] = None _UpperCAmelCase : Any = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(A_ , A_ , A_ , A_ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img _UpperCAmelCase : Any = IFImgaImgPipeline(**pipe_a.components ) _UpperCAmelCase : Union[str, Any] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(A_ , A_ , A_ , A_ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting _UpperCAmelCase : Optional[int] = IFInpaintingPipeline(**pipe_a.components ) _UpperCAmelCase : Union[str, Any] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(A_ , A_ , A_ , A_ ) def __snake_case( self , A_ , A_ , A_ , A_ ): # pipeline 1 _start_torch_memory_measurement() _UpperCAmelCase : Optional[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) _UpperCAmelCase : List[str] = pipe_a( prompt_embeds=A_ , negative_prompt_embeds=A_ , num_inference_steps=2 , generator=A_ , output_type="""np""" , ) _UpperCAmelCase : int = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase : Dict = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 _UpperCAmelCase : str = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy""" ) assert_mean_pixel_difference(A_ , A_ ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase : List[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) _UpperCAmelCase : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(A_ ) _UpperCAmelCase : str = pipe_a( prompt_embeds=A_ , negative_prompt_embeds=A_ , image=A_ , generator=A_ , num_inference_steps=2 , output_type="""np""" , ) _UpperCAmelCase : int = output.images[0] assert image.shape == (2_56, 2_56, 3) _UpperCAmelCase : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(A_ , A_ ) def __snake_case( self , A_ , A_ , A_ , A_ ): # pipeline 1 _start_torch_memory_measurement() _UpperCAmelCase : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(A_ ) _UpperCAmelCase : Dict = torch.Generator(device="""cpu""" ).manual_seed(0 ) _UpperCAmelCase : List[str] = pipe_a( prompt_embeds=A_ , negative_prompt_embeds=A_ , image=A_ , num_inference_steps=2 , generator=A_ , output_type="""np""" , ) _UpperCAmelCase : int = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase : str = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _UpperCAmelCase : str = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy""" ) assert_mean_pixel_difference(A_ , A_ ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase : List[str] = torch.Generator(device="""cpu""" ).manual_seed(0 ) _UpperCAmelCase : Union[str, Any] = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(A_ ) _UpperCAmelCase : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(A_ ) _UpperCAmelCase : Optional[int] = pipe_a( prompt_embeds=A_ , negative_prompt_embeds=A_ , image=A_ , original_image=A_ , generator=A_ , num_inference_steps=2 , output_type="""np""" , ) _UpperCAmelCase : Dict = output.images[0] assert image.shape == (2_56, 2_56, 3) _UpperCAmelCase : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(A_ , A_ ) def __snake_case( self , A_ , A_ , A_ , A_ ): # pipeline 1 _start_torch_memory_measurement() _UpperCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(A_ ) _UpperCAmelCase : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(A_ ) _UpperCAmelCase : Optional[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) _UpperCAmelCase : str = pipe_a( prompt_embeds=A_ , negative_prompt_embeds=A_ , image=A_ , mask_image=A_ , num_inference_steps=2 , generator=A_ , output_type="""np""" , ) _UpperCAmelCase : Optional[Any] = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase : List[str] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _UpperCAmelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy""" ) assert_mean_pixel_difference(A_ , A_ ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase : str = torch.Generator(device="""cpu""" ).manual_seed(0 ) _UpperCAmelCase : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(A_ ) _UpperCAmelCase : Tuple = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(A_ ) _UpperCAmelCase : str = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(1 ) ).to(A_ ) _UpperCAmelCase : Union[str, Any] = pipe_a( prompt_embeds=A_ , negative_prompt_embeds=A_ , image=A_ , mask_image=A_ , original_image=A_ , generator=A_ , num_inference_steps=2 , output_type="""np""" , ) _UpperCAmelCase : Any = output.images[0] assert image.shape == (2_56, 2_56, 3) _UpperCAmelCase : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase : Tuple = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(A_ , A_ ) def a__ ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
643
0
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
709
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __UpperCAmelCase (_UpperCAmelCase ): __snake_case : int = "ctrl" __snake_case : Dict = ["past_key_values"] __snake_case : List[str] = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self: Optional[Any] , UpperCAmelCase_: int=246_534 , UpperCAmelCase_: List[Any]=256 , UpperCAmelCase_: int=1_280 , UpperCAmelCase_: str=8_192 , UpperCAmelCase_: Optional[Any]=48 , UpperCAmelCase_: Optional[Any]=16 , UpperCAmelCase_: Optional[int]=0.1 , UpperCAmelCase_: Dict=0.1 , UpperCAmelCase_: Union[str, Any]=1E-6 , UpperCAmelCase_: Optional[Any]=0.02 , UpperCAmelCase_: Dict=True , **UpperCAmelCase_: str , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = n_positions _SCREAMING_SNAKE_CASE = n_embd _SCREAMING_SNAKE_CASE = n_layer _SCREAMING_SNAKE_CASE = n_head _SCREAMING_SNAKE_CASE = dff _SCREAMING_SNAKE_CASE = resid_pdrop _SCREAMING_SNAKE_CASE = embd_pdrop _SCREAMING_SNAKE_CASE = layer_norm_epsilon _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = use_cache super().__init__(**UpperCAmelCase_ )
569
0
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class _lowercase ( _UpperCAmelCase ): """simple docstring""" lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 class _lowercase ( nn.Module ): """simple docstring""" lowerCAmelCase__ = 42 lowerCAmelCase__ = (16, 32, 96, 256) lowerCAmelCase__ = jnp.floataa def _UpperCAmelCase ( self ): '''simple docstring''' _lowercase = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _lowercase = [] for i in range(len(self.block_out_channels ) - 1 ): _lowercase = self.block_out_channels[i] _lowercase = self.block_out_channels[i + 1] _lowercase = nn.Conv( _snake_case , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_snake_case ) _lowercase = nn.Conv( _snake_case , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_snake_case ) _lowercase = blocks _lowercase = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , UpperCAmelCase ): '''simple docstring''' _lowercase = self.conv_in(_snake_case ) _lowercase = nn.silu(_snake_case ) for block in self.blocks: _lowercase = block(_snake_case ) _lowercase = nn.silu(_snake_case ) _lowercase = self.conv_out(_snake_case ) return embedding @flax_register_to_config class _lowercase ( nn.Module , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" lowerCAmelCase__ = 32 lowerCAmelCase__ = 4 lowerCAmelCase__ = ( 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D', ) lowerCAmelCase__ = False lowerCAmelCase__ = (320, 640, 1_280, 1_280) lowerCAmelCase__ = 2 lowerCAmelCase__ = 8 lowerCAmelCase__ = None lowerCAmelCase__ = 1_280 lowerCAmelCase__ = 0.0 lowerCAmelCase__ = False lowerCAmelCase__ = jnp.floataa lowerCAmelCase__ = True lowerCAmelCase__ = 0 lowerCAmelCase__ = 'rgb' lowerCAmelCase__ = (16, 32, 96, 256) def _UpperCAmelCase ( self , UpperCAmelCase ): '''simple docstring''' _lowercase = (1, self.in_channels, self.sample_size, self.sample_size) _lowercase = jnp.zeros(_snake_case , dtype=jnp.floataa ) _lowercase = jnp.ones((1,) , dtype=jnp.intaa ) _lowercase = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) _lowercase = (1, 3, self.sample_size * 8, self.sample_size * 8) _lowercase = jnp.zeros(_snake_case , dtype=jnp.floataa ) _lowercase , _lowercase = jax.random.split(_snake_case ) _lowercase = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case )["params"] def _UpperCAmelCase ( self ): '''simple docstring''' _lowercase = self.block_out_channels _lowercase = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _lowercase = self.num_attention_heads or self.attention_head_dim # input _lowercase = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _lowercase = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) _lowercase = FlaxTimestepEmbedding(_snake_case , dtype=self.dtype ) _lowercase = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) _lowercase = self.only_cross_attention if isinstance(_snake_case , _snake_case ): _lowercase = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_snake_case , _snake_case ): _lowercase = (num_attention_heads,) * len(self.down_block_types ) # down _lowercase = [] _lowercase = [] _lowercase = block_out_channels[0] _lowercase = nn.Conv( _snake_case , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_snake_case ) for i, down_block_type in enumerate(self.down_block_types ): _lowercase = output_channel _lowercase = block_out_channels[i] _lowercase = i == len(_snake_case ) - 1 if down_block_type == "CrossAttnDownBlock2D": _lowercase = FlaxCrossAttnDownBlockaD( in_channels=_snake_case , out_channels=_snake_case , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: _lowercase = FlaxDownBlockaD( in_channels=_snake_case , out_channels=_snake_case , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_snake_case ) for _ in range(self.layers_per_block ): _lowercase = nn.Conv( _snake_case , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_snake_case ) if not is_final_block: _lowercase = nn.Conv( _snake_case , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_snake_case ) _lowercase = down_blocks _lowercase = controlnet_down_blocks # mid _lowercase = block_out_channels[-1] _lowercase = FlaxUNetMidBlockaDCrossAttn( in_channels=_snake_case , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) _lowercase = nn.Conv( _snake_case , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 1.0 , UpperCAmelCase = True , UpperCAmelCase = False , ): '''simple docstring''' _lowercase = self.controlnet_conditioning_channel_order if channel_order == "bgr": _lowercase = jnp.flip(_snake_case , axis=1 ) # 1. time if not isinstance(_snake_case , jnp.ndarray ): _lowercase = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_snake_case , jnp.ndarray ) and len(timesteps.shape ) == 0: _lowercase = timesteps.astype(dtype=jnp.floataa ) _lowercase = jnp.expand_dims(_snake_case , 0 ) _lowercase = self.time_proj(_snake_case ) _lowercase = self.time_embedding(_snake_case ) # 2. pre-process _lowercase = jnp.transpose(_snake_case , (0, 2, 3, 1) ) _lowercase = self.conv_in(_snake_case ) _lowercase = jnp.transpose(_snake_case , (0, 2, 3, 1) ) _lowercase = self.controlnet_cond_embedding(_snake_case ) sample += controlnet_cond # 3. down _lowercase = (sample,) for down_block in self.down_blocks: if isinstance(_snake_case , _snake_case ): _lowercase , _lowercase = down_block(_snake_case , _snake_case , _snake_case , deterministic=not train ) else: _lowercase , _lowercase = down_block(_snake_case , _snake_case , deterministic=not train ) down_block_res_samples += res_samples # 4. mid _lowercase = self.mid_block(_snake_case , _snake_case , _snake_case , deterministic=not train ) # 5. contronet blocks _lowercase = () for down_block_res_sample, controlnet_block in zip(_snake_case , self.controlnet_down_blocks ): _lowercase = controlnet_block(_snake_case ) controlnet_down_block_res_samples += (down_block_res_sample,) _lowercase = controlnet_down_block_res_samples _lowercase = self.controlnet_mid_block(_snake_case ) # 6. scaling _lowercase = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=_snake_case , mid_block_res_sample=_snake_case )
398
'''simple docstring''' from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class _SCREAMING_SNAKE_CASE : """simple docstring""" pass
316
0
"""simple docstring""" from ... import PretrainedConfig __UpperCamelCase = { '''sijunhe/nezha-cn-base''': '''https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json''', } class lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP SCREAMING_SNAKE_CASE_ : int = """nezha""" def __init__( self , lowerCAmelCase__=21_128 , lowerCAmelCase__=768 , lowerCAmelCase__=12 , lowerCAmelCase__=12 , lowerCAmelCase__=3_072 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=512 , lowerCAmelCase__=64 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1e-12 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__=3 , lowerCAmelCase__=True , **lowerCAmelCase__ , ) -> Any: super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) 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 = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = max_relative_position SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = classifier_dropout SCREAMING_SNAKE_CASE = use_cache
327
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __A ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = BlipImageProcessor() SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-BertModel' ) SCREAMING_SNAKE_CASE = BlipProcessor(lowerCAmelCase__ , lowerCAmelCase__ ) processor.save_pretrained(self.tmpdirname ) def __A ( self , **lowerCAmelCase__ ) -> Tuple: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ).tokenizer def __A ( self , **lowerCAmelCase__ ) -> int: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ).image_processor def __A ( self ) -> str: shutil.rmtree(self.tmpdirname ) def __A ( self ) -> List[Any]: SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self ) -> List[str]: SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) SCREAMING_SNAKE_CASE = BlipProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=lowerCAmelCase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCAmelCase__ ) def __A ( self ) -> Any: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = image_processor(lowerCAmelCase__ , return_tensors='np' ) SCREAMING_SNAKE_CASE = processor(images=lowerCAmelCase__ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __A ( self ) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = 'lower newer' SCREAMING_SNAKE_CASE = processor(text=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer(lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self ) -> int: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = 'lower newer' SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def __A ( self ) -> Tuple: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) def __A ( self ) -> str: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = 'lower newer' SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] )
327
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowercase ( UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[List[PIL.Image.Image], np.ndarray] SCREAMING_SNAKE_CASE : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowercase ( UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE : np.ndarray SCREAMING_SNAKE_CASE : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
605
from __future__ import annotations def SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): """simple docstring""" if len(UpperCAmelCase__ ) == 0: return array _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = min(UpperCAmelCase__ ), max(UpperCAmelCase__ ) # Compute the variables _SCREAMING_SNAKE_CASE = _max - _min + 1 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: _SCREAMING_SNAKE_CASE = i - _min _SCREAMING_SNAKE_CASE = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. _SCREAMING_SNAKE_CASE = 0 for i in range(UpperCAmelCase__ ): while holes_repeat[i] > 0: _SCREAMING_SNAKE_CASE = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() snake_case : Dict = input('Enter numbers separated by comma:\n') snake_case : List[Any] = [int(x) for x in user_input.split(',')] print(pigeon_sort(unsorted))
605
1
"""simple docstring""" 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 SCREAMING_SNAKE_CASE__:List[str] = False class snake_case__ ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case__ ( unittest.TestCase ): def a__ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a__ ( self ): __a = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) __a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __a = torch.manual_seed(0 ) __a = pipe.dual_guided( prompt="first prompt" , image=a_ , text_to_image_strength=0.75 , generator=a_ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(a_ ) __a = VersatileDiffusionPipeline.from_pretrained(a_ , torch_dtype=torch.floataa ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) __a = generator.manual_seed(0 ) __a = pipe.dual_guided( prompt="first prompt" , image=a_ , text_to_image_strength=0.75 , generator=a_ , 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 a__ ( self ): __a = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) __a = """cyberpunk 2077""" __a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __a = torch.manual_seed(0 ) __a = pipe.dual_guided( prompt=a_ , image=a_ , text_to_image_strength=0.75 , generator=a_ , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" , ).images __a = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __a = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 __a = """A painting of a squirrel eating a burger """ __a = torch.manual_seed(0 ) __a = pipe.text_to_image( prompt=a_ , generator=a_ , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" ).images __a = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __a = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 __a = pipe.image_variation(a_ , generator=a_ , output_type="numpy" ).images __a = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __a = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
706
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=99 , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=9 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase=8 , lowerCamelCase=0.1 , lowerCamelCase=0.002 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0 , lowerCamelCase=None , lowerCamelCase=None , ): __a = parent __a = batch_size __a = encoder_seq_length __a = decoder_seq_length # For common tests __a = self.decoder_seq_length __a = is_training __a = use_attention_mask __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = d_ff __a = relative_attention_num_buckets __a = dropout_rate __a = initializer_factor __a = eos_token_id __a = pad_token_id __a = decoder_start_token_id __a = None __a = decoder_layers def a__ ( self ): return TaConfig.from_pretrained("google/umt5-base" ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if attention_mask is None: __a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __a = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=lowerCamelCase ) if decoder_head_mask is None: __a = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) if cross_attn_head_mask is None: __a = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def a__ ( self ): __a = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __a = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __a = input_ids.clamp(self.pad_token_id + 1 ) __a = decoder_input_ids.clamp(self.pad_token_id + 1 ) __a = self.get_config() __a = config.num_attention_heads __a = self.prepare_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return config, input_dict def a__ ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def a__ ( self ): return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase , attention_mask=lowerCamelCase , decoder_attention_mask=lowerCamelCase , ) __a = model(input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase ) __a = result.last_hidden_state __a = result.past_key_values __a = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(lowerCamelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).get_decoder().to(lowerCamelCase ).eval() # first forward pass __a = model(lowerCamelCase , use_cache=lowerCamelCase ) __a = model(lowerCamelCase ) __a = model(lowerCamelCase , use_cache=lowerCamelCase ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) + 1 ) __a , __a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = model(lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , past_key_values=lowerCamelCase )["last_hidden_state"] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -1, random_slice_idx].detach() __a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).to(lowerCamelCase ).half().eval() __a = model(**lowerCamelCase )["last_hidden_state"] self.parent.assertFalse(torch.isnan(lowerCamelCase ).any().item() ) @require_torch class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _snake_case : int = (UMTaForConditionalGeneration,) if is_torch_available() else () _snake_case : Optional[int] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _snake_case : List[Any] = True _snake_case : Union[str, Any] = False _snake_case : Union[str, Any] = False _snake_case : Tuple = True _snake_case : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _snake_case : Optional[Any] = [0.8, 0.9] def a__ ( self ): __a = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() __a = UMTaModel(config_and_inputs[0] ).to(lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( lowerCamelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=lowerCamelCase , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*lowerCamelCase ) def a__ ( self ): __a = ["encoder_attentions", "decoder_attentions", "cross_attentions"] __a = self.model_tester.prepare_config_and_inputs() __a = config_and_inputs[0] __a = UMTaForConditionalGeneration(lowerCamelCase ).eval() model.to(lowerCamelCase ) __a = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=lowerCamelCase ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), } for attn_name, (name, mask) in zip(lowerCamelCase , head_masking.items() ): __a = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __a = torch.ones( config.num_decoder_layers , config.num_heads , device=lowerCamelCase ) __a = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=lowerCamelCase , return_dict_in_generate=lowerCamelCase , **lowerCamelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step __a = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("Does not work on the tiny model as we keep hitting edge cases." ) def a__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow @unittest.skip( "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" ) def a__ ( self ): __a = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=lowerCamelCase ).to(lowerCamelCase ) __a = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=lowerCamelCase , legacy=lowerCamelCase ) __a = [ "Bonjour monsieur <extra_id_0> bien <extra_id_1>.", "No se como puedo <extra_id_0>.", "This is the reason why we <extra_id_0> them.", "The <extra_id_0> walks in <extra_id_1>, seats", "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.", ] __a = tokenizer(lowerCamelCase , return_tensors="pt" , padding=lowerCamelCase ).input_ids # fmt: off __a = torch.tensor( [ [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(lowerCamelCase , lowerCamelCase ) __a = model.generate(input_ids.to(lowerCamelCase ) ) __a = [ "<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>", "<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", ] __a = tokenizer.batch_decode(lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" from __future__ import annotations def __A (_SCREAMING_SNAKE_CASE ) ->list[int]: """simple docstring""" lowerCAmelCase__ :str = [True] * limit lowerCAmelCase__ :Optional[int] = False lowerCAmelCase__ :str = False lowerCAmelCase__ :Dict = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): lowerCAmelCase__ :Union[str, Any] = i * 2 while index < limit: lowerCAmelCase__ :Dict = False lowerCAmelCase__ :Any = index + i lowerCAmelCase__ :List[Any] = [2] for i in range(3 , _SCREAMING_SNAKE_CASE , 2 ): if is_prime[i]: primes.append(_SCREAMING_SNAKE_CASE ) return primes def __A (_SCREAMING_SNAKE_CASE = 100_0000 ) ->int: """simple docstring""" lowerCAmelCase__ :Tuple = prime_sieve(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = 0 lowerCAmelCase__ :Any = 0 for i in range(len(_SCREAMING_SNAKE_CASE ) ): for j in range(i + length , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :Any = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: lowerCAmelCase__ :List[str] = j - i lowerCAmelCase__ :Tuple = sol return largest if __name__ == "__main__": print(F'''{solution() = }''')
93
'''simple docstring''' import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _A = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ["""memory_attention""", """encoder_attn"""], ["""attention""", """attn"""], ["""/""", """."""], [""".LayerNorm.gamma""", """_layer_norm.weight"""], [""".LayerNorm.beta""", """_layer_norm.bias"""], ["""r.layer_""", """r.layers."""], ["""output_proj""", """out_proj"""], ["""ffn.dense_1.""", """fc2."""], ["""ffn.dense.""", """fc1."""], ["""ffn_layer_norm""", """final_layer_norm"""], ["""kernel""", """weight"""], ["""encoder_layer_norm.""", """encoder.layer_norm."""], ["""decoder_layer_norm.""", """decoder.layer_norm."""], ["""embeddings.weights""", """shared.weight"""], ] def A_ ( __SCREAMING_SNAKE_CASE : Dict ) -> List[Any]: for pegasus_name, hf_name in PATTERNS: __SCREAMING_SNAKE_CASE : List[str] = k.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return k def A_ ( __SCREAMING_SNAKE_CASE : dict , __SCREAMING_SNAKE_CASE : dict ) -> PegasusForConditionalGeneration: __SCREAMING_SNAKE_CASE : Tuple = DEFAULTS.copy() cfg_kwargs.update(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Union[str, Any] = PegasusConfig(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : List[Any] = PegasusForConditionalGeneration(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Tuple = torch_model.model.state_dict() __SCREAMING_SNAKE_CASE : Dict = {} for k, v in tf_weights.items(): __SCREAMING_SNAKE_CASE : List[str] = rename_state_dict_key(__SCREAMING_SNAKE_CASE ) if new_k not in sd: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: __SCREAMING_SNAKE_CASE : Dict = v.T __SCREAMING_SNAKE_CASE : Any = torch.tensor(__SCREAMING_SNAKE_CASE , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, f"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected __SCREAMING_SNAKE_CASE : int = torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1] ) __SCREAMING_SNAKE_CASE : Optional[Any] = mapping['''shared.weight'''] __SCREAMING_SNAKE_CASE : Tuple = mapping['''shared.weight'''] __SCREAMING_SNAKE_CASE : List[Any] = {k: torch.zeros_like(__SCREAMING_SNAKE_CASE ) for k, v in sd.items() if k.endswith('''bias''' ) and k not in mapping} mapping.update(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = torch_model.model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : List[Any] = [ k for k in missing if k not in ['''encoder.embed_positions.weight''', '''decoder.embed_positions.weight'''] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def A_ ( __SCREAMING_SNAKE_CASE : Union[str, Any]="./ckpt/aeslc/model.ckpt-32000" ) -> Dict: __SCREAMING_SNAKE_CASE : Any = tf.train.list_variables(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''Adafactor''', '''global_step'''] for name, shape in tqdm(__SCREAMING_SNAKE_CASE , desc='''converting tf checkpoint to dict''' ): __SCREAMING_SNAKE_CASE : Tuple = any(pat in name for pat in ignore_name ) if skip_key: continue __SCREAMING_SNAKE_CASE : Any = tf.train.load_variable(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Dict = array return tf_weights def A_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ) -> Optional[int]: # save tokenizer first __SCREAMING_SNAKE_CASE : List[str] = Path(__SCREAMING_SNAKE_CASE ).parent.name __SCREAMING_SNAKE_CASE : Optional[int] = task_specific_params[f"""summarization_{dataset}"""]['''max_position_embeddings'''] __SCREAMING_SNAKE_CASE : List[str] = PegasusTokenizer.from_pretrained('''sshleifer/pegasus''' , model_max_length=__SCREAMING_SNAKE_CASE ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(__SCREAMING_SNAKE_CASE ) # convert model __SCREAMING_SNAKE_CASE : Any = get_tf_weights_as_numpy(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : str = task_specific_params[f"""summarization_{dataset}"""] if dataset == "large": __SCREAMING_SNAKE_CASE : Dict = task_specific_params __SCREAMING_SNAKE_CASE : Optional[int] = convert_pegasus(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) torch_model.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : List[Any] = torch_model.state_dict() sd.pop('''model.decoder.embed_positions.weight''' ) sd.pop('''model.encoder.embed_positions.weight''' ) torch.save(__SCREAMING_SNAKE_CASE , Path(__SCREAMING_SNAKE_CASE ) / '''pytorch_model.bin''' ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument("""tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") _A = parser.parse_args() if args.save_dir is None: _A = Path(args.tf_ckpt_path).parent.name _A = os.path.join("""pegasus""", dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
158
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCamelCase__ : Optional[Any] = logging.get_logger(__name__) UpperCamelCase__ : List[Any] = { '''shi-labs/dinat-mini-in1k-224''': '''https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json''', # See all Dinat models at https://huggingface.co/models?filter=dinat } class _UpperCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' _A : Optional[int] = '''dinat''' _A : Optional[Any] = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Optional[Any] , lowerCAmelCase__ : Dict=4 , lowerCAmelCase__ : List[Any]=3 , lowerCAmelCase__ : List[str]=6_4 , lowerCAmelCase__ : Tuple=[3, 4, 6, 5] , lowerCAmelCase__ : Optional[Any]=[2, 4, 8, 1_6] , lowerCAmelCase__ : str=7 , lowerCAmelCase__ : Optional[Any]=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] , lowerCAmelCase__ : Tuple=3.0 , lowerCAmelCase__ : str=True , lowerCAmelCase__ : Union[str, Any]=0.0 , lowerCAmelCase__ : Dict=0.0 , lowerCAmelCase__ : List[Any]=0.1 , lowerCAmelCase__ : Union[str, Any]="gelu" , lowerCAmelCase__ : int=0.02 , lowerCAmelCase__ : Any=1E-5 , lowerCAmelCase__ : int=0.0 , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : Optional[int]=None , **lowerCAmelCase__ : Union[str, Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : str = patch_size __SCREAMING_SNAKE_CASE : Any = num_channels __SCREAMING_SNAKE_CASE : Any = embed_dim __SCREAMING_SNAKE_CASE : Optional[int] = depths __SCREAMING_SNAKE_CASE : Dict = len(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = num_heads __SCREAMING_SNAKE_CASE : Optional[int] = kernel_size __SCREAMING_SNAKE_CASE : str = dilations __SCREAMING_SNAKE_CASE : List[Any] = mlp_ratio __SCREAMING_SNAKE_CASE : Optional[Any] = qkv_bias __SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob __SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Dict = drop_path_rate __SCREAMING_SNAKE_CASE : str = hidden_act __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Tuple = initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE : int = int(embed_dim * 2 ** (len(lowerCAmelCase__ ) - 1) ) __SCREAMING_SNAKE_CASE : str = layer_scale_init_value __SCREAMING_SNAKE_CASE : int = ["""stem"""] + [F"stage{idx}" for idx in range(1 , len(lowerCAmelCase__ ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = get_aligned_output_features_output_indices( out_features=lowerCAmelCase__ , out_indices=lowerCAmelCase__ , stage_names=self.stage_names )
178
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True) def lowerCAmelCase_ ( _lowerCamelCase: int ): if hor == 1_28: __SCREAMING_SNAKE_CASE : Any = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") __SCREAMING_SNAKE_CASE : List[Any] = (32, 1_28, 2_56) __SCREAMING_SNAKE_CASE : str = ("""UpResnetBlock1D""", """UpResnetBlock1D""") elif hor == 32: __SCREAMING_SNAKE_CASE : Union[str, Any] = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") __SCREAMING_SNAKE_CASE : str = (32, 64, 1_28, 2_56) __SCREAMING_SNAKE_CASE : Tuple = ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D""") __SCREAMING_SNAKE_CASE : Optional[Any] = torch.load(F"/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch" ) __SCREAMING_SNAKE_CASE : Any = model.state_dict() __SCREAMING_SNAKE_CASE : Optional[Any] = { """down_block_types""": down_block_types, """block_out_channels""": block_out_channels, """up_block_types""": up_block_types, """layers_per_block""": 1, """use_timestep_embedding""": True, """out_block_type""": """OutConv1DBlock""", """norm_num_groups""": 8, """downsample_each_block""": False, """in_channels""": 14, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """flip_sin_to_cos""": False, """freq_shift""": 1, """sample_size""": 6_55_36, """mid_block_type""": """MidResTemporalBlock1D""", """act_fn""": """mish""", } __SCREAMING_SNAKE_CASE : int = UNetaDModel(**_lowerCamelCase ) print(F"length of state dict: {len(state_dict.keys() )}" ) print(F"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) __SCREAMING_SNAKE_CASE : Optional[int] = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(_lowerCamelCase ) hf_value_function.load_state_dict(_lowerCamelCase ) torch.save(hf_value_function.state_dict() , F"hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin" ) with open(F"hub/hopper-medium-v2/unet/hor{hor}/config.json" , """w""" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) def lowerCAmelCase_ ( ): __SCREAMING_SNAKE_CASE : Dict = { """in_channels""": 14, """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""), """up_block_types""": (), """out_block_type""": """ValueFunction""", """mid_block_type""": """ValueFunctionMidBlock1D""", """block_out_channels""": (32, 64, 1_28, 2_56), """layers_per_block""": 1, """downsample_each_block""": True, """sample_size""": 6_55_36, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """use_timestep_embedding""": True, """flip_sin_to_cos""": False, """freq_shift""": 1, """norm_num_groups""": 8, """act_fn""": """mish""", } __SCREAMING_SNAKE_CASE : Optional[int] = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""" ) __SCREAMING_SNAKE_CASE : Dict = model __SCREAMING_SNAKE_CASE : List[Any] = UNetaDModel(**_lowerCamelCase ) print(F"length of state dict: {len(state_dict.keys() )}" ) print(F"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) __SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __SCREAMING_SNAKE_CASE : str = state_dict.pop(_lowerCamelCase ) hf_value_function.load_state_dict(_lowerCamelCase ) torch.save(hf_value_function.state_dict() , """hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin""" ) with open("""hub/hopper-medium-v2/value_function/config.json""" , """w""" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": unet(32) # unet(128) value_function()
178
1
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class UpperCAmelCase_ : '''simple docstring''' def __init__( self , _lowercase , _lowercase=13 , _lowercase=7 , _lowercase=False , _lowercase=True , _lowercase=False , _lowercase=True , _lowercase=33 , _lowercase=32 , _lowercase=5 , _lowercase=4 , _lowercase=37 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=512 , _lowercase=16 , _lowercase=2 , _lowercase=0.02 , _lowercase=3 , _lowercase=4 , _lowercase=None , ): """simple docstring""" _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = seq_length _lowerCAmelCase = is_training _lowerCAmelCase = use_input_mask _lowerCAmelCase = use_token_type_ids _lowerCAmelCase = use_labels _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_act _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = type_vocab_size _lowerCAmelCase = type_sequence_label_size _lowerCAmelCase = initializer_range _lowerCAmelCase = num_labels _lowerCAmelCase = num_choices _lowerCAmelCase = scope def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase = None if self.use_input_mask: _lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCAmelCase = None _lowerCAmelCase = None _lowerCAmelCase = None if self.use_labels: _lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) _lowerCAmelCase = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self ): """simple docstring""" return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def _lowercase ( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" _lowerCAmelCase = EsmModel(config=_lowercase ) model.to(_lowercase ) model.eval() _lowerCAmelCase = model(_lowercase , attention_mask=_lowercase ) _lowerCAmelCase = model(_lowercase ) _lowerCAmelCase = model(_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _lowercase ( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" _lowerCAmelCase = EsmForMaskedLM(config=_lowercase ) model.to(_lowercase ) model.eval() _lowerCAmelCase = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" _lowerCAmelCase = self.num_labels _lowerCAmelCase = EsmForTokenClassification(config=_lowercase ) model.to(_lowercase ) model.eval() _lowerCAmelCase = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) = config_and_inputs _lowerCAmelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' _lowercase : List[str] = False _lowercase : Tuple = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) _lowercase : Tuple = () _lowercase : Optional[int] = ( { '''feature-extraction''': EsmModel, '''fill-mask''': EsmForMaskedLM, '''text-classification''': EsmForSequenceClassification, '''token-classification''': EsmForTokenClassification, '''zero-shot''': EsmForSequenceClassification, } if is_torch_available() else {} ) _lowercase : int = True def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = EsmModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=_lowercase , hidden_size=37 ) def _lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _lowerCAmelCase = type self.model_tester.create_and_check_model(*_lowercase ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowercase ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowercase ) @slow def _lowercase ( self ): """simple docstring""" for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase = EsmModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs()[0] _lowerCAmelCase = EsmEmbeddings(config=_lowercase ) _lowerCAmelCase = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) _lowerCAmelCase = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _lowerCAmelCase = create_position_ids_from_input_ids(_lowercase , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(_lowercase , _lowercase ) ) ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs()[0] _lowerCAmelCase = EsmEmbeddings(config=_lowercase ) _lowerCAmelCase = torch.empty(2 , 4 , 30 ) _lowerCAmelCase = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _lowerCAmelCase = torch.as_tensor([expected_single_positions, expected_single_positions] ) _lowerCAmelCase = embeddings.create_position_ids_from_inputs_embeds(_lowercase ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(_lowercase , _lowercase ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def _lowercase ( self ): """simple docstring""" pass @unittest.skip("""Esm does not support embedding resizing""" ) def _lowercase ( self ): """simple docstring""" pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _lowercase ( self ): """simple docstring""" pass @require_torch class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' @slow def _lowercase ( self ): """simple docstring""" with torch.no_grad(): _lowerCAmelCase = EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _lowerCAmelCase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) _lowerCAmelCase = model(_lowercase )[0] _lowerCAmelCase = 33 _lowerCAmelCase = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , _lowercase ) _lowerCAmelCase = torch.tensor( [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowercase , atol=1e-4 ) ) @slow def _lowercase ( self ): """simple docstring""" with torch.no_grad(): _lowerCAmelCase = EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _lowerCAmelCase = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) _lowerCAmelCase = model(_lowercase )[0] # compare the actual values for a slice. _lowerCAmelCase = torch.tensor( [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowercase , atol=1e-4 ) )
5
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def __UpperCAmelCase ( lowerCamelCase_ : np.ndarray , lowerCamelCase_ : np.ndarray ) -> float: """simple docstring""" return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(lowerCamelCase_ , lowerCamelCase_ ) ) ) def __UpperCAmelCase ( lowerCamelCase_ : np.ndarray , lowerCamelCase_ : np.ndarray ) -> list[list[list[float] | float]]: """simple docstring""" if dataset.ndim != value_array.ndim: SCREAMING_SNAKE_CASE_ : Optional[int] = ( 'Wrong input data\'s dimensions... ' F'dataset : {dataset.ndim}, value_array : {value_array.ndim}' ) raise ValueError(lowerCamelCase_ ) try: if dataset.shape[1] != value_array.shape[1]: SCREAMING_SNAKE_CASE_ : List[Any] = ( 'Wrong input data\'s shape... ' F'dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}' ) raise ValueError(lowerCamelCase_ ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError('Wrong shape' ) if dataset.dtype != value_array.dtype: SCREAMING_SNAKE_CASE_ : Tuple = ( 'Input data have different datatype... ' F'dataset : {dataset.dtype}, value_array : {value_array.dtype}' ) raise TypeError(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for value in value_array: SCREAMING_SNAKE_CASE_ : str = euclidean(lowerCamelCase_ , dataset[0] ) SCREAMING_SNAKE_CASE_ : List[Any] = dataset[0].tolist() for dataset_value in dataset[1:]: SCREAMING_SNAKE_CASE_ : Optional[Any] = euclidean(lowerCamelCase_ , lowerCamelCase_ ) if dist > temp_dist: SCREAMING_SNAKE_CASE_ : Optional[int] = temp_dist SCREAMING_SNAKE_CASE_ : Union[str, Any] = dataset_value.tolist() answer.append([vector, dist] ) return answer def __UpperCAmelCase ( lowerCamelCase_ : np.ndarray , lowerCamelCase_ : np.ndarray ) -> float: """simple docstring""" return np.dot(lowerCamelCase_ , lowerCamelCase_ ) / (norm(lowerCamelCase_ ) * norm(lowerCamelCase_ )) if __name__ == "__main__": import doctest doctest.testmod()
105
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint lowercase : Optional[Any] = { "169M": 12, "430M": 24, "1B5": 24, "3B": 32, "7B": 32, "14B": 40, } lowercase : List[str] = { "169M": 7_68, "430M": 10_24, "1B5": 20_48, "3B": 25_60, "7B": 40_96, "14B": 51_20, } def snake_case__ ( lowerCamelCase_ ): A : Optional[Any] = list(state_dict.keys() ) for name in state_dict_keys: A : int = state_dict.pop(lowerCamelCase_ ) # emb -> embedding if name.startswith('''emb.''' ): A : Optional[int] = name.replace('''emb.''' , '''embeddings.''' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('''blocks.0.ln0''' ): A : int = name.replace('''blocks.0.ln0''' , '''blocks.0.pre_ln''' ) # att -> attention A : Tuple = re.sub(r'''blocks\.(\d+)\.att''' , r'''blocks.\1.attention''' , lowerCamelCase_ ) # ffn -> feed_forward A : Union[str, Any] = re.sub(r'''blocks\.(\d+)\.ffn''' , r'''blocks.\1.feed_forward''' , lowerCamelCase_ ) # time_mix_k -> time_mix_key and reshape if name.endswith('''.time_mix_k''' ): A : str = name.replace('''.time_mix_k''' , '''.time_mix_key''' ) # time_mix_v -> time_mix_value and reshape if name.endswith('''.time_mix_v''' ): A : Any = name.replace('''.time_mix_v''' , '''.time_mix_value''' ) # time_mix_r -> time_mix_key and reshape if name.endswith('''.time_mix_r''' ): A : List[Any] = name.replace('''.time_mix_r''' , '''.time_mix_receptance''' ) if name != "head.weight": A : Dict = '''rwkv.''' + name A : str = weight return state_dict def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=False , lowerCamelCase_=None ): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('''No `--tokenizer_file` provided, we will use the default tokenizer.''' ) A : Tuple = 50277 A : str = AutoTokenizer.from_pretrained('''EleutherAI/gpt-neox-20b''' ) else: A : Optional[Any] = PreTrainedTokenizerFast(tokenizer_file=lowerCamelCase_ ) A : Optional[Any] = len(lowerCamelCase_ ) tokenizer.save_pretrained(lowerCamelCase_ ) # 2. Build the config A : Optional[int] = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: A : Any = candidate break if size is None: raise ValueError('''Could not infer the size, please provide it with the `--size` argument.''' ) if size not in possible_sizes: raise ValueError(F'`size` should be one of {possible_sizes}, got {size}.' ) A : Any = RwkvConfig( vocab_size=lowerCamelCase_ , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(lowerCamelCase_ ) # 3. Download model file then convert state_dict A : Tuple = hf_hub_download(lowerCamelCase_ , lowerCamelCase_ ) A : Union[str, Any] = torch.load(lowerCamelCase_ , map_location='''cpu''' ) A : List[Any] = convert_state_dict(lowerCamelCase_ ) # 4. Split in shards and save A , A : List[Any] = shard_checkpoint(lowerCamelCase_ ) for shard_file, shard in shards.items(): torch.save(lowerCamelCase_ , os.path.join(lowerCamelCase_ , lowerCamelCase_ ) ) if index is not None: A : Optional[Any] = os.path.join(lowerCamelCase_ , lowerCamelCase_ ) # Save the index as well with open(lowerCamelCase_ , '''w''' , encoding='''utf-8''' ) as f: A : List[Any] = json.dumps(lowerCamelCase_ , indent=2 , sort_keys=lowerCamelCase_ ) + '''\n''' f.write(lowerCamelCase_ ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( '''Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.''' ) A : List[str] = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: A : Dict = torch.load(os.path.join(lowerCamelCase_ , lowerCamelCase_ ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(lowerCamelCase_ , lowerCamelCase_ ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('''Please provide a `model_name` to push the model to the Hub.''' ) A : List[Any] = AutoModelForCausalLM.from_pretrained(lowerCamelCase_ ) model.push_to_hub(lowerCamelCase_ , max_shard_size='''2GB''' ) tokenizer.push_to_hub(lowerCamelCase_ ) if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--repo_id", default=None, type=str, required=True, help="Repo ID from which to pull the checkpoint." ) parser.add_argument( "--checkpoint_file", default=None, type=str, required=True, help="Name of the checkpoint file in the repo." ) parser.add_argument( "--output_dir", default=None, type=str, required=True, help="Where to save the converted model." ) parser.add_argument( "--tokenizer_file", default=None, type=str, help="Path to the tokenizer file to use (if not provided, only the model is converted).", ) parser.add_argument( "--size", default=None, type=str, help="Size of the model. Will be inferred from the `checkpoint_file` if not passed.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Push to the Hub the converted model.", ) parser.add_argument( "--model_name", default=None, type=str, help="Name of the pushed model on the Hub, including the username / organization.", ) lowercase : List[Any] = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
423
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase : Any = abspath(join(dirname(dirname(__file__)), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def snake_case__ ( lowerCamelCase_ ): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCamelCase_ ) def snake_case__ ( lowerCamelCase_ ): from diffusers.utils.testing_utils import pytest_terminal_summary_main A : Union[str, Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowerCamelCase_ , id=lowerCamelCase_ )
423
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class __SCREAMING_SNAKE_CASE ( _a ): snake_case : int = """gpt_neox_japanese""" def __init__( self , __lowerCAmelCase=32000 , __lowerCAmelCase=2560 , __lowerCAmelCase=32 , __lowerCAmelCase=32 , __lowerCAmelCase=4 , __lowerCAmelCase="gelu" , __lowerCAmelCase=1.00 , __lowerCAmelCase=10000 , __lowerCAmelCase=2048 , __lowerCAmelCase=0.02 , __lowerCAmelCase=1E-5 , __lowerCAmelCase=True , __lowerCAmelCase=31996 , __lowerCAmelCase=31999 , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.0 , **__lowerCAmelCase , ): super().__init__(bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) UpperCamelCase__ = vocab_size UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_multiple_size UpperCamelCase__ = hidden_act UpperCamelCase__ = rotary_pct UpperCamelCase__ = rotary_emb_base UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = use_cache UpperCamelCase__ = attention_dropout UpperCamelCase__ = hidden_dropout
619
import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case : Dict = CodeGenTokenizer snake_case : Dict = CodeGenTokenizerFast snake_case : Tuple = True snake_case : Optional[int] = {"""add_prefix_space""": True} snake_case : int = False def _lowerCamelCase ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] UpperCamelCase__ = dict(zip(__lowerCAmelCase , range(len(__lowerCAmelCase ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__lowerCAmelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__lowerCAmelCase ) ) def _lowerCamelCase ( self , **__lowerCAmelCase ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def _lowerCamelCase ( self , **__lowerCAmelCase ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def _lowerCamelCase ( self , __lowerCAmelCase ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def _lowerCamelCase ( self ): UpperCamelCase__ = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(__lowerCAmelCase , add_prefix_space=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , __lowerCAmelCase ) def _lowerCamelCase ( self ): if not self.test_rust_tokenizer: return UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_rust_tokenizer(add_prefix_space=__lowerCAmelCase ) UpperCamelCase__ = """lower newer""" # Testing tokenization UpperCamelCase__ = tokenizer.tokenize(__lowerCAmelCase , add_prefix_space=__lowerCAmelCase ) UpperCamelCase__ = rust_tokenizer.tokenize(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) # Testing conversion to ids without special tokens UpperCamelCase__ = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase ) UpperCamelCase__ = rust_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) # Testing conversion to ids with special tokens UpperCamelCase__ = self.get_rust_tokenizer(add_prefix_space=__lowerCAmelCase ) UpperCamelCase__ = tokenizer.encode(__lowerCAmelCase , add_prefix_space=__lowerCAmelCase ) UpperCamelCase__ = rust_tokenizer.encode(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) # Testing the unknown token UpperCamelCase__ = tokens + [rust_tokenizer.unk_token] UpperCamelCase__ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , __lowerCAmelCase ) def _lowerCamelCase ( self , *__lowerCAmelCase , **__lowerCAmelCase ): # It's very difficult to mix/test pretokenization with byte-level # And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _lowerCamelCase ( self , __lowerCAmelCase=15 ): 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(__lowerCAmelCase , **__lowerCAmelCase ) # Simple input UpperCamelCase__ = """This is a simple input""" UpperCamelCase__ = ["""This is a simple input 1""", """This is a simple input 2"""] UpperCamelCase__ = ("""This is a simple input""", """This is a pair""") UpperCamelCase__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__lowerCAmelCase , tokenizer_r.encode , __lowerCAmelCase , max_length=__lowerCAmelCase , padding="""max_length""" ) # Simple input self.assertRaises(__lowerCAmelCase , tokenizer_r.encode_plus , __lowerCAmelCase , max_length=__lowerCAmelCase , padding="""max_length""" ) # Simple input self.assertRaises( __lowerCAmelCase , tokenizer_r.batch_encode_plus , __lowerCAmelCase , max_length=__lowerCAmelCase , padding="""max_length""" , ) # Pair input self.assertRaises(__lowerCAmelCase , tokenizer_r.encode , __lowerCAmelCase , max_length=__lowerCAmelCase , padding="""max_length""" ) # Pair input self.assertRaises(__lowerCAmelCase , tokenizer_r.encode_plus , __lowerCAmelCase , max_length=__lowerCAmelCase , padding="""max_length""" ) # Pair input self.assertRaises( __lowerCAmelCase , tokenizer_r.batch_encode_plus , __lowerCAmelCase , max_length=__lowerCAmelCase , padding="""max_length""" , ) def _lowerCamelCase ( self ): UpperCamelCase__ = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token="""<pad>""" ) # Simple input UpperCamelCase__ = """This is a simple input""" UpperCamelCase__ = ["""This is a simple input looooooooong""", """This is a simple input"""] UpperCamelCase__ = ("""This is a simple input""", """This is a pair""") UpperCamelCase__ = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] UpperCamelCase__ = tokenizer.pad_token_id UpperCamelCase__ = tokenizer(__lowerCAmelCase , padding="""max_length""" , max_length=30 , return_tensors="""np""" ) UpperCamelCase__ = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase , truncate=__lowerCAmelCase , return_tensors="""np""" ) UpperCamelCase__ = tokenizer(*__lowerCAmelCase , padding="""max_length""" , max_length=60 , return_tensors="""np""" ) UpperCamelCase__ = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase , truncate=__lowerCAmelCase , return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def _lowerCamelCase ( self ): UpperCamelCase__ = """$$$""" UpperCamelCase__ = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=__lowerCAmelCase , add_bos_token=__lowerCAmelCase ) UpperCamelCase__ = """This is a simple input""" UpperCamelCase__ = ["""This is a simple input 1""", """This is a simple input 2"""] UpperCamelCase__ = tokenizer.bos_token_id UpperCamelCase__ = tokenizer(__lowerCAmelCase ) UpperCamelCase__ = tokenizer(__lowerCAmelCase ) self.assertEqual(out_s.input_ids[0] , __lowerCAmelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) UpperCamelCase__ = tokenizer.decode(out_s.input_ids ) UpperCamelCase__ = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __lowerCAmelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def _lowerCamelCase ( self ): UpperCamelCase__ = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) UpperCamelCase__ = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#""" UpperCamelCase__ = """\nif len_a > len_b: result = a\nelse: result = b""" UpperCamelCase__ = tokenizer.encode(__lowerCAmelCase ) UpperCamelCase__ = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""] UpperCamelCase__ = tokenizer.decode(__lowerCAmelCase , truncate_before_pattern=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def _lowerCamelCase ( self ): pass
619
1
from argparse import ArgumentParser from .env import EnvironmentCommand def lowerCamelCase_() -> Any: UpperCAmelCase = ArgumentParser("Diffusers CLI tool" , usage="diffusers-cli <command> [<args>]" ) UpperCAmelCase = parser.add_subparsers(help="diffusers-cli command helpers" ) # Register commands EnvironmentCommand.register_subcommand(lowerCamelCase_ ) # Let's go UpperCAmelCase = parser.parse_args() if not hasattr(lowerCamelCase_ , "func" ): parser.print_help() exit(1 ) # Run UpperCAmelCase = args.func(lowerCamelCase_ ) service.run() if __name__ == "__main__": main()
457
from __future__ import annotations def lowerCamelCase_(lowerCamelCase_ ) -> int: UpperCAmelCase = len(lowerCamelCase_ ) // 2 # choose the middle 3 elements UpperCAmelCase = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
457
1
"""simple docstring""" import re from filelock import FileLock try: import nltk _a = True except (ImportError, ModuleNotFoundError): _a = False if NLTK_AVAILABLE: with FileLock(""".lock""") as lock: nltk.download("""punkt""", quiet=True) def lowerCamelCase__ ( __snake_case ) -> str: """simple docstring""" re.sub('''<n>''', '''''', __snake_case ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(__snake_case ) )
19
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' _UpperCamelCase = ViTImageProcessor if is_vision_available() else None @property def __snake_case ( self : List[str]) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Optional[Any]) -> List[str]: A_ = (3, 32, 128) A_ = tempfile.mkdtemp() # fmt: off A_ = ['[GO]', '[s]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # fmt: on A_ = dict(zip(_lowercase , range(len(_lowercase)))) A_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) with open(self.vocab_file , 'w' , encoding='utf-8') as fp: fp.write(json.dumps(_lowercase) + '\n') A_ = { 'do_normalize': False, 'do_resize': True, 'image_processor_type': 'ViTImageProcessor', 'resample': 3, 'size': {'height': 32, 'width': 128}, } A_ = os.path.join(self.tmpdirname , _lowercase) with open(self.image_processor_file , 'w' , encoding='utf-8') as fp: json.dump(_lowercase , _lowercase) def __snake_case ( self : int , **_lowercase : Optional[int]) -> int: return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_lowercase) def __snake_case ( self : Optional[int] , **_lowercase : Optional[int]) -> Union[str, Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowercase) def __snake_case ( self : Dict) -> str: shutil.rmtree(self.tmpdirname) def __snake_case ( self : Union[str, Any]) -> Any: A_ = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta) A_ = Image.fromarray(np.moveaxis(_lowercase , 0 , -1)) return image_input def __snake_case ( self : Optional[Any]) -> List[Any]: A_ = self.get_tokenizer() A_ = self.get_image_processor() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) processor.save_pretrained(self.tmpdirname) A_ = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=_lowercase) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.char_tokenizer , _lowercase) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor.image_processor , _lowercase) def __snake_case ( self : Union[str, Any]) -> Optional[Any]: A_ = self.get_tokenizer() A_ = self.get_image_processor() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) processor.save_pretrained(self.tmpdirname) A_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') A_ = self.get_image_processor(do_normalize=_lowercase , padding_value=1.0) A_ = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_lowercase , padding_value=1.0) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.char_tokenizer , _lowercase) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , _lowercase) def __snake_case ( self : List[Any]) -> str: A_ = self.get_image_processor() A_ = self.get_tokenizer() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) A_ = self.prepare_image_inputs() A_ = image_processor(_lowercase , return_tensors='np') A_ = processor(images=_lowercase , return_tensors='np') for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2) def __snake_case ( self : Any) -> str: A_ = self.get_image_processor() A_ = self.get_tokenizer() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) A_ = 'test' A_ = processor(text=_lowercase) A_ = tokenizer(_lowercase) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def __snake_case ( self : str) -> Dict: A_ = self.get_image_processor() A_ = self.get_tokenizer() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) A_ = 'test' A_ = self.prepare_image_inputs() A_ = processor(text=_lowercase , images=_lowercase) self.assertListEqual(list(inputs.keys()) , ['pixel_values', 'labels']) # test if it raises when no input is passed with pytest.raises(_lowercase): processor() def __snake_case ( self : Union[str, Any]) -> Optional[int]: A_ = self.get_image_processor() A_ = self.get_tokenizer() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) A_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] A_ = processor.char_decode(_lowercase) A_ = tokenizer.batch_decode(_lowercase) A_ = [seq.replace(' ' , '') for seq in decoded_tok] self.assertListEqual(_lowercase , _lowercase) def __snake_case ( self : List[str]) -> str: A_ = self.get_image_processor() A_ = self.get_tokenizer() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) A_ = None A_ = self.prepare_image_inputs() A_ = processor(text=_lowercase , images=_lowercase) self.assertListEqual(list(inputs.keys()) , processor.model_input_names) def __snake_case ( self : List[str]) -> Any: A_ = self.get_image_processor() A_ = self.get_tokenizer() A_ = MgpstrProcessor(tokenizer=_lowercase , image_processor=_lowercase) A_ = torch.randn(1 , 27 , 38) A_ = torch.randn(1 , 27 , 50_257) A_ = torch.randn(1 , 27 , 30_522) A_ = processor.batch_decode([char_input, bpe_input, wp_input]) self.assertListEqual(list(results.keys()) , ['generated_text', 'scores', 'char_preds', 'bpe_preds', 'wp_preds'])
366
0
'''simple docstring''' import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class __a ( unittest.TestCase ): def __init__( self : Optional[int] ,lowerCamelCase : str ,lowerCamelCase : List[str]=13 ,lowerCamelCase : Optional[Any]=30 ,lowerCamelCase : Dict=2 ,lowerCamelCase : List[Any]=3 ,lowerCamelCase : List[str]=True ,lowerCamelCase : str=True ,lowerCamelCase : Optional[int]=32 ,lowerCamelCase : Dict=5 ,lowerCamelCase : Optional[int]=4 ,lowerCamelCase : List[Any]=37 ,lowerCamelCase : Union[str, Any]="gelu" ,lowerCamelCase : List[Any]=0.1 ,lowerCamelCase : Any=0.1 ,lowerCamelCase : str=10 ,lowerCamelCase : Dict=0.02 ,): '''simple docstring''' __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __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 = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 __SCREAMING_SNAKE_CASE = num_patches + 1 def UpperCAmelCase__ ( self : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = ViTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,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 ,is_decoder=lowerCamelCase ,initializer_range=self.initializer_range ,) return config, pixel_values def UpperCAmelCase__ ( self : Tuple ,lowerCamelCase : int ,lowerCamelCase : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = FlaxViTModel(config=lowerCamelCase ) __SCREAMING_SNAKE_CASE = model(lowerCamelCase ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) __SCREAMING_SNAKE_CASE = (self.patch_size, self.patch_size) __SCREAMING_SNAKE_CASE = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, num_patches + 1, self.hidden_size) ) def UpperCAmelCase__ ( self : Union[str, Any] ,lowerCamelCase : Optional[int] ,lowerCamelCase : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.type_sequence_label_size __SCREAMING_SNAKE_CASE = FlaxViTForImageClassification(config=lowerCamelCase ) __SCREAMING_SNAKE_CASE = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = FlaxViTForImageClassification(lowerCamelCase ) __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = model(lowerCamelCase ) def UpperCAmelCase__ ( self : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class __a ( _snake_case, unittest.TestCase ): __UpperCamelCase : Any = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def UpperCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = FlaxViTModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self ,config_class=lowerCamelCase ,has_text_modality=lowerCamelCase ,hidden_size=37 ) def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def UpperCAmelCase__ ( self : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) def UpperCAmelCase__ ( self : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(lowerCamelCase ) __SCREAMING_SNAKE_CASE = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["""pixel_values"""] self.assertListEqual(arg_names[:1] ,lowerCamelCase ) def UpperCAmelCase__ ( self : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = model_class(lowerCamelCase ) @jax.jit def model_jitted(lowerCamelCase : int ,**lowerCamelCase : Union[str, Any] ): return model(pixel_values=lowerCamelCase ,**lowerCamelCase ) with self.subTest("""JIT Enabled""" ): __SCREAMING_SNAKE_CASE = model_jitted(**lowerCamelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = model_jitted(**lowerCamelCase ).to_tuple() self.assertEqual(len(lowerCamelCase ) ,len(lowerCamelCase ) ) for jitted_output, output in zip(lowerCamelCase ,lowerCamelCase ): self.assertEqual(jitted_output.shape ,output.shape ) @slow def UpperCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("""google/vit-base-patch16-224""" ) __SCREAMING_SNAKE_CASE = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(lowerCamelCase )
13
'''simple docstring''' from __future__ import annotations from collections.abc import Callable a = list[list[float | int]] def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Matrix: '''simple docstring''' __SCREAMING_SNAKE_CASE = len(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = [[0 for _ in range(size + 1 )] for _ in range(__UpperCAmelCase )] __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 for row in range(__UpperCAmelCase ): for col in range(__UpperCAmelCase ): __SCREAMING_SNAKE_CASE = matrix[row][col] __SCREAMING_SNAKE_CASE = vector[row][0] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 while row < size and col < size: # pivoting __SCREAMING_SNAKE_CASE = max((abs(augmented[rowa][col] ), rowa) for rowa in range(__UpperCAmelCase , __UpperCAmelCase ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , __UpperCAmelCase ): __SCREAMING_SNAKE_CASE = augmented[rowa][col] / augmented[row][col] __SCREAMING_SNAKE_CASE = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , __UpperCAmelCase ): for row in range(__UpperCAmelCase ): __SCREAMING_SNAKE_CASE = augmented[row][col] / augmented[col][col] for cola in range(__UpperCAmelCase , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(__UpperCAmelCase ) ] def __magic_name__ ( __UpperCAmelCase ) -> Callable[[int], int]: '''simple docstring''' __SCREAMING_SNAKE_CASE = len(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = [[0 for _ in range(__UpperCAmelCase )] for _ in range(__UpperCAmelCase )] __SCREAMING_SNAKE_CASE = [[0] for _ in range(__UpperCAmelCase )] __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 for x_val, y_val in enumerate(__UpperCAmelCase ): for col in range(__UpperCAmelCase ): __SCREAMING_SNAKE_CASE = (x_val + 1) ** (size - col - 1) __SCREAMING_SNAKE_CASE = y_val __SCREAMING_SNAKE_CASE = solve(__UpperCAmelCase , __UpperCAmelCase ) def interpolated_func(__UpperCAmelCase ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(__UpperCAmelCase ) ) return interpolated_func def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def __magic_name__ ( __UpperCAmelCase = question_function , __UpperCAmelCase = 10 ) -> int: '''simple docstring''' __SCREAMING_SNAKE_CASE = [func(__UpperCAmelCase ) for x_val in range(1 , order + 1 )] __SCREAMING_SNAKE_CASE = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 for poly in polynomials: __SCREAMING_SNAKE_CASE = 1 while func(__UpperCAmelCase ) == poly(__UpperCAmelCase ): x_val += 1 ret += poly(__UpperCAmelCase ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
13
1
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : List[Any] = '''''' UpperCamelCase__ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) UpperCamelCase__ : str = None # compression type in fsspec. ex: "gzip" UpperCamelCase__ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self , _A = "" , _A = None , _A = None , **_A ): '''simple docstring''' super().__init__(self , **_A ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode __SCREAMING_SNAKE_CASE = fsspec.open( _A , mode='rb' , protocol=_A , compression=self.compression , client_kwargs={ 'requote_redirect_url': False, # see https://github.com/huggingface/datasets/pull/5459 'trust_env': True, # Enable reading proxy env variables. **(target_options or {}).pop('client_kwargs' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) __SCREAMING_SNAKE_CASE = os.path.basename(self.file.path.split('::' )[0] ) __SCREAMING_SNAKE_CASE = ( self.compressed_name[: self.compressed_name.rindex('.' )] if '.' in self.compressed_name else self.compressed_name ) __SCREAMING_SNAKE_CASE = None @classmethod def _A ( cls , _A ): '''simple docstring''' return super()._strip_protocol(_A ).lstrip('/' ) def _A ( self ): '''simple docstring''' if self.dir_cache is None: __SCREAMING_SNAKE_CASE = {**self.file.fs.info(self.file.path ), 'name': self.uncompressed_name} __SCREAMING_SNAKE_CASE = {f['name']: f} def _A ( self , _A ): '''simple docstring''' return self.file.open().read() def _A ( self , _A , _A = "rb" , _A=None , _A=True , _A=None , **_A , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self._strip_protocol(_A ) if mode != "rb": raise ValueError(f"""Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'""" ) return self.file.open() class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : List[Any] = '''bz2''' UpperCamelCase__ : Tuple = '''bz2''' UpperCamelCase__ : List[Any] = '''.bz2''' class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : int = '''gzip''' UpperCamelCase__ : Optional[Any] = '''gzip''' UpperCamelCase__ : Any = '''.gz''' class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : List[Any] = '''lz4''' UpperCamelCase__ : int = '''lz4''' UpperCamelCase__ : Union[str, Any] = '''.lz4''' class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Optional[Any] = '''xz''' UpperCamelCase__ : Any = '''xz''' UpperCamelCase__ : Any = '''.xz''' class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Dict = '''zstd''' UpperCamelCase__ : Any = '''zstd''' UpperCamelCase__ : Optional[int] = '''.zst''' def __init__( self , _A , _A = "rb" , _A = None , _A = None , _A = DEFAULT_BLOCK_SIZE , **_A , ): '''simple docstring''' super().__init__( fo=_A , mode=_A , target_protocol=_A , target_options=_A , block_size=_A , **_A , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 __SCREAMING_SNAKE_CASE = self.file.__enter__ class UpperCAmelCase_ : '''simple docstring''' def __init__( self , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = file_ def __enter__( self ): '''simple docstring''' self._file.__enter__() return self def __exit__( self , *_A , **_A ): '''simple docstring''' self._file.__exit__(*_A , **_A ) def __iter__( self ): '''simple docstring''' return iter(self._file ) def _A ( self ): '''simple docstring''' return next(self._file ) def __getattr__( self , _A ): '''simple docstring''' return getattr(self._file , _A ) def fixed_enter(*_A , **_A ): return WrappedFile(_enter(*_A , **_A ) ) __SCREAMING_SNAKE_CASE = fixed_enter
148
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ : List[str] =logging.get_logger(__name__) lowerCAmelCase__ : List[Any] ={ '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } lowerCAmelCase__ : Dict ={ '''vocab_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json''' }, '''merges_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt''' }, '''tokenizer_config_file''': { '''facebook/blenderbot_small-90M''': ( '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json''' ) }, } lowerCAmelCase__ : Dict ={'''facebook/blenderbot_small-90M''': 512} def __lowercase ( a__ ) -> str: __SCREAMING_SNAKE_CASE = set() __SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __SCREAMING_SNAKE_CASE = char __SCREAMING_SNAKE_CASE = set(a__ ) return pairs class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : int = VOCAB_FILES_NAMES UpperCamelCase__ : List[str] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ : Any = ['''input_ids''', '''attention_mask'''] def __init__( self , _A , _A , _A="__start__" , _A="__end__" , _A="__unk__" , _A="__null__" , **_A , ): '''simple docstring''' super().__init__(unk_token=_A , bos_token=_A , eos_token=_A , pad_token=_A , **_A ) with open(_A , encoding='utf-8' ) as vocab_handle: __SCREAMING_SNAKE_CASE = json.load(_A ) __SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} with open(_A , encoding='utf-8' ) as merges_handle: __SCREAMING_SNAKE_CASE = merges_handle.read().split('\n' )[1:-1] __SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in merges] __SCREAMING_SNAKE_CASE = dict(zip(_A , range(len(_A ) ) ) ) __SCREAMING_SNAKE_CASE = {} @property def _A ( self ): '''simple docstring''' return len(self.encoder ) def _A ( self ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def _A ( self , _A ): '''simple docstring''' if token in self.cache: return self.cache[token] __SCREAMING_SNAKE_CASE = re.sub('([.,!?()])' , r' \1' , _A ) __SCREAMING_SNAKE_CASE = re.sub('(\')' , r' \1 ' , _A ) __SCREAMING_SNAKE_CASE = re.sub(r'\s{2,}' , ' ' , _A ) if "\n" in token: __SCREAMING_SNAKE_CASE = token.replace('\n' , ' __newln__' ) __SCREAMING_SNAKE_CASE = token.split(' ' ) __SCREAMING_SNAKE_CASE = [] for token in tokens: if not len(_A ): continue __SCREAMING_SNAKE_CASE = token.lower() __SCREAMING_SNAKE_CASE = tuple(_A ) __SCREAMING_SNAKE_CASE = tuple(list(word[:-1] ) + [word[-1] + '</w>'] ) __SCREAMING_SNAKE_CASE = get_pairs(_A ) if not pairs: words.append(_A ) continue while True: __SCREAMING_SNAKE_CASE = min(_A , key=lambda _A : self.bpe_ranks.get(_A , float('inf' ) ) ) if bigram not in self.bpe_ranks: break __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = bigram __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 while i < len(_A ): try: __SCREAMING_SNAKE_CASE = word.index(_A , _A ) new_word.extend(word[i:j] ) __SCREAMING_SNAKE_CASE = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(_A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __SCREAMING_SNAKE_CASE = tuple(_A ) __SCREAMING_SNAKE_CASE = new_word if len(_A ) == 1: break else: __SCREAMING_SNAKE_CASE = get_pairs(_A ) __SCREAMING_SNAKE_CASE = '@@ '.join(_A ) __SCREAMING_SNAKE_CASE = word[:-4] __SCREAMING_SNAKE_CASE = word words.append(_A ) return " ".join(_A ) def _A ( self , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = re.findall(r'\S+\n?' , _A ) for token in words: split_tokens.extend(list(self.bpe(_A ).split(' ' ) ) ) return split_tokens def _A ( self , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = token.lower() return self.encoder.get(_A , self.encoder.get(self.unk_token ) ) def _A ( self , _A ): '''simple docstring''' return self.decoder.get(_A , self.unk_token ) def _A ( self , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = ' '.join(_A ).replace('@@ ' , '' ).strip() return out_string def _A ( self , _A , _A = None ): '''simple docstring''' if not os.path.isdir(_A ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __SCREAMING_SNAKE_CASE = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __SCREAMING_SNAKE_CASE = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(_A , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_A , ensure_ascii=_A ) + '\n' ) __SCREAMING_SNAKE_CASE = 0 with open(_A , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) __SCREAMING_SNAKE_CASE = token_index writer.write(' '.join(_A ) + '\n' ) index += 1 return vocab_file, merge_file
148
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = """roc_bert""" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any]=30_522 , SCREAMING_SNAKE_CASE__ : List[str]=768 , SCREAMING_SNAKE_CASE__ : str=12 , SCREAMING_SNAKE_CASE__ : Optional[int]=12 , SCREAMING_SNAKE_CASE__ : Any=3_072 , SCREAMING_SNAKE_CASE__ : str="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=512 , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Tuple=1e-1_2 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int="absolute" , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : int=768 , SCREAMING_SNAKE_CASE__ : List[Any]=910 , SCREAMING_SNAKE_CASE__ : Optional[Any]=512 , SCREAMING_SNAKE_CASE__ : Dict=24_858 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : int , ) -> Union[str, Any]: lowerCAmelCase__ = vocab_size lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = use_cache lowerCAmelCase__ = enable_pronunciation lowerCAmelCase__ = enable_shape lowerCAmelCase__ = pronunciation_embed_dim lowerCAmelCase__ = pronunciation_vocab_size lowerCAmelCase__ = shape_embed_dim lowerCAmelCase__ = shape_vocab_size lowerCAmelCase__ = concat_input lowerCAmelCase__ = position_embedding_type lowerCAmelCase__ = classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
716
import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _A ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = BigBirdConfig.from_json_file(lowerCAmelCase_ ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(lowerCAmelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(lowerCAmelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(lowerCAmelCase_ , lowerCAmelCase_ , is_trivia_qa=lowerCAmelCase_ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) UpperCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
125
0
def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple ): # Return True if there is node that has not iterated. __a : int = [False] * len(lowerCamelCase_ ) __a : Optional[int] = [] queue.append(lowerCamelCase_ ) __a : List[str] = True while queue: __a : Optional[Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(lowerCamelCase_ ) __a : Dict = True __a : int = u return visited[t] def UpperCAmelCase__ ( lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any ): # This array is filled by BFS and to store path __a : List[str] = [-1] * (len(lowerCamelCase_ )) __a : int = 0 while bfs(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): __a : List[Any] = float('Inf' ) __a : List[Any] = sink while s != source: # Find the minimum value in select path __a : List[str] = min(lowerCamelCase_ , graph[parent[s]][s] ) __a : List[str] = parent[s] max_flow += path_flow __a : int = sink while v != source: __a : Optional[Any] = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow __a : Optional[Any] = parent[v] return max_flow SCREAMING_SNAKE_CASE__ = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 5 print(ford_fulkerson(graph, source, sink))
47
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A = input('Enter image url: ').strip() print(F'''Downloading image from {url} ...''') A = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image A = soup.find('meta', {'property': 'og:image'})['content'] A = requests.get(image_url).content A = F'''{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg''' with open(file_name, 'wb') as fp: fp.write(image_data) print(F'''Done. Image saved to disk as {file_name}.''')
544
0
from math import isclose, sqrt def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> tuple[float, float, float]: lowerCamelCase__ : str = point_y / 4 / point_x lowerCamelCase__ : Dict = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase__ : Optional[int] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase__ : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase__ : Union[str, Any] = outgoing_gradient**2 + 4 lowerCamelCase__ : Any = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase__ : int = (point_y - outgoing_gradient * point_x) ** 2 - 100 lowerCamelCase__ : List[Any] = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowerCamelCase__ : int = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase__ : List[str] = x_minus if isclose(UpperCamelCase , UpperCamelCase ) else x_plus lowerCamelCase__ : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 1.4 , UpperCamelCase = -9.6 ) -> int: lowerCamelCase__ : int = 0 lowerCamelCase__ : float = first_x_coord lowerCamelCase__ : float = first_y_coord lowerCamelCase__ : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowerCamelCase__ : int = next_point(UpperCamelCase , UpperCamelCase , UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F'{solution() = }')
715
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : str =logging.get_logger(__name__) _A : int ={ '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """roc_bert""" def __init__( self: Optional[Any] , UpperCamelCase__: Any=30_522 , UpperCamelCase__: Optional[Any]=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: Tuple=12 , UpperCamelCase__: Tuple=3_072 , UpperCamelCase__: str="gelu" , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: List[str]=0.1 , UpperCamelCase__: Dict=512 , UpperCamelCase__: str=2 , UpperCamelCase__: str=0.02 , UpperCamelCase__: Tuple=1e-12 , UpperCamelCase__: Any=True , UpperCamelCase__: Union[str, Any]=0 , UpperCamelCase__: List[Any]="absolute" , UpperCamelCase__: Any=None , UpperCamelCase__: Any=True , UpperCamelCase__: Optional[int]=True , UpperCamelCase__: Union[str, Any]=768 , UpperCamelCase__: int=910 , UpperCamelCase__: Tuple=512 , UpperCamelCase__: int=24_858 , UpperCamelCase__: Optional[Any]=True , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Optional[Any] = vocab_size lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : Tuple = num_attention_heads lowerCamelCase__ : Any = intermediate_size lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = initializer_range lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Optional[Any] = layer_norm_eps lowerCamelCase__ : List[Any] = use_cache lowerCamelCase__ : Tuple = enable_pronunciation lowerCamelCase__ : Union[str, Any] = enable_shape lowerCamelCase__ : Union[str, Any] = pronunciation_embed_dim lowerCamelCase__ : Any = pronunciation_vocab_size lowerCamelCase__ : int = shape_embed_dim lowerCamelCase__ : Tuple = shape_vocab_size lowerCamelCase__ : Optional[Any] = concat_input lowerCamelCase__ : str = position_embedding_type lowerCamelCase__ : Dict = classifier_dropout super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { """configuration_git""": ["""GIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GitConfig""", """GitVisionConfig"""], """processing_git""": ["""GitProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ """GIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GitForCausalLM""", """GitModel""", """GitPreTrainedModel""", """GitVisionModel""", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys A_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
29
from ...configuration_utils import PretrainedConfig from ...utils import logging __a : Optional[Any] = logging.get_logger(__name__) __a : Dict = { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json", # See all REALM models at https://huggingface.co/models?filter=realm } class __lowercase ( lowercase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE = "realm" def __init__( self : str , UpperCamelCase_ : List[Any]=30_522 , UpperCamelCase_ : Dict=768 , UpperCamelCase_ : Union[str, Any]=128 , UpperCamelCase_ : Tuple=12 , UpperCamelCase_ : Optional[Any]=12 , UpperCamelCase_ : Optional[int]=8 , UpperCamelCase_ : str=3_072 , UpperCamelCase_ : List[str]="gelu_new" , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : str=512 , UpperCamelCase_ : int=2 , UpperCamelCase_ : str=0.02 , UpperCamelCase_ : List[Any]=1e-12 , UpperCamelCase_ : str=256 , UpperCamelCase_ : List[str]=10 , UpperCamelCase_ : int=1e-3 , UpperCamelCase_ : List[str]=5 , UpperCamelCase_ : Tuple=320 , UpperCamelCase_ : List[str]=13_353_718 , UpperCamelCase_ : Tuple=5_000 , UpperCamelCase_ : Optional[int]=1 , UpperCamelCase_ : List[str]=0 , UpperCamelCase_ : Union[str, Any]=2 , **UpperCamelCase_ : List[Any] , ): """simple docstring""" super().__init__(pad_token_id=UpperCamelCase_ , bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ ) # Common config __A = vocab_size __A = max_position_embeddings __A = hidden_size __A = retriever_proj_size __A = num_hidden_layers __A = num_attention_heads __A = num_candidates __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = initializer_range __A = type_vocab_size __A = layer_norm_eps # Reader config __A = span_hidden_size __A = max_span_width __A = reader_layer_norm_eps __A = reader_beam_size __A = reader_seq_len # Retrieval config __A = num_block_records __A = searcher_beam_size
637
0
def lowercase__( A , A ): snake_case__ : Optional[Any] = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def lowercase__( A , A , A ): snake_case__ : Optional[Any] = 0 while b > 0: if b & 1: snake_case__ : List[Any] = ((res % c) + (a % c)) % c a += a b >>= 1 return res
303
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case__ : def __init__( self : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : Optional[Any]=2 , _lowerCamelCase : Dict=True , _lowerCamelCase : Optional[Any]=False , _lowerCamelCase : int=1_0 , _lowerCamelCase : Dict=3 , _lowerCamelCase : List[str]=3_2 * 8 , _lowerCamelCase : Tuple=3_2 * 8 , _lowerCamelCase : Optional[int]=4 , _lowerCamelCase : Optional[Any]=6_4 , ): snake_case__ : Dict = parent snake_case__ : Optional[Any] = batch_size snake_case__ : str = is_training snake_case__ : List[str] = use_auxiliary_loss snake_case__ : Union[str, Any] = num_queries snake_case__ : List[Any] = num_channels snake_case__ : Dict = min_size snake_case__ : str = max_size snake_case__ : Any = num_labels snake_case__ : int = hidden_dim snake_case__ : List[Any] = hidden_dim def UpperCAmelCase__ ( self : str ): snake_case__ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) snake_case__ : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) snake_case__ : Optional[Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() snake_case__ : str = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() snake_case__ : int = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCAmelCase__ ( self : Optional[int] ): snake_case__ : Optional[Any] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) snake_case__ : Optional[Any] = self.num_queries snake_case__ : int = self.num_labels snake_case__ : Any = [1, 1, 1, 1] snake_case__ : str = self.num_channels snake_case__ : List[str] = 6_4 snake_case__ : Optional[int] = 1_2_8 snake_case__ : Optional[int] = self.hidden_dim snake_case__ : Optional[int] = self.hidden_dim snake_case__ : Union[str, Any] = self.hidden_dim return config def UpperCAmelCase__ ( self : str ): snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = self.prepare_config_and_inputs() snake_case__ : Tuple = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def UpperCAmelCase__ ( self : Optional[int] , _lowerCamelCase : Tuple , _lowerCamelCase : Dict ): snake_case__ : Optional[Any] = output.encoder_hidden_states snake_case__ : Optional[int] = output.pixel_decoder_hidden_states snake_case__ : Union[str, Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_layers ) def UpperCAmelCase__ ( self : List[str] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : int , _lowerCamelCase : List[str]=False ): with torch.no_grad(): snake_case__ : Union[str, Any] = MaskaFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() snake_case__ : List[Any] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) snake_case__ : Optional[Any] = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def UpperCAmelCase__ ( self : List[str] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : str , _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : Optional[Any] ): snake_case__ : int = MaskaFormerForUniversalSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase : int ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): snake_case__ : Optional[Any] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) snake_case__ : Any = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) snake_case__ : List[Any] = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): _lowerCAmelCase =(MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () _lowerCAmelCase ={'feature-extraction': MaskaFormerModel} if is_torch_available() else {} _lowerCAmelCase =False _lowerCAmelCase =False _lowerCAmelCase =False _lowerCAmelCase =False def UpperCAmelCase__ ( self : Tuple ): snake_case__ : Optional[Any] = MaskaFormerModelTester(self ) snake_case__ : Optional[int] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def UpperCAmelCase__ ( self : Tuple ): self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Dict ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def UpperCAmelCase__ ( self : str ): snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def UpperCAmelCase__ ( self : Union[str, Any] ): pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def UpperCAmelCase__ ( self : Optional[int] ): pass @unittest.skip(reason='Mask2Former is not a generative model' ) def UpperCAmelCase__ ( self : List[Any] ): pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def UpperCAmelCase__ ( self : Optional[Any] ): pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def UpperCAmelCase__ ( self : Optional[Any] ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCAmelCase__ ( self : Optional[int] ): pass def UpperCAmelCase__ ( self : int ): snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : List[str] = model_class(_lowerCamelCase ) snake_case__ : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Dict = [*signature.parameters.keys()] snake_case__ : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def UpperCAmelCase__ ( self : Tuple ): for model_name in ["facebook/mask2former-swin-small-coco-instance"]: snake_case__ : Tuple = MaskaFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def UpperCAmelCase__ ( self : List[Any] ): snake_case__ : int = (self.model_tester.min_size,) * 2 snake_case__ : Tuple = { 'pixel_values': torch.randn((2, 3, *size) , device=_lowerCamelCase ), 'mask_labels': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), 'class_labels': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } snake_case__ : str = self.model_tester.get_config() snake_case__ : Optional[int] = MaskaFormerForUniversalSegmentation(_lowerCamelCase ).to(_lowerCamelCase ) snake_case__ : Tuple = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def UpperCAmelCase__ ( self : str ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def UpperCAmelCase__ ( self : Tuple ): snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) snake_case__ : List[str] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def UpperCAmelCase__ ( self : Any ): if not self.model_tester.is_training: return snake_case__ : Tuple = self.all_model_classes[1] snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs() snake_case__ : List[Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() snake_case__ : int = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def UpperCAmelCase__ ( self : Any ): snake_case__ : int = self.all_model_classes[1] snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs() snake_case__ : Union[str, Any] = True snake_case__ : Optional[Any] = True snake_case__ : Tuple = model_class(_lowerCamelCase ).to(_lowerCamelCase ) model.train() snake_case__ : Union[str, Any] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) snake_case__ : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() snake_case__ : Any = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() snake_case__ : Dict = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() snake_case__ : List[Any] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) lowerCamelCase : int = 1e-4 def lowercase__( ): snake_case__ : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class snake_case__ ( unittest.TestCase ): @cached_property def UpperCAmelCase__ ( self : Union[str, Any] ): return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCAmelCase__ ( self : str ): return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def UpperCAmelCase__ ( self : int ): snake_case__ : Dict = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(_lowerCamelCase ) snake_case__ : List[str] = self.default_image_processor snake_case__ : Union[str, Any] = prepare_img() snake_case__ : Any = image_processor(_lowerCamelCase , return_tensors='pt' ).to(_lowerCamelCase ) snake_case__ : Dict = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 3_8_4, 3_8_4) ) with torch.no_grad(): snake_case__ : List[Any] = model(**_lowerCamelCase ) snake_case__ : Optional[Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) snake_case__ : List[Any] = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) snake_case__ : str = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def UpperCAmelCase__ ( self : List[Any] ): snake_case__ : Dict = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_lowerCamelCase ).eval() snake_case__ : Union[str, Any] = self.default_image_processor snake_case__ : Union[str, Any] = prepare_img() snake_case__ : Tuple = image_processor(_lowerCamelCase , return_tensors='pt' ).to(_lowerCamelCase ) snake_case__ : str = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 3_8_4, 3_8_4) ) with torch.no_grad(): snake_case__ : Dict = model(**_lowerCamelCase ) # masks_queries_logits snake_case__ : Optional[Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) snake_case__ : Optional[Any] = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] snake_case__ : Optional[Any] = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits snake_case__ : int = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) snake_case__ : List[str] = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def UpperCAmelCase__ ( self : int ): snake_case__ : Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_lowerCamelCase ).eval() snake_case__ : Any = self.default_image_processor snake_case__ : Optional[int] = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='pt' , ) snake_case__ : Dict = inputs['pixel_values'].to(_lowerCamelCase ) snake_case__ : Optional[Any] = [el.to(_lowerCamelCase ) for el in inputs['mask_labels']] snake_case__ : Union[str, Any] = [el.to(_lowerCamelCase ) for el in inputs['class_labels']] with torch.no_grad(): snake_case__ : Tuple = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
303
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class _SCREAMING_SNAKE_CASE ( __a ): __SCREAMING_SNAKE_CASE :Optional[Any] = """ibert""" def __init__( self : Optional[Any] , a__ : List[str]=3_0522 , a__ : Tuple=768 , a__ : str=12 , a__ : Any=12 , a__ : List[Any]=3072 , a__ : Optional[int]="gelu" , a__ : Optional[int]=0.1 , a__ : List[str]=0.1 , a__ : Optional[int]=512 , a__ : List[Any]=2 , a__ : Optional[Any]=0.02 , a__ : int=1E-12 , a__ : List[Any]=1 , a__ : Optional[int]=0 , a__ : List[str]=2 , a__ : Tuple="absolute" , a__ : Union[str, Any]=False , a__ : str="none" , **a__ : List[Any] , ): super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = position_embedding_type __magic_name__ = quant_mode __magic_name__ = force_dequant class _SCREAMING_SNAKE_CASE ( __a ): @property def snake_case__ ( self : Any ): if self.task == "multiple-choice": __magic_name__ = {0: "batch", 1: "choice", 2: "sequence"} else: __magic_name__ = {0: "batch", 1: "sequence"} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
432
'''simple docstring''' import numpy as np def __A ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase = 1E-12 ,UpperCAmelCase = 1_0_0 ,) -> tuple[float, np.ndarray]: '''simple docstring''' assert np.shape(UpperCAmelCase )[0] == np.shape(UpperCAmelCase )[1] # Ensure proper dimensionality. assert np.shape(UpperCAmelCase )[0] == np.shape(UpperCAmelCase )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(UpperCAmelCase ) == np.iscomplexobj(UpperCAmelCase ) _UpperCamelCase : int = np.iscomplexobj(UpperCAmelCase ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(UpperCAmelCase ,input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. _UpperCamelCase : str = False _UpperCamelCase : Any = 0 _UpperCamelCase : List[Any] = 0 _UpperCamelCase : int = 1E12 while not convergence: # Multiple matrix by the vector. _UpperCamelCase : str = np.dot(UpperCAmelCase ,UpperCAmelCase ) # Normalize the resulting output vector. _UpperCamelCase : int = w / np.linalg.norm(UpperCAmelCase ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) _UpperCamelCase : Any = vector.conj().T if is_complex else vector.T _UpperCamelCase : Dict = np.dot(UpperCAmelCase ,np.dot(UpperCAmelCase ,UpperCAmelCase ) ) # Check convergence. _UpperCamelCase : Optional[Any] = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: _UpperCamelCase : Union[str, Any] = True _UpperCamelCase : int = lambda_ if is_complex: _UpperCamelCase : List[Any] = np.real(lambda_ ) return lambda_, vector def __A ( ) -> None: '''simple docstring''' _UpperCamelCase : Any = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) _UpperCamelCase : str = np.array([4_1, 4, 2_0] ) _UpperCamelCase : Union[str, Any] = real_input_matrix.astype(np.complexaaa ) _UpperCamelCase : List[str] = np.triu(1j * complex_input_matrix ,1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T _UpperCamelCase : Optional[int] = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": _UpperCamelCase : Tuple = real_input_matrix _UpperCamelCase : List[Any] = real_vector elif problem_type == "complex": _UpperCamelCase : Optional[int] = complex_input_matrix _UpperCamelCase : Any = complex_vector # Our implementation. _UpperCamelCase , _UpperCamelCase : Any = power_iteration(UpperCAmelCase ,UpperCAmelCase ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). _UpperCamelCase , _UpperCamelCase : Any = np.linalg.eigh(UpperCAmelCase ) # Last eigenvalue is the maximum one. _UpperCamelCase : Union[str, Any] = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. _UpperCamelCase : Optional[int] = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(UpperCAmelCase ) - np.abs(UpperCAmelCase ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
435
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor SCREAMING_SNAKE_CASE = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" if isinstance(__UpperCAmelCase ,torch.Tensor ): return image elif isinstance(__UpperCAmelCase ,PIL.Image.Image ): _lowercase : Any = [image] _lowercase : Dict = [trans(img.convert('RGB' ) ) for img in image] _lowercase : Any = torch.stack(__UpperCAmelCase ) return image class _lowerCamelCase (__lowerCamelCase ): def __init__( self : Tuple , lowerCamelCase_ : int , lowerCamelCase_ : int ): """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM _lowercase : Union[str, Any] = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=lowerCamelCase_ , scheduler=lowerCamelCase_ ) def __UpperCAmelCase ( self : Any , lowerCamelCase_ : Optional[int] ): """simple docstring""" if strength < 0 or strength > 1: raise ValueError(F'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def __UpperCAmelCase ( self : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Tuple ): """simple docstring""" _lowercase : List[Any] = min(int(num_inference_steps * strength ) , lowerCamelCase_ ) _lowercase : Optional[int] = max(num_inference_steps - init_timestep , 0 ) _lowercase : Dict = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __UpperCAmelCase ( self : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int=None ): """simple docstring""" if not isinstance(lowerCamelCase_ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowerCamelCase_ )}''' ) _lowercase : Optional[Any] = image.to(device=lowerCamelCase_ , dtype=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(lowerCamelCase_ ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(lowerCamelCase_ )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) _lowercase : List[Any] = init_latents.shape _lowercase : int = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ , device=lowerCamelCase_ , dtype=lowerCamelCase_ ) # get latents print('add noise to latents at timestep' , lowerCamelCase_ ) _lowercase : List[str] = self.scheduler.add_noise(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) _lowercase : str = init_latents return latents @torch.no_grad() def __call__( self : str , lowerCamelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , lowerCamelCase_ : float = 0.8 , lowerCamelCase_ : int = 1 , lowerCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : int = 5_0 , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[str] = "pil" , lowerCamelCase_ : bool = True , ): """simple docstring""" self.check_inputs(lowerCamelCase_ ) # 2. Preprocess image _lowercase : Union[str, Any] = preprocess(lowerCamelCase_ ) # 3. set timesteps self.scheduler.set_timesteps(lowerCamelCase_ , device=self.device ) _lowercase : str = self.get_timesteps(lowerCamelCase_ , lowerCamelCase_ , self.device ) _lowercase : List[Any] = timesteps[:1].repeat(lowerCamelCase_ ) # 4. Prepare latent variables _lowercase : Dict = self.prepare_latents(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , self.unet.dtype , self.device , lowerCamelCase_ ) _lowercase : str = latents # 5. Denoising loop for t in self.progress_bar(lowerCamelCase_ ): # 1. predict noise model_output _lowercase : str = self.unet(lowerCamelCase_ , lowerCamelCase_ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 _lowercase : Optional[int] = self.scheduler.step( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , eta=lowerCamelCase_ , use_clipped_model_output=lowerCamelCase_ , generator=lowerCamelCase_ , ).prev_sample _lowercase : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) _lowercase : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _lowercase : Optional[int] = self.numpy_to_pil(lowerCamelCase_ ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=lowerCamelCase_ )
702
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
283
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class lowercase__( unittest.TestCase ): """simple docstring""" def _lowercase ( self : Union[str, Any] ) -> List[Any]: lowercase_ = tempfile.mkdtemp() lowercase_ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] lowercase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) lowercase_ = { '''do_resize''': True, '''size''': 2_0, '''do_center_crop''': True, '''crop_size''': 1_8, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } lowercase_ = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE_ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Optional[Any] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Any: return BertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Optional[Any] , **SCREAMING_SNAKE_CASE_ : Tuple ) -> Tuple: return BertTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : List[str] , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Dict ) -> Optional[Any]: shutil.rmtree(self.tmpdirname ) def _lowercase ( self : Dict ) -> Any: lowercase_ = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] lowercase_ = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self : Optional[Any] ) -> Union[str, Any]: lowercase_ = self.get_tokenizer() lowercase_ = self.get_rust_tokenizer() lowercase_ = self.get_image_processor() lowercase_ = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor_slow.save_pretrained(self.tmpdirname ) lowercase_ = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ ) lowercase_ = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor_fast.save_pretrained(self.tmpdirname ) lowercase_ = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : List[Any] ) -> int: lowercase_ = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowercase_ = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) lowercase_ = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) lowercase_ = AlignProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : List[Any] ) -> Union[str, Any]: lowercase_ = self.get_image_processor() lowercase_ = self.get_tokenizer() lowercase_ = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) lowercase_ = self.prepare_image_inputs() lowercase_ = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) lowercase_ = processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _lowercase ( self : Optional[Any] ) -> int: lowercase_ = self.get_image_processor() lowercase_ = self.get_tokenizer() lowercase_ = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) lowercase_ = '''lower newer''' lowercase_ = processor(text=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=6_4 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self : Dict ) -> str: lowercase_ = self.get_image_processor() lowercase_ = self.get_tokenizer() lowercase_ = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) lowercase_ = '''lower newer''' lowercase_ = self.prepare_image_inputs() lowercase_ = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def _lowercase ( self : int ) -> List[str]: lowercase_ = self.get_image_processor() lowercase_ = self.get_tokenizer() lowercase_ = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) lowercase_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowercase_ = processor.batch_decode(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : str ) -> Any: lowercase_ = self.get_image_processor() lowercase_ = self.get_tokenizer() lowercase_ = AlignProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) lowercase_ = '''lower newer''' lowercase_ = self.prepare_image_inputs() lowercase_ = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
97
import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' a : int = CodeGenTokenizer a : List[str] = CodeGenTokenizerFast a : List[Any] = True a : Optional[Any] = {"add_prefix_space": True} a : Dict = False def UpperCamelCase__ ( self ) -> int: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ : str = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', '''<|endoftext|>''', ] UpperCamelCase__ : Dict = dict(zip(__magic_name__, range(len(__magic_name__ ) ) ) ) UpperCamelCase__ : Dict = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] UpperCamelCase__ : Dict = {'''unk_token''': '''<unk>'''} UpperCamelCase__ : str = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCamelCase__ : Optional[int] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file, '''w''', encoding='''utf-8''' ) as fp: fp.write(json.dumps(__magic_name__ ) + '''\n''' ) with open(self.merges_file, '''w''', encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def UpperCamelCase__ ( self, **__magic_name__ ) -> Union[str, Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **__magic_name__ ) def UpperCamelCase__ ( self, **__magic_name__ ) -> Dict: """simple docstring""" kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **__magic_name__ ) def UpperCamelCase__ ( self, __magic_name__ ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ : List[Any] = '''lower newer''' UpperCamelCase__ : int = '''lower newer''' return input_text, output_text def UpperCamelCase__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase__ : Any = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map ) UpperCamelCase__ : List[Any] = '''lower newer''' UpperCamelCase__ : Dict = ['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] UpperCamelCase__ : int = tokenizer.tokenize(__magic_name__, add_prefix_space=__magic_name__ ) self.assertListEqual(__magic_name__, __magic_name__ ) UpperCamelCase__ : Dict = tokens + [tokenizer.unk_token] UpperCamelCase__ : int = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ), __magic_name__ ) def UpperCamelCase__ ( self ) -> Any: """simple docstring""" if not self.test_rust_tokenizer: return UpperCamelCase__ : int = self.get_tokenizer() UpperCamelCase__ : List[str] = self.get_rust_tokenizer(add_prefix_space=__magic_name__ ) UpperCamelCase__ : List[Any] = '''lower newer''' # Testing tokenization UpperCamelCase__ : Tuple = tokenizer.tokenize(__magic_name__, add_prefix_space=__magic_name__ ) UpperCamelCase__ : Tuple = rust_tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__, __magic_name__ ) # Testing conversion to ids without special tokens UpperCamelCase__ : int = tokenizer.encode(__magic_name__, add_special_tokens=__magic_name__, add_prefix_space=__magic_name__ ) UpperCamelCase__ : str = rust_tokenizer.encode(__magic_name__, add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__, __magic_name__ ) # Testing conversion to ids with special tokens UpperCamelCase__ : Union[str, Any] = self.get_rust_tokenizer(add_prefix_space=__magic_name__ ) UpperCamelCase__ : Dict = tokenizer.encode(__magic_name__, add_prefix_space=__magic_name__ ) UpperCamelCase__ : List[str] = rust_tokenizer.encode(__magic_name__ ) self.assertListEqual(__magic_name__, __magic_name__ ) # Testing the unknown token UpperCamelCase__ : Optional[int] = tokens + [rust_tokenizer.unk_token] UpperCamelCase__ : Union[str, Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__magic_name__ ), __magic_name__ ) def UpperCamelCase__ ( self, *__magic_name__, **__magic_name__ ) -> List[str]: """simple docstring""" # It's very difficult to mix/test pretokenization with byte-level # And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def UpperCamelCase__ ( self, __magic_name__=15 ) -> str: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ : List[Any] = self.rust_tokenizer_class.from_pretrained(__magic_name__, **__magic_name__ ) # Simple input UpperCamelCase__ : int = '''This is a simple input''' UpperCamelCase__ : Any = ['''This is a simple input 1''', '''This is a simple input 2'''] UpperCamelCase__ : Optional[int] = ('''This is a simple input''', '''This is a pair''') UpperCamelCase__ : List[Any] = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(__magic_name__, tokenizer_r.encode, __magic_name__, max_length=__magic_name__, padding='''max_length''' ) # Simple input self.assertRaises(__magic_name__, tokenizer_r.encode_plus, __magic_name__, max_length=__magic_name__, padding='''max_length''' ) # Simple input self.assertRaises( __magic_name__, tokenizer_r.batch_encode_plus, __magic_name__, max_length=__magic_name__, padding='''max_length''', ) # Pair input self.assertRaises(__magic_name__, tokenizer_r.encode, __magic_name__, max_length=__magic_name__, padding='''max_length''' ) # Pair input self.assertRaises(__magic_name__, tokenizer_r.encode_plus, __magic_name__, max_length=__magic_name__, padding='''max_length''' ) # Pair input self.assertRaises( __magic_name__, tokenizer_r.batch_encode_plus, __magic_name__, max_length=__magic_name__, padding='''max_length''', ) def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase__ : Optional[int] = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token='''<pad>''' ) # Simple input UpperCamelCase__ : Union[str, Any] = '''This is a simple input''' UpperCamelCase__ : List[Any] = ['''This is a simple input looooooooong''', '''This is a simple input'''] UpperCamelCase__ : Any = ('''This is a simple input''', '''This is a pair''') UpperCamelCase__ : str = [ ('''This is a simple input loooooong''', '''This is a simple input'''), ('''This is a simple pair loooooong''', '''This is a simple pair'''), ] UpperCamelCase__ : str = tokenizer.pad_token_id UpperCamelCase__ : int = tokenizer(__magic_name__, padding='''max_length''', max_length=30, return_tensors='''np''' ) UpperCamelCase__ : Union[str, Any] = tokenizer(__magic_name__, padding=__magic_name__, truncate=__magic_name__, return_tensors='''np''' ) UpperCamelCase__ : str = tokenizer(*__magic_name__, padding='''max_length''', max_length=60, return_tensors='''np''' ) UpperCamelCase__ : str = tokenizer(__magic_name__, padding=__magic_name__, truncate=__magic_name__, return_tensors='''np''' ) # s # test single string max_length padding self.assertEqual(out_s['''input_ids'''].shape[-1], 30 ) self.assertTrue(pad_token_id in out_s['''input_ids'''] ) self.assertTrue(0 in out_s['''attention_mask'''] ) # s2 # test automatic padding self.assertEqual(out_sa['''input_ids'''].shape[-1], 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['''input_ids'''][0] ) self.assertFalse(0 in out_sa['''attention_mask'''][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['''input_ids'''][1] ) self.assertTrue(0 in out_sa['''attention_mask'''][1] ) # p # test single pair max_length padding self.assertEqual(out_p['''input_ids'''].shape[-1], 60 ) self.assertTrue(pad_token_id in out_p['''input_ids'''] ) self.assertTrue(0 in out_p['''attention_mask'''] ) # p2 # test automatic padding pair self.assertEqual(out_pa['''input_ids'''].shape[-1], 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['''input_ids'''][0] ) self.assertFalse(0 in out_pa['''attention_mask'''][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['''input_ids'''][1] ) self.assertTrue(0 in out_pa['''attention_mask'''][1] ) def UpperCamelCase__ ( self ) -> int: """simple docstring""" UpperCamelCase__ : Union[str, Any] = '''$$$''' UpperCamelCase__ : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=__magic_name__, add_bos_token=__magic_name__ ) UpperCamelCase__ : Tuple = '''This is a simple input''' UpperCamelCase__ : int = ['''This is a simple input 1''', '''This is a simple input 2'''] UpperCamelCase__ : List[Any] = tokenizer.bos_token_id UpperCamelCase__ : Dict = tokenizer(__magic_name__ ) UpperCamelCase__ : Optional[Any] = tokenizer(__magic_name__ ) self.assertEqual(out_s.input_ids[0], __magic_name__ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) UpperCamelCase__ : Optional[int] = tokenizer.decode(out_s.input_ids ) UpperCamelCase__ : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0], __magic_name__ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def UpperCamelCase__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase__ : List[Any] = CodeGenTokenizer.from_pretrained('''Salesforce/codegen-350M-mono''' ) UpperCamelCase__ : Any = '''\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#''' UpperCamelCase__ : List[str] = '''\nif len_a > len_b: result = a\nelse: result = b''' UpperCamelCase__ : int = tokenizer.encode(__magic_name__ ) UpperCamelCase__ : Optional[int] = ['''^#''', re.escape('''<|endoftext|>''' ), '''^\'\'\'''', '''^"""''', '''\n\n\n'''] UpperCamelCase__ : Tuple = tokenizer.decode(__magic_name__, truncate_before_pattern=__magic_name__ ) self.assertEqual(__magic_name__, __magic_name__ ) def UpperCamelCase__ ( self ) -> str: """simple docstring""" pass
253
0
"""simple docstring""" def lowercase ( _SCREAMING_SNAKE_CASE : str ): '''simple docstring''' return "".join(chr(ord(_SCREAMING_SNAKE_CASE ) - 32 ) if '''a''' <= char <= '''z''' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
95
"""simple docstring""" class _a : """simple docstring""" def __init__( self : Tuple , __UpperCamelCase : list[int] )->None: _UpperCAmelCase = len(__UpperCamelCase ) _UpperCAmelCase = [0] * len_array if len_array > 0: _UpperCAmelCase = array[0] for i in range(1 , __UpperCamelCase ): _UpperCAmelCase = self.prefix_sum[i - 1] + array[i] def lowercase__ ( self : str , __UpperCamelCase : int , __UpperCamelCase : int )->int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def lowercase__ ( self : Any , __UpperCamelCase : int )->bool: _UpperCAmelCase = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__UpperCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
95
1
import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList __UpperCAmelCase = ['''\nclass''', '''\ndef''', '''\n#''', '''\n@''', '''\nprint''', '''\nif'''] class lowerCAmelCase_ ( a__ ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=1 ) -> List[str]: UpperCamelCase : int = tokenizer UpperCamelCase : List[str] = dataset UpperCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) if n_tasks is None else n_tasks UpperCamelCase : str = n_copies def __iter__( self ) -> Tuple: UpperCamelCase : List[str] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() ) UpperCamelCase : Any = self.tokenizer(SCREAMING_SNAKE_CASE_, padding=SCREAMING_SNAKE_CASE_, return_tensors='pt' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class lowerCAmelCase_ ( a__ ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase : Any = start_length UpperCamelCase : Optional[int] = eof_strings UpperCamelCase : List[Any] = tokenizer def __call__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase : str = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) UpperCamelCase : List[Any] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase ( snake_case__ : Any ) -> List[str]: UpperCamelCase : Tuple = re.split('(%s)' % '|'.join(snake_case__ ) , snake_case__ ) # last string should be "" return "".join(string_list[:-2] ) def UpperCamelCase ( snake_case__ : List[str] , snake_case__ : List[str] , snake_case__ : Optional[int] , snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : Optional[Any]=20 , **snake_case__ : List[str] ) -> Tuple: UpperCamelCase : Union[str, Any] = defaultdict(snake_case__ ) # dict of list of generated tokens for step, batch in tqdm(enumerate(snake_case__ ) ): with torch.no_grad(): UpperCamelCase : Optional[int] = batch['ids'].shape[-1] UpperCamelCase : Union[str, Any] = accelerator.unwrap_model(snake_case__ ).generate( input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=snake_case__ , **snake_case__ ) # each task is generated batch_size times UpperCamelCase : Optional[Any] = batch['task_id'].repeat(snake_case__ ) UpperCamelCase : Any = accelerator.pad_across_processes( snake_case__ , dim=1 , pad_index=tokenizer.pad_token_id ) UpperCamelCase , UpperCamelCase : Any = accelerator.gather((generated_tokens, generated_tasks) ) UpperCamelCase : Optional[int] = generated_tokens.cpu().numpy() UpperCamelCase : str = generated_tasks.cpu().numpy() for task, generated_tokens in zip(snake_case__ , snake_case__ ): gen_token_dict[task].append(snake_case__ ) UpperCamelCase : Tuple = [[] for _ in range(snake_case__ )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: UpperCamelCase : Optional[Any] = tokenizer.decode(snake_case__ , skip_special_tokens=snake_case__ , clean_up_tokenization_spaces=snake_case__ ) code_gens[task].append(remove_last_block(snake_case__ ) ) return code_gens def UpperCamelCase ( ) -> Any: # Setup configuration UpperCamelCase : Optional[Any] = HfArgumentParser(snake_case__ ) UpperCamelCase : Optional[Any] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric UpperCamelCase : Dict = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing UpperCamelCase : Optional[int] = 'false' if args.num_workers is None: UpperCamelCase : Union[str, Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate UpperCamelCase : List[Any] = Accelerator() set_seed(args.seed , device_specific=snake_case__ ) # Load model and tokenizer UpperCamelCase : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) UpperCamelCase : List[str] = tokenizer.eos_token UpperCamelCase : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings UpperCamelCase : Optional[Any] = { 'do_sample': args.do_sample, 'temperature': args.temperature, 'max_new_tokens': args.max_new_tokens, 'top_p': args.top_p, 'top_k': args.top_k, 'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , snake_case__ , snake_case__ )] ), } # Load evaluation dataset and metric UpperCamelCase : Dict = load_dataset('openai_humaneval' ) UpperCamelCase : List[str] = load_metric('code_eval' ) UpperCamelCase : Optional[int] = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] ) UpperCamelCase : Union[str, Any] = args.n_samples // args.batch_size UpperCamelCase : int = TokenizedDataset(snake_case__ , human_eval['test'] , n_copies=snake_case__ , n_tasks=snake_case__ ) # do not confuse args.batch_size, which is actually the num_return_sequences UpperCamelCase : Tuple = DataLoader(snake_case__ , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: UpperCamelCase : int = code_eval_metric.compute(references=[''] , predictions=[['']] ) except ValueError as exception: print( 'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`' ' flag to enable code evaluation.' ) raise exception UpperCamelCase , UpperCamelCase : Tuple = accelerator.prepare(snake_case__ , snake_case__ ) UpperCamelCase : List[Any] = complete_code( snake_case__ , snake_case__ , snake_case__ , snake_case__ , n_tasks=snake_case__ , batch_size=args.batch_size , **snake_case__ , ) if accelerator.is_main_process: UpperCamelCase : int = [] for task in tqdm(range(snake_case__ ) ): UpperCamelCase : Tuple = human_eval['test'][task]['test'] UpperCamelCase : str = F"""check({human_eval["test"][task]["entry_point"]})""" references.append('\n' + test_func + '\n' + entry_point ) # Evaluate completions with "code_eval" metric UpperCamelCase , UpperCamelCase : str = code_eval_metric.compute( references=snake_case__ , predictions=snake_case__ , num_workers=args.num_workers ) print(F"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , 'w' ) as fp: json.dump(snake_case__ , snake_case__ ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
40
"""simple docstring""" from __future__ import annotations from collections import namedtuple def __magic_name__ ( lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: str =namedtuple("""result""" , """name value""" ) if (voltage, current, power).count(0 ) != 1: raise ValueError("""Only one argument must be 0""" ) elif power < 0: raise ValueError( """Power cannot be negative in any electrical/electronics system""" ) elif voltage == 0: return result("""voltage""" , power / current ) elif current == 0: return result("""current""" , power / voltage ) elif power == 0: return result("""power""" , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
409
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def snake_case_ ( _lowerCAmelCase : Callable[[int | float], int | float] , _lowerCAmelCase : int | float , _lowerCAmelCase : int | float , _lowerCAmelCase : int = 100 , ) -> float: UpperCAmelCase : Optional[Any] = x_start UpperCAmelCase : Dict = fnc(snake_case__ ) UpperCAmelCase : Union[str, Any] = 0.0 for _ in range(snake_case__ ): # Approximates small segments of curve as linear and solve # for trapezoidal area UpperCAmelCase : int = (x_end - x_start) / steps + xa UpperCAmelCase : Optional[int] = fnc(snake_case__ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step UpperCAmelCase : str = xa UpperCAmelCase : str = fxa return area if __name__ == "__main__": def snake_case_ ( _lowerCAmelCase : Tuple ) -> List[str]: return x**3 + x**2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") UpperCamelCase__: Union[str, Any] = 10 while i <= 100000: print(F"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
717
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor UpperCamelCase__: Dict = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" def __init__( self : Optional[Any] , *__snake_case : List[str] , **__snake_case : str ) -> None: warnings.warn( '''The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use BeitImageProcessor instead.''' , __snake_case , ) super().__init__(*__snake_case , **__snake_case )
528
0
"""simple docstring""" import argparse from collections import defaultdict import yaml _A : int = "docs/source/en/_toctree.yml" def __magic_name__ ( __snake_case : List[str] ) -> Optional[Any]: lowercase : List[str] = defaultdict(UpperCamelCase__ ) lowercase : Optional[Any] = [] lowercase : str = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({"local": doc["local"], "title": doc["title"]} ) else: new_doc_list.append(UpperCamelCase__ ) lowercase : str = new_doc_list lowercase : List[str] = [key for key, value in counts.items() if value > 1] lowercase : Optional[int] = [] for duplicate_key in duplicates: lowercase : Optional[Any] = list({doc["title"] for doc in doc_list if doc["local"] == duplicate_key} ) if len(UpperCamelCase__ ) > 1: raise ValueError( f"""{duplicate_key} is present several times in the documentation table of content at """ "`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the " "others." ) # Only add this once new_doc.append({"local": duplicate_key, "title": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if "local" not in counts or counts[doc["local"]] == 1] ) lowercase : Tuple = sorted(UpperCamelCase__ , key=lambda __snake_case : s["title"].lower() ) # "overview" gets special treatment and is always first if len(UpperCamelCase__ ) > 1: raise ValueError("{doc_list} has two \'overview\' docs which is not allowed." ) overview_doc.extend(UpperCamelCase__ ) # Sort return overview_doc def __magic_name__ ( __snake_case : Optional[Any]=False ) -> Optional[int]: with open(UpperCamelCase__ , encoding="utf-8" ) as f: lowercase : Union[str, Any] = yaml.safe_load(f.read() ) # Get to the API doc lowercase : Optional[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowercase : List[Any] = content[api_idx]["sections"] # Then to the model doc lowercase : List[str] = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 lowercase : Union[str, Any] = api_doc[scheduler_idx]["sections"] lowercase : str = clean_doc_toc(UpperCamelCase__ ) lowercase : int = False if new_scheduler_doc != scheduler_doc: lowercase : Union[str, Any] = True if overwrite: lowercase : List[Any] = new_scheduler_doc if diff: if overwrite: lowercase : List[str] = api_doc with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) ) else: raise ValueError( "The model doc part of the table of content is not properly sorted, run `make style` to fix this." ) def __magic_name__ ( __snake_case : Optional[int]=False ) -> List[str]: with open(UpperCamelCase__ , encoding="utf-8" ) as f: lowercase : List[Any] = yaml.safe_load(f.read() ) # Get to the API doc lowercase : Optional[int] = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowercase : Tuple = content[api_idx]["sections"] # Then to the model doc lowercase : Tuple = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 lowercase : List[Any] = False lowercase : Tuple = api_doc[pipeline_idx]["sections"] lowercase : int = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: lowercase : Dict = pipeline_doc["section"] lowercase : Optional[Any] = clean_doc_toc(UpperCamelCase__ ) if overwrite: lowercase : List[str] = new_sub_pipeline_doc new_pipeline_docs.append(UpperCamelCase__ ) # sort overall pipeline doc lowercase : int = clean_doc_toc(UpperCamelCase__ ) if new_pipeline_docs != pipeline_docs: lowercase : Union[str, Any] = True if overwrite: lowercase : Union[str, Any] = new_pipeline_docs if diff: if overwrite: lowercase : Tuple = api_doc with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) ) else: raise ValueError( "The model doc part of the table of content is not properly sorted, run `make style` to fix this." ) if __name__ == "__main__": _A : Tuple = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") _A : Tuple = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
361
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __lowerCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class A ( UpperCAmelCase ): def __init__( self : Dict , __a : List[Any] , __a : Optional[Any] ) -> Dict: super().__init__() self.register_modules(unet=__a , scheduler=__a ) @torch.no_grad() def __call__( self : Tuple , __a : int = 1 , __a : int = 1_0_0 , __a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __a : Optional[float] = None , __a : bool = True , ) -> Union[AudioPipelineOutput, Tuple]: if audio_length_in_s is None: __UpperCAmelCase = self.unet.config.sample_size / self.unet.config.sample_rate __UpperCAmelCase = audio_length_in_s * self.unet.config.sample_rate __UpperCAmelCase = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" f""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) __UpperCAmelCase = int(__a ) if sample_size % down_scale_factor != 0: __UpperCAmelCase = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" f""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" ''' process.''' ) __UpperCAmelCase = int(__a ) __UpperCAmelCase = next(iter(self.unet.parameters() ) ).dtype __UpperCAmelCase = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(__a , __a ) and len(__a ) != batch_size: raise ValueError( f"""You have passed a list of generators of length {len(__a )}, but requested an effective batch""" f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) __UpperCAmelCase = randn_tensor(__a , generator=__a , device=self.device , dtype=__a ) # set step values self.scheduler.set_timesteps(__a , device=audio.device ) __UpperCAmelCase = self.scheduler.timesteps.to(__a ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output __UpperCAmelCase = self.unet(__a , __a ).sample # 2. compute previous image: x_t -> t_t-1 __UpperCAmelCase = self.scheduler.step(__a , __a , __a ).prev_sample __UpperCAmelCase = audio.clamp(-1 , 1 ).float().cpu().numpy() __UpperCAmelCase = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=__a )
262
0
import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def __a ( self :str ): UpperCamelCase__ :Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""" ) UpperCamelCase__ :str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""" ) model.to(_UpperCAmelCase ) from datasets import load_dataset UpperCamelCase__ :int = load_dataset("""nielsr/rvlcdip-demo""" ) UpperCamelCase__ :str = dataset['''train'''][0]['''image'''].convert("""RGB""" ) UpperCamelCase__ :Optional[int] = image_processor(_UpperCAmelCase , return_tensors="""pt""" ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): UpperCamelCase__ :Optional[Any] = model(**_UpperCAmelCase ) UpperCamelCase__ :List[str] = outputs.logits UpperCamelCase__ :Any = torch.Size((1, 16) ) self.assertEqual(logits.shape , _UpperCAmelCase ) UpperCamelCase__ :str = torch.tensor( [-0.4158, -0.4092, -0.4347] , device=_UpperCAmelCase , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _UpperCAmelCase , atol=1e-4 ) )
713
from manim import * class lowerCAmelCase_ ( lowercase ): """simple docstring""" def __a ( self :Optional[int] ): UpperCamelCase__ :Union[str, Any] = Rectangle(height=0.5 , width=0.5 ) UpperCamelCase__ :int = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCamelCase__ :Dict = [mem.copy() for i in range(6 )] UpperCamelCase__ :Any = [mem.copy() for i in range(6 )] UpperCamelCase__ :List[str] = VGroup(*lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0 ) UpperCamelCase__ :Any = VGroup(*lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0 ) UpperCamelCase__ :Dict = VGroup(lowerCamelCase__ , lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0 ) UpperCamelCase__ :Union[str, Any] = Text("""CPU""" , font_size=24 ) UpperCamelCase__ :str = Group(lowerCamelCase__ , lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0.5 , aligned_edge=lowerCamelCase__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowerCamelCase__ ) UpperCamelCase__ :List[str] = [mem.copy() for i in range(1 )] UpperCamelCase__ :Optional[int] = VGroup(*lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0 ) UpperCamelCase__ :Optional[Any] = Text("""GPU""" , font_size=24 ) UpperCamelCase__ :Any = Group(lowerCamelCase__ , lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0.5 , aligned_edge=lowerCamelCase__ ) gpu.align_to(lowerCamelCase__ , lowerCamelCase__ ) gpu.set_x(gpu.get_x() - 1 ) self.add(lowerCamelCase__ ) UpperCamelCase__ :Optional[int] = [mem.copy() for i in range(6 )] UpperCamelCase__ :Optional[Any] = VGroup(*lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0 ) UpperCamelCase__ :str = Text("""Model""" , font_size=24 ) UpperCamelCase__ :Optional[Any] = Group(lowerCamelCase__ , lowerCamelCase__ ).arrange(lowerCamelCase__ , buff=0.5 , aligned_edge=lowerCamelCase__ ) model.move_to([3, -1.0, 0] ) self.play( Create(lowerCamelCase__ , run_time=1 ) , Create(lowerCamelCase__ , run_time=1 ) , Create(lowerCamelCase__ , run_time=1 ) , ) UpperCamelCase__ :Tuple = MarkupText( f"""First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM.""" , font_size=24 , ) UpperCamelCase__ :Union[str, Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCamelCase__ :Tuple = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(lowerCamelCase__ , run_time=2.5 ) , Write(lowerCamelCase__ ) , Write(lowerCamelCase__ ) ) self.add(lowerCamelCase__ ) UpperCamelCase__ :Any = [] UpperCamelCase__ :List[Any] = [] UpperCamelCase__ :int = [] for i, rect in enumerate(lowerCamelCase__ ): UpperCamelCase__ :int = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(lowerCamelCase__ , opacity=0.7 ) cpu_target.move_to(lowerCamelCase__ ) cpu_target.generate_target() UpperCamelCase__ :Any = 0.46 / 4 UpperCamelCase__ :Optional[Any] = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=lowerCamelCase__ ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=lowerCamelCase__ , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=lowerCamelCase__ , buff=0.0 ) cpu_targs.append(lowerCamelCase__ ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(lowerCamelCase__ ) ) second_animations.append(MoveToTarget(lowerCamelCase__ , run_time=1.5 ) ) self.play(*lowerCamelCase__ ) self.play(*lowerCamelCase__ ) self.wait()
383
0