code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Dict ): super().__init__() UpperCamelCase :List[str] = nn.Linear(3 , 4 ) UpperCamelCase :Dict = nn.BatchNormad(4 ) UpperCamelCase :Optional[Any] = nn.Linear(4 , 5 ) def _A ( self : Tuple , __lowerCamelCase : List[str] ): return self.lineara(self.batchnorm(self.lineara(__lowerCamelCase ) ) ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Tuple ): UpperCamelCase :List[Any] = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(__lowerCamelCase , model.state_dict() ) UpperCamelCase :Dict = os.path.join(__lowerCamelCase , """index.json""" ) self.assertTrue(os.path.isfile(__lowerCamelCase ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: UpperCamelCase :Union[str, Any] = os.path.join(__lowerCamelCase , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(__lowerCamelCase ) ) # TODO: add tests on the fact weights are properly loaded def _A ( self : Optional[Any] ): UpperCamelCase :List[str] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: UpperCamelCase :Optional[Any] = torch.randn(2 , 3 , dtype=__lowerCamelCase ) with TemporaryDirectory() as tmp_dir: UpperCamelCase :Dict = offload_weight(__lowerCamelCase , """weight""" , __lowerCamelCase , {} ) UpperCamelCase :Optional[Any] = os.path.join(__lowerCamelCase , """weight.dat""" ) self.assertTrue(os.path.isfile(__lowerCamelCase ) ) self.assertDictEqual(__lowerCamelCase , {"""weight""": {"""shape""": [2, 3], """dtype""": str(__lowerCamelCase ).split(""".""" )[1]}} ) UpperCamelCase :str = load_offloaded_weight(__lowerCamelCase , index["""weight"""] ) self.assertTrue(torch.equal(__lowerCamelCase , __lowerCamelCase ) ) def _A ( self : str ): UpperCamelCase :List[str] = ModelForTest() UpperCamelCase :Optional[int] = model.state_dict() UpperCamelCase :Optional[Any] = {k: v for k, v in state_dict.items() if """linear2""" not in k} UpperCamelCase :List[str] = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = OffloadedWeightsLoader(state_dict=__lowerCamelCase , save_folder=__lowerCamelCase ) # Every key is there with the right value self.assertEqual(sorted(__lowerCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(__lowerCamelCase , weight_map[key] ) ) UpperCamelCase :Tuple = {k: v for k, v in state_dict.items() if """weight""" in k} UpperCamelCase :List[Any] = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = OffloadedWeightsLoader(state_dict=__lowerCamelCase , save_folder=__lowerCamelCase ) # Every key is there with the right value self.assertEqual(sorted(__lowerCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(__lowerCamelCase , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(__lowerCamelCase , __lowerCamelCase ) # Duplicates are removed UpperCamelCase :Optional[int] = OffloadedWeightsLoader(state_dict=__lowerCamelCase , save_folder=__lowerCamelCase ) # Every key is there with the right value self.assertEqual(sorted(__lowerCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(__lowerCamelCase , weight_map[key] ) ) def _A ( self : int ): UpperCamelCase :str = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} UpperCamelCase :Optional[int] = extract_submodules_state_dict(__lowerCamelCase , ["""a.1""", """a.2"""] ) self.assertDictEqual(__lowerCamelCase , {"""a.1""": 0, """a.2""": 2} ) UpperCamelCase :List[Any] = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} UpperCamelCase :List[Any] = extract_submodules_state_dict(__lowerCamelCase , ["""a.1""", """a.2"""] ) self.assertDictEqual(__lowerCamelCase , {"""a.1.a""": 0, """a.2.a""": 2} )
38
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase_ : Any = '''Create a default config file for Accelerate with only a few flags set.''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int]="no" , __magic_name__ : str = default_json_config_file , __magic_name__ : bool = False ) -> str: """simple docstring""" UpperCamelCase :Any = Path(__magic_name__ ) path.parent.mkdir(parents=__magic_name__ , exist_ok=__magic_name__ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False UpperCamelCase :Dict = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) UpperCamelCase :Optional[Any] = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): UpperCamelCase :Union[str, Any] = torch.cuda.device_count() UpperCamelCase :List[Any] = num_gpus UpperCamelCase :Dict = False if num_gpus > 1: UpperCamelCase :Any = """MULTI_GPU""" else: UpperCamelCase :Any = """NO""" elif is_xpu_available() and use_xpu: UpperCamelCase :Optional[Any] = torch.xpu.device_count() UpperCamelCase :Optional[int] = num_xpus UpperCamelCase :int = False if num_xpus > 1: UpperCamelCase :Union[str, Any] = """MULTI_XPU""" else: UpperCamelCase :Union[str, Any] = """NO""" elif is_npu_available(): UpperCamelCase :List[Any] = torch.npu.device_count() UpperCamelCase :Optional[Any] = num_npus UpperCamelCase :Tuple = False if num_npus > 1: UpperCamelCase :Optional[Any] = """MULTI_NPU""" else: UpperCamelCase :List[Any] = """NO""" else: UpperCamelCase :Any = 0 UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[str] = """NO""" UpperCamelCase :int = ClusterConfig(**__magic_name__ ) config.to_json_file(__magic_name__ ) return path def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = parser.add_parser("""default""" , parents=__magic_name__ , help=__magic_name__ , formatter_class=__magic_name__ ) parser.add_argument( """--config_file""" , default=__magic_name__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=__magic_name__ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=__magic_name__ ) return parser def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
38
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : int = { '''microsoft/markuplm-base''': '''https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json''', '''microsoft/markuplm-large''': '''https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json''', } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Tuple = """markuplm""" def __init__( self : Union[str, Any] , __lowerCamelCase : List[Any]=30_522 , __lowerCamelCase : Union[str, Any]=768 , __lowerCamelCase : Dict=12 , __lowerCamelCase : Optional[int]=12 , __lowerCamelCase : Optional[int]=3_072 , __lowerCamelCase : Optional[int]="gelu" , __lowerCamelCase : Tuple=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=512 , __lowerCamelCase : int=2 , __lowerCamelCase : Tuple=0.02 , __lowerCamelCase : Any=1E-12 , __lowerCamelCase : Any=0 , __lowerCamelCase : Union[str, Any]=0 , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : List[str]=256 , __lowerCamelCase : Union[str, Any]=1_024 , __lowerCamelCase : Any=216 , __lowerCamelCase : Optional[Any]=1_001 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : Dict=50 , __lowerCamelCase : Optional[int]="absolute" , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : int=None , **__lowerCamelCase : str , ): super().__init__( pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :str = vocab_size UpperCamelCase :List[str] = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :Dict = num_attention_heads UpperCamelCase :int = hidden_act UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :Any = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = max_position_embeddings UpperCamelCase :Optional[Any] = type_vocab_size UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :List[str] = layer_norm_eps UpperCamelCase :Optional[Any] = position_embedding_type UpperCamelCase :Optional[Any] = use_cache UpperCamelCase :Any = classifier_dropout # additional properties UpperCamelCase :Dict = max_depth UpperCamelCase :List[Any] = max_xpath_tag_unit_embeddings UpperCamelCase :List[Any] = max_xpath_subs_unit_embeddings UpperCamelCase :Dict = tag_pad_id UpperCamelCase :Optional[Any] = subs_pad_id UpperCamelCase :Any = xpath_unit_hidden_size
38
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
1
class _SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowerCamelCase : int ): UpperCamelCase :List[Any] = size UpperCamelCase :Optional[Any] = [0] * size UpperCamelCase :Any = [0] * size @staticmethod def _A ( __lowerCamelCase : int ): return index | (index + 1) @staticmethod def _A ( __lowerCamelCase : int ): return (index & (index + 1)) - 1 def _A ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : int ): UpperCamelCase :Union[str, Any] = value while index < self.size: UpperCamelCase :int = self.get_prev(__lowerCamelCase ) + 1 if current_left_border == index: UpperCamelCase :List[Any] = value else: UpperCamelCase :Union[str, Any] = max(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Tuple = self.get_next(__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : int , __lowerCamelCase : int ): right -= 1 # Because of right is exclusive UpperCamelCase :Union[str, Any] = 0 while left <= right: UpperCamelCase :List[Any] = self.get_prev(__lowerCamelCase ) if left <= current_left: UpperCamelCase :Tuple = max(__lowerCamelCase , self.tree[right] ) UpperCamelCase :List[Any] = current_left else: UpperCamelCase :Tuple = max(__lowerCamelCase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, 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 _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = ShapEImgaImgPipeline snake_case__ : Optional[Any] = ["""image"""] snake_case__ : Union[str, Any] = ["""image"""] snake_case__ : Optional[Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case__ : List[str] = False @property def _A ( self : Any ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Optional[Any] ): return self.time_input_dim * 4 @property def _A ( self : Union[str, Any] ): return 8 @property def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCamelCase :Optional[int] = CLIPVisionModel(__lowerCamelCase ) return model @property def _A ( self : str ): UpperCamelCase :Optional[int] = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def _A ( self : Tuple ): torch.manual_seed(0 ) UpperCamelCase :Dict = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase :int = PriorTransformer(**__lowerCamelCase ) return model @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) UpperCamelCase :str = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase :List[str] = ShapERenderer(**__lowerCamelCase ) return model def _A ( self : str ): UpperCamelCase :int = self.dummy_prior UpperCamelCase :Any = self.dummy_image_encoder UpperCamelCase :Dict = self.dummy_image_processor UpperCamelCase :List[Any] = self.dummy_renderer UpperCamelCase :int = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__lowerCamelCase , clip_sample=__lowerCamelCase , clip_sample_range=1.0 , ) UpperCamelCase :Optional[Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def _A ( self : int , __lowerCamelCase : int , __lowerCamelCase : Any=0 ): UpperCamelCase :Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :List[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _A ( self : List[str] ): UpperCamelCase :Dict = """cpu""" UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) UpperCamelCase :Dict = output.images[0] UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase :Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : List[Any] ): # 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 : List[Any] ): UpperCamelCase :str = torch_device == """cpu""" UpperCamelCase :int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , ) def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :List[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = 1 UpperCamelCase :int = 2 UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase :str = batch_size * [inputs[key]] UpperCamelCase :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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Any ): UpperCamelCase :Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCamelCase :Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( __lowerCamelCase , generator=__lowerCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
38
1
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets UpperCAmelCase_ : int = '''\ @inproceedings{lin-2004-rouge, title = "{ROUGE}: A Package for Automatic Evaluation of Summaries", author = "Lin, Chin-Yew", booktitle = "Text Summarization Branches Out", month = jul, year = "2004", address = "Barcelona, Spain", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W04-1013", pages = "74--81", } ''' UpperCAmelCase_ : Union[str, Any] = '''\ ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters. This metrics is a wrapper around Google Research reimplementation of ROUGE: https://github.com/google-research/google-research/tree/master/rouge ''' UpperCAmelCase_ : Any = ''' Calculates average rouge scores for a list of hypotheses and references Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. rouge_types: A list of rouge types to calculate. Valid names: `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring, `"rougeL"`: Longest common subsequence based scoring. `"rougeLSum"`: rougeLsum splits text using `"\n"`. See details in https://github.com/huggingface/datasets/issues/617 use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes. use_aggregator: Return aggregates if this is set to True Returns: rouge1: rouge_1 (precision, recall, f1), rouge2: rouge_2 (precision, recall, f1), rougeL: rouge_l (precision, recall, f1), rougeLsum: rouge_lsum (precision, recall, f1) Examples: >>> rouge = datasets.load_metric(\'rouge\') >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> results = rouge.compute(predictions=predictions, references=references) >>> print(list(results.keys())) [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\'] >>> print(results["rouge1"]) AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0)) >>> print(results["rouge1"].mid.fmeasure) 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/google-research/tree/master/rouge"""] , reference_urls=[ """https://en.wikipedia.org/wiki/ROUGE_(metric)""", """https://github.com/google-research/google-research/tree/master/rouge""", ] , ) def _A ( self : Optional[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str]=None , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Optional[int]=False ): if rouge_types is None: UpperCamelCase :Any = ["""rouge1""", """rouge2""", """rougeL""", """rougeLsum"""] UpperCamelCase :Any = rouge_scorer.RougeScorer(rouge_types=__lowerCamelCase , use_stemmer=__lowerCamelCase ) if use_aggregator: UpperCamelCase :Union[str, Any] = scoring.BootstrapAggregator() else: UpperCamelCase :Optional[int] = [] for ref, pred in zip(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :Optional[int] = scorer.score(__lowerCamelCase , __lowerCamelCase ) if use_aggregator: aggregator.add_scores(__lowerCamelCase ) else: scores.append(__lowerCamelCase ) if use_aggregator: UpperCamelCase :List[Any] = aggregator.aggregate() else: UpperCamelCase :Tuple = {} for key in scores[0]: UpperCamelCase :int = [score[key] for score in scores] return result
38
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record UpperCAmelCase_ : int = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' UpperCAmelCase_ : Optional[Any] = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' UpperCAmelCase_ : int = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any="binary" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = simple_accuracy(__magic_name__ , __magic_name__ ) UpperCamelCase :Dict = float(fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average=__magic_name__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = {} for id_pred, label in zip(__magic_name__ , __magic_name__ ): UpperCamelCase :str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCamelCase :Union[str, Any] = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase :Dict = [(pred, label)] UpperCamelCase , UpperCamelCase :Optional[int] = [], [] for question, preds_labels in question_map.items(): UpperCamelCase , UpperCamelCase :Optional[Any] = zip(*__magic_name__ ) UpperCamelCase :Optional[int] = fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average="""macro""" ) fas.append(__magic_name__ ) UpperCamelCase :int = int(sum(pred == label for pred, label in preds_labels ) == len(__magic_name__ ) ) ems.append(__magic_name__ ) UpperCamelCase :Optional[int] = float(sum(__magic_name__ ) / len(__magic_name__ ) ) UpperCamelCase :str = sum(__magic_name__ ) / len(__magic_name__ ) UpperCamelCase :Tuple = float(fa_score(y_true=__magic_name__ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : str ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _A ( self : Optional[Any] ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _A ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : str ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCamelCase :Optional[Any] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCamelCase :Tuple = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
38
1
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class _SCREAMING_SNAKE_CASE ( ctypes.Structure ): # _fields is a specific attr expected by ctypes snake_case__ : Union[str, Any] = [("""size""", ctypes.c_int), ("""visible""", ctypes.c_byte)] def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: """simple docstring""" if os.name == "nt": UpperCamelCase :Any = CursorInfo() UpperCamelCase :Any = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__magic_name__ , ctypes.byref(__magic_name__ ) ) UpperCamelCase :Union[str, Any] = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__magic_name__ , ctypes.byref(__magic_name__ ) ) elif os.name == "posix": sys.stdout.write("""\033[?25l""" ) sys.stdout.flush() def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: """simple docstring""" if os.name == "nt": UpperCamelCase :Tuple = CursorInfo() UpperCamelCase :int = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__magic_name__ , ctypes.byref(__magic_name__ ) ) UpperCamelCase :List[str] = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__magic_name__ , ctypes.byref(__magic_name__ ) ) elif os.name == "posix": sys.stdout.write("""\033[?25h""" ) sys.stdout.flush() @contextmanager def SCREAMING_SNAKE_CASE_ ( ) -> List[str]: """simple docstring""" try: hide_cursor() yield finally: show_cursor()
38
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any=13 , __lowerCamelCase : Dict=3 , __lowerCamelCase : int=224 , __lowerCamelCase : Any=30 , __lowerCamelCase : Tuple=400 , __lowerCamelCase : int=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , ): UpperCamelCase :List[Any] = size if size is not None else {"""height""": 18, """width""": 18} UpperCamelCase :str = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :Dict = num_channels UpperCamelCase :str = image_size UpperCamelCase :Dict = min_resolution UpperCamelCase :str = max_resolution UpperCamelCase :Union[str, Any] = do_resize UpperCamelCase :Optional[Any] = size UpperCamelCase :Any = do_normalize UpperCamelCase :Optional[Any] = image_mean UpperCamelCase :Tuple = image_std def _A ( self : int ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : List[Any] = ViTImageProcessor if is_vision_available() else None def _A ( self : str ): UpperCamelCase :Tuple = EfficientFormerImageProcessorTester(self ) @property def _A ( self : List[str] ): return self.image_proc_tester.prepare_image_processor_dict() def _A ( self : int ): UpperCamelCase :List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) def _A ( self : Optional[int] ): pass def _A ( self : str ): # Initialize image_processor UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :List[str] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :List[Any] = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : Union[str, Any] ): # Initialize image_processor UpperCamelCase :Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase :Dict = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :Tuple = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : List[Any] ): # Initialize image_processor UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase :List[Any] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :str = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
38
1
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer UpperCAmelCase_ : Optional[Any] = ['''bert-base-uncased''', '''bert-base-cased'''] UpperCAmelCase_ : List[str] = '''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class _SCREAMING_SNAKE_CASE ( tf.keras.Model ): def __init__( self : List[str] , __lowerCamelCase : Union[str, Any] ): super().__init__() UpperCamelCase :Any = tokenizer UpperCamelCase :List[str] = AutoConfig.from_pretrained(__lowerCamelCase ) UpperCamelCase :List[str] = TFAutoModel.from_config(__lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : str ): UpperCamelCase :str = self.tokenizer(__lowerCamelCase ) UpperCamelCase :Any = self.bert(**__lowerCamelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Dict ): super().setUp() UpperCamelCase :int = [ BertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase :Any = [TFBertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(__lowerCamelCase , use_fast_bert_tokenizer=__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase :Any = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] UpperCamelCase :Union[str, Any] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _A ( self : Optional[int] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tokenizer(__lowerCamelCase , return_tensors="""tf""" , padding="""longest""" ) UpperCamelCase :str = tf_tokenizer(__lowerCamelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _A ( self : Dict ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :str = tf_tokenizer(self.paired_sentences ) UpperCamelCase :Any = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _A ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[Any] = tf.function(__lowerCamelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tf.constant(__lowerCamelCase ) UpperCamelCase :List[str] = compiled_tokenizer(__lowerCamelCase ) UpperCamelCase :Optional[Any] = tf_tokenizer(__lowerCamelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _A ( self : Tuple ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[str] = ModelToSave(tokenizer=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase :List[str] = Path(__lowerCamelCase ) / """saved.model""" model.save(__lowerCamelCase ) UpperCamelCase :List[Any] = tf.keras.models.load_model(__lowerCamelCase ) UpperCamelCase :Dict = loaded_model(__lowerCamelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
38
from collections.abc import Generator from math import sin def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" if len(__magic_name__ ) != 32: raise ValueError("""Input must be of length 32""" ) UpperCamelCase :int = B"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bytes: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :Any = format(__magic_name__ , """08x""" )[-8:] UpperCamelCase :Union[str, Any] = B"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :str = B"""""" for char in message: bit_string += format(__magic_name__ , """08b""" ).encode("""utf-8""" ) UpperCamelCase :Any = format(len(__magic_name__ ) , """064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__magic_name__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> Generator[list[int], None, None]: """simple docstring""" if len(__magic_name__ ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 , len(__magic_name__ ) , 512 ): UpperCamelCase :Tuple = bit_string[pos : pos + 512] UpperCamelCase :Optional[int] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :List[str] = format(__magic_name__ , """032b""" ) UpperCamelCase :Any = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(__magic_name__ , 2 ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" return (a + b) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :Tuple = preprocess(__magic_name__ ) UpperCamelCase :List[str] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states UpperCamelCase :Union[str, Any] = 0X67_45_23_01 UpperCamelCase :Union[str, Any] = 0XEF_CD_AB_89 UpperCamelCase :List[str] = 0X98_BA_DC_FE UpperCamelCase :int = 0X10_32_54_76 UpperCamelCase :int = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__magic_name__ ): UpperCamelCase :Optional[Any] = aa UpperCamelCase :Any = ba UpperCamelCase :Tuple = ca UpperCamelCase :List[str] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f UpperCamelCase :int = d ^ (b & (c ^ d)) UpperCamelCase :Optional[int] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f UpperCamelCase :str = c ^ (d & (b ^ c)) UpperCamelCase :Union[str, Any] = (5 * i + 1) % 16 elif i <= 47: UpperCamelCase :str = b ^ c ^ d UpperCamelCase :Optional[int] = (3 * i + 5) % 16 else: UpperCamelCase :List[str] = c ^ (b | not_aa(__magic_name__ )) UpperCamelCase :int = (7 * i) % 16 UpperCamelCase :Dict = (f + a + added_consts[i] + block_words[g]) % 2**32 UpperCamelCase :Tuple = d UpperCamelCase :str = c UpperCamelCase :Tuple = b UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , left_rotate_aa(__magic_name__ , shift_amounts[i] ) ) # Add hashed chunk to running total UpperCamelCase :List[str] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :str = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :int = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
38
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[int] = CycleDiffusionPipeline snake_case__ : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { """negative_prompt""", """height""", """width""", """negative_prompt_embeds""", } snake_case__ : Any = PipelineTesterMixin.required_optional_params - {"""latents"""} snake_case__ : Tuple = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""source_prompt"""} ) snake_case__ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS snake_case__ : List[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : str ): torch.manual_seed(0 ) UpperCamelCase :Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) UpperCamelCase :Union[str, Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , num_train_timesteps=1_000 , clip_sample=__lowerCamelCase , set_alpha_to_one=__lowerCamelCase , ) torch.manual_seed(0 ) UpperCamelCase :Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase :List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) UpperCamelCase :List[Any] = CLIPTextModel(__lowerCamelCase ) UpperCamelCase :Optional[int] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCamelCase :List[str] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _A ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any]=0 ): UpperCamelCase :Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) UpperCamelCase :List[str] = image / 2 + 0.5 if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :Union[str, Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :List[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """prompt""": """An astronaut riding an elephant""", """source_prompt""": """An astronaut riding a horse""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """eta""": 0.1, """strength""": 0.8, """guidance_scale""": 3, """source_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def _A ( self : Optional[int] ): UpperCamelCase :Dict = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :str = self.get_dummy_components() UpperCamelCase :int = CycleDiffusionPipeline(**__lowerCamelCase ) UpperCamelCase :Dict = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Tuple = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Any = pipe(**__lowerCamelCase ) UpperCamelCase :Dict = output.images UpperCamelCase :Any = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) UpperCamelCase :int = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def _A ( self : Optional[int] ): UpperCamelCase :Dict = self.get_dummy_components() for name, module in components.items(): if hasattr(__lowerCamelCase , """half""" ): UpperCamelCase :Optional[Any] = module.half() UpperCamelCase :int = CycleDiffusionPipeline(**__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = pipe(**__lowerCamelCase ) UpperCamelCase :List[str] = output.images UpperCamelCase :Optional[Any] = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) UpperCamelCase :List[str] = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def _A ( self : List[str] ): return super().test_save_load_local() @unittest.skip("""non-deterministic pipeline""" ) def _A ( self : Optional[int] ): return super().test_inference_batch_single_identical() @skip_mps def _A ( self : Optional[int] ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def _A ( self : List[str] ): return super().test_save_load_optional_components() @skip_mps def _A ( self : Tuple ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Tuple ): UpperCamelCase :int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) UpperCamelCase :List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""" ) UpperCamelCase :Any = init_image.resize((512, 512) ) UpperCamelCase :Dict = """CompVis/stable-diffusion-v1-4""" UpperCamelCase :List[Any] = DDIMScheduler.from_pretrained(__lowerCamelCase , subfolder="""scheduler""" ) UpperCamelCase :str = CycleDiffusionPipeline.from_pretrained( __lowerCamelCase , scheduler=__lowerCamelCase , safety_checker=__lowerCamelCase , torch_dtype=torch.floataa , revision="""fp16""" ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) pipe.enable_attention_slicing() UpperCamelCase :List[Any] = """A black colored car""" UpperCamelCase :Tuple = """A blue colored car""" UpperCamelCase :Tuple = torch.manual_seed(0 ) UpperCamelCase :List[Any] = pipe( prompt=__lowerCamelCase , source_prompt=__lowerCamelCase , image=__lowerCamelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__lowerCamelCase , output_type="""np""" , ) UpperCamelCase :Optional[int] = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5E-1 def _A ( self : Optional[Any] ): UpperCamelCase :Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""" ) UpperCamelCase :Optional[Any] = init_image.resize((512, 512) ) UpperCamelCase :str = """CompVis/stable-diffusion-v1-4""" UpperCamelCase :Union[str, Any] = DDIMScheduler.from_pretrained(__lowerCamelCase , subfolder="""scheduler""" ) UpperCamelCase :str = CycleDiffusionPipeline.from_pretrained(__lowerCamelCase , scheduler=__lowerCamelCase , safety_checker=__lowerCamelCase ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) pipe.enable_attention_slicing() UpperCamelCase :Dict = """A black colored car""" UpperCamelCase :str = """A blue colored car""" UpperCamelCase :List[Any] = torch.manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( prompt=__lowerCamelCase , source_prompt=__lowerCamelCase , image=__lowerCamelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__lowerCamelCase , output_type="""np""" , ) UpperCamelCase :Optional[int] = output.images assert np.abs(image - expected_image ).max() < 2E-2
38
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[Any] , __lowerCamelCase : Callable , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[dict] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : List[Any] , ): super().__init__( features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = Generator( cache_dir=__lowerCamelCase , features=__lowerCamelCase , generator=__lowerCamelCase , gen_kwargs=__lowerCamelCase , **__lowerCamelCase , ) def _A ( self : List[str] ): # Build iterable dataset if self.streaming: UpperCamelCase :Any = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: UpperCamelCase :Tuple = None UpperCamelCase :Dict = None UpperCamelCase :Dict = None UpperCamelCase :List[str] = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) UpperCamelCase :Tuple = self.builder.as_dataset( split="""train""" , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
38
1
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bool: """simple docstring""" UpperCamelCase :int = int(number**0.5 ) return number == sq * sq def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int ) -> tuple[int, int]: """simple docstring""" UpperCamelCase :int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCamelCase :int = x_den * y_den * z_den UpperCamelCase :int = gcd(__magic_name__ , __magic_name__ ) top //= hcf bottom //= hcf return top, bottom def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 35 ) -> int: """simple docstring""" UpperCamelCase :set = set() UpperCamelCase :int UpperCamelCase :Fraction = Fraction(0 ) UpperCamelCase :tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 UpperCamelCase :List[str] = x_num * y_den + x_den * y_num UpperCamelCase :Dict = x_den * y_den UpperCamelCase :str = gcd(__magic_name__ , __magic_name__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase :Tuple = add_three( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) unique_s.add(__magic_name__ ) # n=2 UpperCamelCase :Optional[Any] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCamelCase :str = x_den * x_den * y_den * y_den if is_sq(__magic_name__ ) and is_sq(__magic_name__ ): UpperCamelCase :Optional[Any] = int(sqrt(__magic_name__ ) ) UpperCamelCase :Optional[int] = int(sqrt(__magic_name__ ) ) UpperCamelCase :int = gcd(__magic_name__ , __magic_name__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase :Union[str, Any] = add_three( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) unique_s.add(__magic_name__ ) # n=-1 UpperCamelCase :Tuple = x_num * y_num UpperCamelCase :List[Any] = x_den * y_num + x_num * y_den UpperCamelCase :List[str] = gcd(__magic_name__ , __magic_name__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase :List[Any] = add_three( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) unique_s.add(__magic_name__ ) # n=2 UpperCamelCase :Tuple = x_num * x_num * y_num * y_num UpperCamelCase :str = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__magic_name__ ) and is_sq(__magic_name__ ): UpperCamelCase :List[Any] = int(sqrt(__magic_name__ ) ) UpperCamelCase :str = int(sqrt(__magic_name__ ) ) UpperCamelCase :Any = gcd(__magic_name__ , __magic_name__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase :int = add_three( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) unique_s.add(__magic_name__ ) for num, den in unique_s: total += Fraction(__magic_name__ , __magic_name__ ) return total.denominator + total.numerator if __name__ == "__main__": print(F'''{solution() = }''')
38
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase_ : Union[str, Any] = 16 UpperCAmelCase_ : int = 32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 , __magic_name__ : str = "bert-base-cased" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = AutoTokenizer.from_pretrained(__magic_name__ ) UpperCamelCase :Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__magic_name__ : Tuple ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase :List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__magic_name__ , max_length=__magic_name__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase :List[Any] = datasets.map( __magic_name__ , batched=__magic_name__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__magic_name__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase :Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__magic_name__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__magic_name__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__magic_name__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase :List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) UpperCamelCase :List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase :Union[str, Any] = config["""lr"""] UpperCamelCase :List[str] = int(config["""num_epochs"""] ) UpperCamelCase :str = int(config["""seed"""] ) UpperCamelCase :Dict = int(config["""batch_size"""] ) UpperCamelCase :Union[str, Any] = args.model_name_or_path set_seed(__magic_name__ ) UpperCamelCase , UpperCamelCase :Dict = get_dataloaders(__magic_name__ , __magic_name__ , __magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase :List[str] = AutoModelForSequenceClassification.from_pretrained(__magic_name__ , return_dict=__magic_name__ ) # Instantiate optimizer UpperCamelCase :Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase :Optional[Any] = optimizer_cls(params=model.parameters() , lr=__magic_name__ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase :Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase :Any = 1 UpperCamelCase :Dict = (len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase :List[Any] = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=0 , num_training_steps=__magic_name__ , ) else: UpperCamelCase :Any = DummyScheduler(__magic_name__ , total_num_steps=__magic_name__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase :int = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase :Tuple = 0 # Now we train the model UpperCamelCase :Any = evaluate.load("""glue""" , """mrpc""" ) UpperCamelCase :Tuple = 0 UpperCamelCase :List[Any] = {} for epoch in range(__magic_name__ , __magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): UpperCamelCase :List[str] = model(**__magic_name__ ) UpperCamelCase :Dict = outputs.loss UpperCamelCase :Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__magic_name__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCamelCase :str = 0 for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__magic_name__ ) UpperCamelCase :List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase , UpperCamelCase :Optional[int] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__magic_name__ ) - 1: UpperCamelCase :Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) UpperCamelCase :List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __magic_name__ ) UpperCamelCase :Dict = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCamelCase :str = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :List[str] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__magic_name__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__magic_name__ , ) parser.add_argument( """--output_dir""" , type=__magic_name__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__magic_name__ , default=__magic_name__ , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__magic_name__ , default=3 , help="""Number of train epochs.""" , ) UpperCamelCase :str = parser.parse_args() UpperCamelCase :Any = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : int ) -> list[str]: """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(__magic_name__ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
38
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[Any] = TransfoXLTokenizer snake_case__ : List[Any] = False snake_case__ : Tuple = False def _A ( self : str ): super().setUp() UpperCamelCase :Dict = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _A ( self : List[str] , **__lowerCamelCase : Any ): UpperCamelCase :Any = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : int ): UpperCamelCase :List[Any] = """<unk> UNwanted , running""" UpperCamelCase :int = """<unk> unwanted, running""" return input_text, output_text def _A ( self : Tuple ): UpperCamelCase :List[str] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__lowerCamelCase ) UpperCamelCase :Any = tokenizer.tokenize("""<unk> UNwanted , running""" ) self.assertListEqual(__lowerCamelCase , ["""<unk>""", """unwanted""", """,""", """running"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [0, 4, 8, 7] ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _A ( self : Tuple ): UpperCamelCase :Any = TransfoXLTokenizer(lower_case=__lowerCamelCase ) UpperCamelCase :Optional[int] = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" UpperCamelCase :Optional[int] = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(__lowerCamelCase ) , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = len(__lowerCamelCase ) tokenizer.add_tokens(["""new1""", """new2"""] ) tokenizer.move_added_token("""new1""" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , """new1""" )
38
1
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[Any]=13 , __lowerCamelCase : List[Any]=32 , __lowerCamelCase : Tuple=2 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : Optional[int]=16 , __lowerCamelCase : Optional[int]=[32, 64, 128] , __lowerCamelCase : int=[1, 2, 1] , __lowerCamelCase : int=[2, 2, 4] , __lowerCamelCase : Any=2 , __lowerCamelCase : Tuple=2.0 , __lowerCamelCase : Tuple=True , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Dict=0.0 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : List[str]="gelu" , __lowerCamelCase : Tuple=False , __lowerCamelCase : str=True , __lowerCamelCase : List[Any]=0.02 , __lowerCamelCase : Optional[Any]=1E-5 , __lowerCamelCase : int=True , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : int=True , __lowerCamelCase : str=10 , __lowerCamelCase : Tuple=8 , __lowerCamelCase : List[Any]=["stage1", "stage2"] , __lowerCamelCase : Union[str, Any]=[1, 2] , ): UpperCamelCase :str = parent UpperCamelCase :Dict = batch_size UpperCamelCase :str = image_size UpperCamelCase :List[Any] = patch_size UpperCamelCase :Union[str, Any] = num_channels UpperCamelCase :str = embed_dim UpperCamelCase :int = hidden_sizes UpperCamelCase :Any = depths UpperCamelCase :Union[str, Any] = num_heads UpperCamelCase :List[str] = window_size UpperCamelCase :int = mlp_ratio UpperCamelCase :int = qkv_bias UpperCamelCase :Optional[int] = hidden_dropout_prob UpperCamelCase :Optional[int] = attention_probs_dropout_prob UpperCamelCase :Tuple = drop_path_rate UpperCamelCase :Optional[Any] = hidden_act UpperCamelCase :List[Any] = use_absolute_embeddings UpperCamelCase :List[Any] = patch_norm UpperCamelCase :int = layer_norm_eps UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :Union[str, Any] = is_training UpperCamelCase :Tuple = scope UpperCamelCase :int = use_labels UpperCamelCase :Optional[int] = type_sequence_label_size UpperCamelCase :Union[str, Any] = encoder_stride UpperCamelCase :List[str] = out_features UpperCamelCase :List[Any] = out_indices def _A ( self : List[str] ): UpperCamelCase :int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :str = None if self.use_labels: UpperCamelCase :str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :Dict = self.get_config() return config, pixel_values, labels def _A ( self : Optional[int] ): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _A ( self : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] ): UpperCamelCase :Union[str, Any] = FocalNetModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase ) UpperCamelCase :Optional[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase :Tuple = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _A ( self : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : int , __lowerCamelCase : List[str] ): UpperCamelCase :List[str] = FocalNetBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :List[str] = model(__lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None UpperCamelCase :List[Any] = None UpperCamelCase :Dict = FocalNetBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Dict = model(__lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _A ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : int ): UpperCamelCase :Tuple = FocalNetForMaskedImageModeling(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCamelCase :str = 1 UpperCamelCase :List[str] = FocalNetForMaskedImageModeling(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase :Tuple = model(__lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _A ( self : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] ): UpperCamelCase :Optional[int] = self.type_sequence_label_size UpperCamelCase :Optional[Any] = FocalNetForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Tuple = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase :List[str] = 1 UpperCamelCase :Union[str, Any] = FocalNetForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A ( self : str ): UpperCamelCase :Optional[Any] = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :Tuple = config_and_inputs UpperCamelCase :str = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : str = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) snake_case__ : List[str] = ( {"""feature-extraction""": FocalNetModel, """image-classification""": FocalNetForImageClassification} if is_torch_available() else {} ) snake_case__ : Optional[int] = False snake_case__ : Tuple = False snake_case__ : Optional[Any] = False snake_case__ : Optional[int] = False snake_case__ : Union[str, Any] = False def _A ( self : Optional[Any] ): UpperCamelCase :Dict = FocalNetModelTester(self ) UpperCamelCase :Optional[int] = ConfigTester(self , config_class=__lowerCamelCase , embed_dim=37 , has_text_modality=__lowerCamelCase ) def _A ( self : Union[str, Any] ): 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 : List[Any] ): return def _A ( self : Dict ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__lowerCamelCase ) def _A ( self : Any ): UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @unittest.skip(reason="""FocalNet does not use inputs_embeds""" ) def _A ( self : Optional[int] ): pass @unittest.skip(reason="""FocalNet does not use feedforward chunking""" ) def _A ( self : Optional[Any] ): pass def _A ( self : List[str] ): UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase :Optional[Any] = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase , nn.Linear ) ) def _A ( self : int ): UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase :Dict = model_class(__lowerCamelCase ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Union[str, Any] = [*signature.parameters.keys()] UpperCamelCase :str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Dict ): UpperCamelCase :Optional[Any] = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :Optional[int] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) UpperCamelCase :Tuple = outputs.hidden_states UpperCamelCase :Union[str, Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) # FocalNet has a different seq_length UpperCamelCase :Optional[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase :Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) UpperCamelCase :Union[str, Any] = outputs.reshaped_hidden_states self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = reshaped_hidden_states[0].shape UpperCamelCase :List[Any] = ( reshaped_hidden_states[0].view(__lowerCamelCase , __lowerCamelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _A ( self : List[Any] ): UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: UpperCamelCase :List[Any] = True self.check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase :Optional[Any] = True self.check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _A ( self : int ): UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :List[str] = 3 UpperCamelCase :Optional[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase :List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase :Optional[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase :Dict = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: UpperCamelCase :Optional[Any] = True self.check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase :Dict = True self.check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , (padded_height, padded_width) ) @slow def _A ( self : Tuple ): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Union[str, Any] = FocalNetModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = _config_zero_init(__lowerCamelCase ) for model_class in self.all_model_classes: UpperCamelCase :Optional[Any] = model_class(config=__lowerCamelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def _A ( self : List[str] ): # TODO update organization return AutoImageProcessor.from_pretrained("""microsoft/focalnet-tiny""" ) if is_vision_available() else None @slow def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny""" ).to(__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.default_image_processor UpperCamelCase :List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) UpperCamelCase :int = image_processor(images=__lowerCamelCase , return_tensors="""pt""" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): UpperCamelCase :int = model(**__lowerCamelCase ) # verify the logits UpperCamelCase :str = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) UpperCamelCase :Tuple = torch.tensor([0.2166, -0.4368, 0.2191] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 281 ) @require_torch class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[Any] = (FocalNetBackbone,) if is_torch_available() else () snake_case__ : str = FocalNetConfig snake_case__ : int = False def _A ( self : List[str] ): UpperCamelCase :Optional[Any] = FocalNetModelTester(self )
38
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase_ : int = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[int] ) -> Dict: """simple docstring""" for attribute in key.split(""".""" ): UpperCamelCase :Dict = getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: UpperCamelCase :Optional[int] = getattr(__magic_name__ , __magic_name__ ).shape else: UpperCamelCase :Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCamelCase :str = value elif weight_type == "weight_g": UpperCamelCase :int = value elif weight_type == "weight_v": UpperCamelCase :int = value elif weight_type == "bias": UpperCamelCase :List[Any] = value else: UpperCamelCase :Any = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Dict = fairseq_model.state_dict() UpperCamelCase :int = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase :str = False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == """group""" , ) UpperCamelCase :Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase :Optional[int] = True if "*" in mapped_key: UpperCamelCase :List[Any] = name.split(__magic_name__ )[0].split(""".""" )[-2] UpperCamelCase :int = mapped_key.replace("""*""" , __magic_name__ ) if "weight_g" in name: UpperCamelCase :List[Any] = """weight_g""" elif "weight_v" in name: UpperCamelCase :List[Any] = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase :Any = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase :List[str] = """weight""" else: UpperCamelCase :Optional[int] = None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int , __magic_name__ : List[str] ) -> Dict: """simple docstring""" UpperCamelCase :Dict = full_name.split("""conv_layers.""" )[-1] UpperCamelCase :int = name.split(""".""" ) UpperCamelCase :str = int(items[0] ) UpperCamelCase :str = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCamelCase :Dict = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCamelCase :Union[str, Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : List[Any] , __magic_name__ : str=None ) -> int: """simple docstring""" UpperCamelCase :List[Any] = torch.load(__magic_name__ ) UpperCamelCase :List[Any] = WavLMConfigOrig(checkpoint["""cfg"""] ) UpperCamelCase :int = WavLMOrig(__magic_name__ ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: UpperCamelCase :List[Any] = WavLMConfig.from_pretrained(__magic_name__ ) else: UpperCamelCase :Any = WavLMConfig() UpperCamelCase :Dict = WavLMModel(__magic_name__ ) recursively_load_weights(__magic_name__ , __magic_name__ ) hf_wavlm.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') UpperCAmelCase_ : Optional[int] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
38
1
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = ["""pixel_values"""] def __init__( self : str , __lowerCamelCase : bool = True , __lowerCamelCase : int = 32 , __lowerCamelCase : List[str]=PILImageResampling.BILINEAR , __lowerCamelCase : bool = True , **__lowerCamelCase : Optional[Any] , ): UpperCamelCase :List[str] = do_resize UpperCamelCase :Tuple = do_rescale UpperCamelCase :str = size_divisor UpperCamelCase :Any = resample super().__init__(**__lowerCamelCase ) def _A ( self : Optional[Any] , __lowerCamelCase : np.ndarray , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : Optional[ChannelDimension] = None , **__lowerCamelCase : List[Any] ): UpperCamelCase , UpperCamelCase :Tuple = get_image_size(__lowerCamelCase ) # Rounds the height and width down to the closest multiple of size_divisor UpperCamelCase :Union[str, Any] = height // size_divisor * size_divisor UpperCamelCase :int = width // size_divisor * size_divisor UpperCamelCase :List[str] = resize(__lowerCamelCase , (new_h, new_w) , resample=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) return image def _A ( self : str , __lowerCamelCase : np.ndarray , __lowerCamelCase : float , __lowerCamelCase : Optional[ChannelDimension] = None , **__lowerCamelCase : List[str] ): return rescale(image=__lowerCamelCase , scale=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def _A ( self : Dict , __lowerCamelCase : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[Union[TensorType, str]] = None , __lowerCamelCase : ChannelDimension = ChannelDimension.FIRST , **__lowerCamelCase : Optional[int] , ): UpperCamelCase :int = do_resize if do_resize is not None else self.do_resize UpperCamelCase :Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase :Union[str, Any] = size_divisor if size_divisor is not None else self.size_divisor UpperCamelCase :Optional[int] = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("""size_divisor is required for resizing""" ) UpperCamelCase :str = make_list_of_images(__lowerCamelCase ) if not valid_images(__lowerCamelCase ): raise ValueError("""Invalid image(s)""" ) # All transformations expect numpy arrays. UpperCamelCase :Dict = [to_numpy_array(__lowerCamelCase ) for img in images] if do_resize: UpperCamelCase :Any = [self.resize(__lowerCamelCase , size_divisor=__lowerCamelCase , resample=__lowerCamelCase ) for image in images] if do_rescale: UpperCamelCase :Dict = [self.rescale(__lowerCamelCase , scale=1 / 255 ) for image in images] UpperCamelCase :Tuple = [to_channel_dimension_format(__lowerCamelCase , __lowerCamelCase ) for image in images] UpperCamelCase :List[str] = {"""pixel_values""": images} return BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase )
38
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCAmelCase_ : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""bs4"""] ) super().__init__(**__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = [] UpperCamelCase :List[str] = [] UpperCamelCase :Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag UpperCamelCase :Optional[Any] = parent.find_all(child.name , recursive=__lowerCamelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCamelCase ) else next(i for i, s in enumerate(__lowerCamelCase , 1 ) if s is child ) ) UpperCamelCase :Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Any = BeautifulSoup(__lowerCamelCase , """html.parser""" ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Tuple = [] UpperCamelCase :Tuple = [] for element in html_code.descendants: if type(__lowerCamelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue UpperCamelCase :Any = html.unescape(__lowerCamelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = self.xpath_soup(__lowerCamelCase ) stringaxtag_seq.append(__lowerCamelCase ) stringaxsubs_seq.append(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Tuple = """""" for tagname, subs in zip(__lowerCamelCase , __lowerCamelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Any , __lowerCamelCase : Dict ): UpperCamelCase :Any = False # Check that strings has a valid type if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = True elif isinstance(__lowerCamelCase , (list, tuple) ): if len(__lowerCamelCase ) == 0 or isinstance(html_strings[0] , __lowerCamelCase ): UpperCamelCase :Any = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ F"""but is of type {type(__lowerCamelCase )}.""" ) UpperCamelCase :str = bool(isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(html_strings[0] , __lowerCamelCase )) ) if not is_batched: UpperCamelCase :Any = [html_strings] # Get nodes + xpaths UpperCamelCase :Union[str, Any] = [] UpperCamelCase :str = [] for html_string in html_strings: UpperCamelCase , UpperCamelCase , UpperCamelCase :int = self.get_three_from_single(__lowerCamelCase ) nodes.append(__lowerCamelCase ) UpperCamelCase :int = [] for node, tag_list, sub_list in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): UpperCamelCase :str = self.construct_xpath(__lowerCamelCase , __lowerCamelCase ) xpath_strings.append(__lowerCamelCase ) xpaths.append(__lowerCamelCase ) # return as Dict UpperCamelCase :Optional[int] = {"""nodes""": nodes, """xpaths""": xpaths} UpperCamelCase :Any = BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) return encoded_inputs
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 50 ) -> int: """simple docstring""" UpperCamelCase :Any = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F'''{solution() = }''')
38
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : list[int] ) -> bool: """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : list[int] , __magic_name__ : int ) -> bool: """simple docstring""" if curr_ind == len(__magic_name__ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__magic_name__ ) ): if valid_connection(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): # Insert current vertex into path as next transition UpperCamelCase :str = next_ver # Validate created path if util_hamilton_cycle(__magic_name__ , __magic_name__ , curr_ind + 1 ): return True # Backtrack UpperCamelCase :Union[str, Any] = -1 return False def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int = 0 ) -> list[int]: """simple docstring""" UpperCamelCase :Union[str, Any] = [-1] * (len(__magic_name__ ) + 1) # initialize start and end of path with starting index UpperCamelCase :Any = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__magic_name__ , __magic_name__ , 1 ) else []
38
1
import gc import threading import time import psutil import torch class _SCREAMING_SNAKE_CASE : def __init__( self : List[Any] ): UpperCamelCase :List[str] = psutil.Process() UpperCamelCase :Optional[Any] = False def _A ( self : Optional[int] ): UpperCamelCase :List[str] = -1 while True: UpperCamelCase :Union[str, Any] = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def _A ( self : str ): UpperCamelCase :Dict = True UpperCamelCase :List[str] = threading.Thread(target=self.peak_monitor ) UpperCamelCase :Optional[Any] = True self.thread.start() def _A ( self : Optional[int] ): UpperCamelCase :Any = False self.thread.join() return self.cpu_memory_peak UpperCAmelCase_ : List[str] = PeakCPUMemory() def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: """simple docstring""" UpperCamelCase :Dict = {"""time""": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem UpperCamelCase :Optional[Any] = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): UpperCamelCase :Union[str, Any] = torch.cuda.memory_allocated(__magic_name__ ) torch.cuda.reset_peak_memory_stats() return measures def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] ) -> Any: """simple docstring""" UpperCamelCase :List[Any] = {"""time""": time.time() - start_measures["""time"""]} gc.collect() torch.cuda.empty_cache() # CPU mem UpperCamelCase :str = (psutil.Process().memory_info().rss - start_measures["""cpu"""]) / 2**20 UpperCamelCase :Optional[Any] = (cpu_peak_tracker.stop() - start_measures["""cpu"""]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): UpperCamelCase :Optional[int] = (torch.cuda.memory_allocated(__magic_name__ ) - start_measures[str(__magic_name__ )]) / 2**20 UpperCamelCase :Any = (torch.cuda.max_memory_allocated(__magic_name__ ) - start_measures[str(__magic_name__ )]) / 2**20 return measures def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" print(f"""{description}:""" ) print(f"""- Time: {measures['time']:.2f}s""" ) for i in range(torch.cuda.device_count() ): print(f"""- GPU {i} allocated: {measures[str(__magic_name__ )]:.2f}MiB""" ) UpperCamelCase :Optional[Any] = measures[f"""{i}-peak"""] print(f"""- GPU {i} peak: {peak:.2f}MiB""" ) print(f"""- CPU RAM allocated: {measures['cpu']:.2f}MiB""" ) print(f"""- CPU RAM peak: {measures['cpu-peak']:.2f}MiB""" )
38
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : str=7 , __lowerCamelCase : Tuple=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Any=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : str=False , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : Any=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : List[Any]=12 , __lowerCamelCase : int=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Optional[int]="last" , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[str]=None , ): UpperCamelCase :int = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :str = seq_length UpperCamelCase :Optional[int] = is_training UpperCamelCase :Optional[int] = use_input_lengths UpperCamelCase :Union[str, Any] = use_token_type_ids UpperCamelCase :List[str] = use_labels UpperCamelCase :Dict = gelu_activation UpperCamelCase :Optional[int] = sinusoidal_embeddings UpperCamelCase :List[Any] = causal UpperCamelCase :Optional[int] = asm UpperCamelCase :List[str] = n_langs UpperCamelCase :int = vocab_size UpperCamelCase :List[Any] = n_special UpperCamelCase :List[Any] = hidden_size UpperCamelCase :List[str] = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :Tuple = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :List[str] = type_vocab_size UpperCamelCase :Union[str, Any] = type_sequence_label_size UpperCamelCase :int = initializer_range UpperCamelCase :List[str] = num_labels UpperCamelCase :Optional[int] = num_choices UpperCamelCase :Optional[Any] = summary_type UpperCamelCase :Tuple = use_proj UpperCamelCase :Optional[Any] = scope def _A ( self : List[str] ): UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Any = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :List[Any] = None if self.use_input_lengths: UpperCamelCase :Dict = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase :str = None if self.use_token_type_ids: UpperCamelCase :int = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase :Optional[int] = None UpperCamelCase :int = None UpperCamelCase :List[Any] = None if self.use_labels: UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :List[str] = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase :List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _A ( self : List[Any] ): return 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 , ) def _A ( self : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : int , ): UpperCamelCase :Tuple = FlaubertModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :int = model(__lowerCamelCase , lengths=__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :List[Any] = model(__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , ): UpperCamelCase :Any = FlaubertWithLMHeadModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Dict = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Any = FlaubertForQuestionAnsweringSimple(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) 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 _A ( self : str , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : str , ): UpperCamelCase :str = FlaubertForQuestionAnswering(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :Optional[int] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , p_mask=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , ) ((UpperCamelCase) , ) :int = result_with_labels.to_tuple() UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) ((UpperCamelCase) , ) :List[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , ): UpperCamelCase :Optional[int] = FlaubertForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Tuple = model(__lowerCamelCase ) UpperCamelCase :List[str] = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A ( self : Any , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Dict = self.num_labels UpperCamelCase :Tuple = FlaubertForTokenClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Union[str, Any] = self.num_choices UpperCamelCase :List[Any] = FlaubertForMultipleChoice(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A ( self : str ): UpperCamelCase :List[str] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :List[Any] = config_and_inputs UpperCamelCase :Union[str, Any] = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[int] = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _A ( self : int , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ): 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 _A ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ): UpperCamelCase :Tuple = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": UpperCamelCase :Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) UpperCamelCase :List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def _A ( self : str ): UpperCamelCase :List[Any] = FlaubertModelTester(self ) UpperCamelCase :Any = ConfigTester(self , config_class=__lowerCamelCase , emb_dim=37 ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__lowerCamelCase ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__lowerCamelCase ) def _A ( self : int ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__lowerCamelCase ) @slow def _A ( self : Any ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Optional[int] = FlaubertModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @slow @require_torch_gpu def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = model_class(config=__lowerCamelCase ) UpperCamelCase :str = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :str = torch.jit.trace( __lowerCamelCase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__lowerCamelCase , os.path.join(__lowerCamelCase , """traced_model.pt""" ) ) UpperCamelCase :int = torch.jit.load(os.path.join(__lowerCamelCase , """traced_model.pt""" ) , map_location=__lowerCamelCase ) loaded(inputs_dict["""input_ids"""].to(__lowerCamelCase ) , inputs_dict["""attention_mask"""].to(__lowerCamelCase ) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) UpperCamelCase :Optional[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): UpperCamelCase :Tuple = model(__lowerCamelCase )[0] UpperCamelCase :Union[str, Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :int = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
38
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : str = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """layoutlmv3""" def __init__( self : List[Any] , __lowerCamelCase : Optional[Any]=50_265 , __lowerCamelCase : Dict=768 , __lowerCamelCase : Any=12 , __lowerCamelCase : int=12 , __lowerCamelCase : str=3_072 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=512 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Union[str, Any]=0.02 , __lowerCamelCase : Union[str, Any]=1E-5 , __lowerCamelCase : Any=1 , __lowerCamelCase : Optional[int]=0 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Dict=1_024 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=128 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : str=32 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=64 , __lowerCamelCase : List[str]=256 , __lowerCamelCase : Dict=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Tuple=224 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Dict=16 , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : Optional[Any] , ): super().__init__( 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 , initializer_range=__lowerCamelCase , layer_norm_eps=__lowerCamelCase , pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :int = max_ad_position_embeddings UpperCamelCase :Tuple = coordinate_size UpperCamelCase :List[Any] = shape_size UpperCamelCase :Union[str, Any] = has_relative_attention_bias UpperCamelCase :Any = rel_pos_bins UpperCamelCase :Optional[Any] = max_rel_pos UpperCamelCase :str = has_spatial_attention_bias UpperCamelCase :Tuple = rel_ad_pos_bins UpperCamelCase :Optional[int] = max_rel_ad_pos UpperCamelCase :Tuple = text_embed UpperCamelCase :str = visual_embed UpperCamelCase :Optional[Any] = input_size UpperCamelCase :str = num_channels UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[Any] = classifier_dropout class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = version.parse("""1.12""" ) @property def _A ( self : Optional[int] ): # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def _A ( self : str ): return 1E-5 @property def _A ( self : Dict ): return 12 def _A ( self : Dict , __lowerCamelCase : "ProcessorMixin" , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 40 , __lowerCamelCase : int = 40 , ): setattr(processor.image_processor , """apply_ocr""" , __lowerCamelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase :Optional[Any] = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase :Optional[int] = processor.tokenizer.num_special_tokens_to_add(__lowerCamelCase ) UpperCamelCase :int = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase :Any = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase :Optional[Any] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase :List[str] = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = dict( processor( __lowerCamelCase , text=__lowerCamelCase , boxes=__lowerCamelCase , return_tensors=__lowerCamelCase , ) ) return inputs
38
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """openai/whisper-base""" snake_case__ : Optional[int] = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) snake_case__ : Any = """transcriber""" snake_case__ : Optional[int] = WhisperProcessor snake_case__ : str = WhisperForConditionalGeneration snake_case__ : Optional[Any] = ["""audio"""] snake_case__ : Any = ["""text"""] def _A ( self : str , __lowerCamelCase : Dict ): return self.pre_processor(__lowerCamelCase , return_tensors="""pt""" ).input_features def _A ( self : Dict , __lowerCamelCase : List[Any] ): return self.model.generate(inputs=__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : Optional[Any] ): return self.pre_processor.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase )[0]
38
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } UpperCAmelCase_ : Optional[Any] = { '''vocab_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'''}, '''merges_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'''}, '''tokenizer_config_file''': { '''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json''' }, } UpperCAmelCase_ : Optional[int] = {'''facebook/blenderbot-3B''': 1_28} class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[Any] = VOCAB_FILES_NAMES snake_case__ : List[str] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Dict = ["""input_ids""", """attention_mask"""] snake_case__ : Union[str, Any] = BlenderbotTokenizer def __init__( self : Union[str, Any] , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : int="replace" , __lowerCamelCase : Optional[Any]="<s>" , __lowerCamelCase : List[Any]="</s>" , __lowerCamelCase : Dict="</s>" , __lowerCamelCase : List[str]="<s>" , __lowerCamelCase : int="<unk>" , __lowerCamelCase : Union[str, Any]="<pad>" , __lowerCamelCase : List[Any]="<mask>" , __lowerCamelCase : Dict=False , __lowerCamelCase : Dict=True , **__lowerCamelCase : Dict , ): super().__init__( __lowerCamelCase , __lowerCamelCase , tokenizer_file=__lowerCamelCase , errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , unk_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __lowerCamelCase ) != add_prefix_space: UpperCamelCase :Tuple = getattr(__lowerCamelCase , pre_tok_state.pop("""type""" ) ) UpperCamelCase :List[str] = add_prefix_space UpperCamelCase :Optional[int] = pre_tok_class(**__lowerCamelCase ) UpperCamelCase :Any = add_prefix_space UpperCamelCase :int = """post_processor""" UpperCamelCase :str = getattr(self.backend_tokenizer , __lowerCamelCase , __lowerCamelCase ) if tokenizer_component_instance: UpperCamelCase :str = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: UpperCamelCase :Tuple = tuple(state["""sep"""] ) if "cls" in state: UpperCamelCase :int = tuple(state["""cls"""] ) UpperCamelCase :List[Any] = False if state.get("""add_prefix_space""" , __lowerCamelCase ) != add_prefix_space: UpperCamelCase :int = add_prefix_space UpperCamelCase :Dict = True if state.get("""trim_offsets""" , __lowerCamelCase ) != trim_offsets: UpperCamelCase :Optional[Any] = trim_offsets UpperCamelCase :Union[str, Any] = True if changes_to_apply: UpperCamelCase :str = getattr(__lowerCamelCase , state.pop("""type""" ) ) UpperCamelCase :Any = component_class(**__lowerCamelCase ) setattr(self.backend_tokenizer , __lowerCamelCase , __lowerCamelCase ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def _A ( self : Union[str, Any] ): if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _A ( self : str , __lowerCamelCase : int ): UpperCamelCase :int = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else value UpperCamelCase :str = value def _A ( self : Union[str, Any] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : List[Any] ): UpperCamelCase :int = kwargs.get("""is_split_into_words""" , __lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : Tuple , *__lowerCamelCase : Any , **__lowerCamelCase : str ): UpperCamelCase :Tuple = kwargs.get("""is_split_into_words""" , __lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : str , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): UpperCamelCase :List[Any] = self._tokenizer.model.save(__lowerCamelCase , name=__lowerCamelCase ) return tuple(__lowerCamelCase ) def _A ( self : Optional[int] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): UpperCamelCase :Optional[Any] = [self.sep_token_id] UpperCamelCase :Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _A ( self : List[Any] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): return token_ids_a + [self.eos_token_id] def _A ( self : Union[str, Any] , __lowerCamelCase : "Conversation" ): UpperCamelCase :Optional[int] = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(""" """ + text ) else: # Generated responses should contain them already. inputs.append(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = """ """.join(__lowerCamelCase ) UpperCamelCase :Tuple = self.encode(__lowerCamelCase ) if len(__lowerCamelCase ) > self.model_max_length: UpperCamelCase :List[str] = input_ids[-self.model_max_length :] logger.warning(F"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens.""" ) return input_ids
38
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=_a ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) snake_case__ : ClassVar[Features] = Features({"""audio""": Audio()} ) snake_case__ : ClassVar[Features] = Features({"""transcription""": Value("""string""" )} ) snake_case__ : str = "audio" snake_case__ : str = "transcription" def _A ( self : List[str] , __lowerCamelCase : Dict ): if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) UpperCamelCase :int = copy.deepcopy(self ) UpperCamelCase :Any = self.input_schema.copy() UpperCamelCase :List[str] = features[self.audio_column] UpperCamelCase :List[Any] = input_schema return task_template @property def _A ( self : Optional[int] ): return {self.audio_column: "audio", self.transcription_column: "transcription"}
38
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str]=13 , __lowerCamelCase : List[Any]=10 , __lowerCamelCase : str=3 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : int=32 , __lowerCamelCase : Any=5 , __lowerCamelCase : Union[str, Any]=4 , __lowerCamelCase : Optional[int]=37 , __lowerCamelCase : int="gelu" , __lowerCamelCase : int=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Union[str, Any]=10 , __lowerCamelCase : Tuple=0.02 , __lowerCamelCase : Tuple="divided_space_time" , __lowerCamelCase : Union[str, Any]=None , ): UpperCamelCase :Union[str, Any] = parent UpperCamelCase :List[str] = batch_size UpperCamelCase :Any = image_size UpperCamelCase :Optional[Any] = num_channels UpperCamelCase :int = patch_size UpperCamelCase :List[Any] = num_frames UpperCamelCase :Optional[Any] = is_training UpperCamelCase :Tuple = use_labels UpperCamelCase :Optional[int] = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :Union[str, Any] = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :List[Any] = hidden_act UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :str = attention_probs_dropout_prob UpperCamelCase :List[Any] = attention_type UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :Dict = scope UpperCamelCase :List[Any] = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token UpperCamelCase :List[str] = (image_size // patch_size) ** 2 UpperCamelCase :Any = (num_frames) * self.num_patches_per_frame + 1 def _A ( self : List[Any] ): UpperCamelCase :Tuple = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :List[str] = None if self.use_labels: UpperCamelCase :Dict = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase :Optional[int] = self.get_config() return config, pixel_values, labels def _A ( self : Optional[Any] ): UpperCamelCase :Optional[int] = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) UpperCamelCase :Any = self.num_labels return config def _A ( self : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict ): UpperCamelCase :str = TimesformerModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Tuple = TimesformerForVideoClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Dict = model(__lowerCamelCase ) # verify the logits shape UpperCamelCase :List[str] = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowerCamelCase ) def _A ( self : int ): UpperCamelCase :Dict = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[int] = config_and_inputs UpperCamelCase :Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[Any] = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ : List[str] = ( {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ : Union[str, Any] = False snake_case__ : Tuple = False snake_case__ : Optional[Any] = False snake_case__ : Optional[int] = False def _A ( self : Dict ): UpperCamelCase :int = TimesformerModelTester(self ) UpperCamelCase :Union[str, Any] = ConfigTester( self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _A ( self : Any , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any=False ): UpperCamelCase :List[Any] = copy.deepcopy(__lowerCamelCase ) if return_labels: if model_class in get_values(__lowerCamelCase ): UpperCamelCase :Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def _A ( self : Dict ): self.config_tester.run_common_tests() @unittest.skip(reason="""TimeSformer does not use inputs_embeds""" ) def _A ( self : List[str] ): pass def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Tuple = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase , nn.Linear ) ) def _A ( self : List[Any] ): UpperCamelCase , UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Optional[Any] = model_class(__lowerCamelCase ) UpperCamelCase :Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :int = [*signature.parameters.keys()] UpperCamelCase :int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _A ( self : str ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _A ( self : int ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowerCamelCase ) @slow def _A ( self : str ): for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Any = TimesformerModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def _A ( self : List[Any] ): if not self.has_attentions: pass else: UpperCamelCase , UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[int] = True for model_class in self.all_model_classes: UpperCamelCase :str = self.model_tester.seq_length UpperCamelCase :Optional[int] = self.model_tester.num_frames UpperCamelCase :Union[str, Any] = True UpperCamelCase :Optional[int] = False UpperCamelCase :List[str] = True UpperCamelCase :str = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) UpperCamelCase :str = outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCamelCase :Dict = True UpperCamelCase :Union[str, Any] = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :int = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) UpperCamelCase :Union[str, Any] = outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) UpperCamelCase :Dict = len(__lowerCamelCase ) # Check attention is always last and order is fine UpperCamelCase :Union[str, Any] = True UpperCamelCase :int = True UpperCamelCase :Optional[int] = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + 1 , len(__lowerCamelCase ) ) UpperCamelCase :str = outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def _A ( self : Tuple ): def check_hidden_states_output(__lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] ): UpperCamelCase :int = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :Any = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) UpperCamelCase :Optional[Any] = outputs.hidden_states UpperCamelCase :Tuple = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) UpperCamelCase :Tuple = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Any = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase :Union[str, Any] = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> List[Any]: """simple docstring""" UpperCamelCase :Dict = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""" , filename="""eating_spaghetti.npy""" , repo_type="""dataset""" ) UpperCamelCase :Optional[int] = np.load(__magic_name__ ) return list(__magic_name__ ) @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def _A ( self : Tuple ): # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def _A ( self : Union[str, Any] ): UpperCamelCase :int = TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400""" ).to( __lowerCamelCase ) UpperCamelCase :Dict = self.default_image_processor UpperCamelCase :int = prepare_video() UpperCamelCase :Any = image_processor(video[:8] , return_tensors="""pt""" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__lowerCamelCase ) # verify the logits UpperCamelCase :Tuple = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) UpperCamelCase :str = torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) )
38
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
38
1
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[Any] = TransfoXLTokenizer snake_case__ : List[Any] = False snake_case__ : Tuple = False def _A ( self : str ): super().setUp() UpperCamelCase :Dict = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _A ( self : List[str] , **__lowerCamelCase : Any ): UpperCamelCase :Any = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : int ): UpperCamelCase :List[Any] = """<unk> UNwanted , running""" UpperCamelCase :int = """<unk> unwanted, running""" return input_text, output_text def _A ( self : Tuple ): UpperCamelCase :List[str] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__lowerCamelCase ) UpperCamelCase :Any = tokenizer.tokenize("""<unk> UNwanted , running""" ) self.assertListEqual(__lowerCamelCase , ["""<unk>""", """unwanted""", """,""", """running"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [0, 4, 8, 7] ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _A ( self : Tuple ): UpperCamelCase :Any = TransfoXLTokenizer(lower_case=__lowerCamelCase ) UpperCamelCase :Optional[int] = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" UpperCamelCase :Optional[int] = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(__lowerCamelCase ) , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = len(__lowerCamelCase ) tokenizer.add_tokens(["""new1""", """new2"""] ) tokenizer.move_added_token("""new1""" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , """new1""" )
38
import re import string import numpy as np import datasets UpperCAmelCase_ : Dict = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' UpperCAmelCase_ : Any = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' UpperCAmelCase_ : Tuple = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def _A ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : int=False , __lowerCamelCase : Optional[int]=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase :str = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in predictions] ) UpperCamelCase :Tuple = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in references] ) else: UpperCamelCase :Any = np.asarray(__lowerCamelCase ) UpperCamelCase :str = np.asarray(__lowerCamelCase ) if ignore_case: UpperCamelCase :Tuple = np.char.lower(__lowerCamelCase ) UpperCamelCase :Any = np.char.lower(__lowerCamelCase ) if ignore_punctuation: UpperCamelCase :Optional[int] = string.punctuation.maketrans("""""" , """""" , string.punctuation ) UpperCamelCase :Optional[Any] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :List[str] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) if ignore_numbers: UpperCamelCase :Tuple = string.digits.maketrans("""""" , """""" , string.digits ) UpperCamelCase :Dict = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :Tuple = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :int = predictions == references return {"exact_match": np.mean(__lowerCamelCase ) * 100}
38
1
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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Union[str, Any] ): UpperCamelCase :Union[str, Any] = """ylacombe/bark-small""" UpperCamelCase :List[str] = tempfile.mkdtemp() UpperCamelCase :List[Any] = """en_speaker_1""" UpperCamelCase :int = """This is a test string""" UpperCamelCase :int = """speaker_embeddings_path.json""" UpperCamelCase :Optional[Any] = """speaker_embeddings""" def _A ( self : int , **__lowerCamelCase : Any ): return AutoTokenizer.from_pretrained(self.checkpoint , **__lowerCamelCase ) def _A ( self : Dict ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.get_tokenizer() UpperCamelCase :str = BarkProcessor(tokenizer=__lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase :Union[str, Any] = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def _A ( self : int ): UpperCamelCase :Optional[int] = 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 :Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCamelCase :Tuple = 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 _A ( self : Tuple ): UpperCamelCase :Optional[int] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) UpperCamelCase :Any = 35 UpperCamelCase :Optional[int] = 2 UpperCamelCase :Tuple = 8 UpperCamelCase :Optional[Any] = { """semantic_prompt""": np.ones(__lowerCamelCase ), """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 :List[Any] = processor(text=self.input_string , voice_preset=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file UpperCamelCase :List[Any] = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(__lowerCamelCase , **__lowerCamelCase ) UpperCamelCase :Tuple = processor(text=self.input_string , voice_preset=__lowerCamelCase ) UpperCamelCase :Dict = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub UpperCamelCase :List[Any] = processor(text=self.input_string , voice_preset=self.voice_preset ) def _A ( self : List[str] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = BarkProcessor(tokenizer=__lowerCamelCase ) UpperCamelCase :Tuple = processor(text=self.input_string ) UpperCamelCase :Tuple = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
38
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : str = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """layoutlmv3""" def __init__( self : List[Any] , __lowerCamelCase : Optional[Any]=50_265 , __lowerCamelCase : Dict=768 , __lowerCamelCase : Any=12 , __lowerCamelCase : int=12 , __lowerCamelCase : str=3_072 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=512 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Union[str, Any]=0.02 , __lowerCamelCase : Union[str, Any]=1E-5 , __lowerCamelCase : Any=1 , __lowerCamelCase : Optional[int]=0 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Dict=1_024 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=128 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : str=32 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=64 , __lowerCamelCase : List[str]=256 , __lowerCamelCase : Dict=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Tuple=224 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Dict=16 , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : Optional[Any] , ): super().__init__( 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 , initializer_range=__lowerCamelCase , layer_norm_eps=__lowerCamelCase , pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :int = max_ad_position_embeddings UpperCamelCase :Tuple = coordinate_size UpperCamelCase :List[Any] = shape_size UpperCamelCase :Union[str, Any] = has_relative_attention_bias UpperCamelCase :Any = rel_pos_bins UpperCamelCase :Optional[Any] = max_rel_pos UpperCamelCase :str = has_spatial_attention_bias UpperCamelCase :Tuple = rel_ad_pos_bins UpperCamelCase :Optional[int] = max_rel_ad_pos UpperCamelCase :Tuple = text_embed UpperCamelCase :str = visual_embed UpperCamelCase :Optional[Any] = input_size UpperCamelCase :str = num_channels UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[Any] = classifier_dropout class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = version.parse("""1.12""" ) @property def _A ( self : Optional[int] ): # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def _A ( self : str ): return 1E-5 @property def _A ( self : Dict ): return 12 def _A ( self : Dict , __lowerCamelCase : "ProcessorMixin" , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 40 , __lowerCamelCase : int = 40 , ): setattr(processor.image_processor , """apply_ocr""" , __lowerCamelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase :Optional[Any] = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase :Optional[int] = processor.tokenizer.num_special_tokens_to_add(__lowerCamelCase ) UpperCamelCase :int = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase :Any = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase :Optional[Any] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase :List[str] = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = dict( processor( __lowerCamelCase , text=__lowerCamelCase , boxes=__lowerCamelCase , return_tensors=__lowerCamelCase , ) ) return inputs
38
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=_a ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = field(default="""audio-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) snake_case__ : ClassVar[Features] = Features({"""audio""": Audio()} ) snake_case__ : ClassVar[Features] = Features({"""labels""": ClassLabel} ) snake_case__ : str = "audio" snake_case__ : str = "labels" def _A ( self : Optional[int] , __lowerCamelCase : List[Any] ): if self.label_column not in features: raise ValueError(F"""Column {self.label_column} is not present in features.""" ) if not isinstance(features[self.label_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.label_column} is not a ClassLabel.""" ) UpperCamelCase :Optional[int] = copy.deepcopy(self ) UpperCamelCase :str = self.label_schema.copy() UpperCamelCase :List[Any] = features[self.label_column] UpperCamelCase :Tuple = label_schema return task_template @property def _A ( self : str ): return { self.audio_column: "audio", self.label_column: "labels", }
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Any = StableDiffusionXLImgaImgPipeline snake_case__ : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} snake_case__ : Tuple = PipelineTesterMixin.required_optional_params - {"""latents"""} snake_case__ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case__ : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS snake_case__ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=__lowerCamelCase , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) UpperCamelCase :Tuple = EulerDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCamelCase :Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=32 , ) UpperCamelCase :Any = CLIPTextModel(__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTextModelWithProjection(__lowerCamelCase ) UpperCamelCase :int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _A ( self : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any]=0 ): UpperCamelCase :Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) UpperCamelCase :List[str] = image / 2 + 0.5 if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :Any = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :List[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def _A ( self : str ): UpperCamelCase :List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :Optional[Any] = self.get_dummy_components() UpperCamelCase :List[Any] = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :Any = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = sd_pipe(**__lowerCamelCase ).images UpperCamelCase :Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :List[Any] = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : Dict ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _A ( self : Optional[Any] ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _A ( self : Union[str, Any] ): pass def _A ( self : Optional[int] ): UpperCamelCase :Union[str, Any] = self.get_dummy_components() UpperCamelCase :Dict = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :List[Any] = sd_pipe.to(__lowerCamelCase ) UpperCamelCase :List[str] = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) # forward without prompt embeds UpperCamelCase :List[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :int = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = negative_prompt UpperCamelCase :Union[str, Any] = 3 * [inputs["""prompt"""]] UpperCamelCase :Dict = sd_pipe(**__lowerCamelCase ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = 3 * [inputs.pop("""prompt""" )] ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = sd_pipe.encode_prompt(__lowerCamelCase , negative_prompt=__lowerCamelCase ) UpperCamelCase :Dict = sd_pipe( **__lowerCamelCase , prompt_embeds=__lowerCamelCase , negative_prompt_embeds=__lowerCamelCase , pooled_prompt_embeds=__lowerCamelCase , negative_pooled_prompt_embeds=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Tuple ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict="cpu" , __lowerCamelCase : List[Any]=torch.floataa , __lowerCamelCase : Tuple=0 ): UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = np.random.RandomState(__lowerCamelCase ).standard_normal((1, 4, 64, 64) ) UpperCamelCase :Dict = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase , dtype=__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _A ( self : Optional[Any] ): UpperCamelCase :Any = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = pipe(**__lowerCamelCase ).images UpperCamelCase :Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCamelCase :Union[str, Any] = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
38
1
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class _SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Any=13 , __lowerCamelCase : Tuple=7 , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : str=True , __lowerCamelCase : Any=True , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : Any=2 , __lowerCamelCase : int=4 , __lowerCamelCase : List[str]=37 , __lowerCamelCase : Optional[int]="gelu" , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : Optional[int]=512 , __lowerCamelCase : Union[str, Any]=16 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Optional[Any]=False , __lowerCamelCase : Tuple=True , __lowerCamelCase : Any="None" , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Any=None , ): UpperCamelCase :List[Any] = parent UpperCamelCase :Tuple = batch_size UpperCamelCase :Union[str, Any] = seq_length UpperCamelCase :Dict = is_training UpperCamelCase :Dict = use_input_mask UpperCamelCase :Union[str, Any] = use_token_type_ids UpperCamelCase :Any = use_labels UpperCamelCase :int = vocab_size UpperCamelCase :Tuple = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :List[str] = intermediate_size UpperCamelCase :List[Any] = hidden_act UpperCamelCase :Any = hidden_dropout_prob UpperCamelCase :str = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = max_position_embeddings UpperCamelCase :Any = type_vocab_size UpperCamelCase :Tuple = type_sequence_label_size UpperCamelCase :str = initializer_range UpperCamelCase :Tuple = num_labels UpperCamelCase :int = num_choices UpperCamelCase :Optional[int] = relative_attention UpperCamelCase :List[Any] = position_biased_input UpperCamelCase :Optional[Any] = pos_att_type UpperCamelCase :Dict = scope def _A ( self : Dict ): UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Optional[int] = None if self.use_input_mask: UpperCamelCase :Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :List[Any] = None if self.use_token_type_ids: UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase :Dict = None UpperCamelCase :Dict = None UpperCamelCase :Any = None if self.use_labels: UpperCamelCase :str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :Tuple = DebertaVaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=__lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _A ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] ): UpperCamelCase :Optional[int] = TFDebertaVaModel(config=__lowerCamelCase ) UpperCamelCase :List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :Optional[int] = [input_ids, input_mask] UpperCamelCase :str = model(__lowerCamelCase ) UpperCamelCase :Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : Dict ): UpperCamelCase :Optional[Any] = TFDebertaVaForMaskedLM(config=__lowerCamelCase ) UpperCamelCase :Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : Dict ): UpperCamelCase :Optional[Any] = self.num_labels UpperCamelCase :Optional[int] = TFDebertaVaForSequenceClassification(config=__lowerCamelCase ) UpperCamelCase :Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase :Tuple = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] ): UpperCamelCase :int = self.num_labels UpperCamelCase :Optional[Any] = TFDebertaVaForTokenClassification(config=__lowerCamelCase ) UpperCamelCase :Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase :int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Dict ): UpperCamelCase :Optional[Any] = TFDebertaVaForQuestionAnswering(config=__lowerCamelCase ) UpperCamelCase :Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase :Dict = model(__lowerCamelCase ) 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 _A ( self : Any ): UpperCamelCase :List[Any] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :str = config_and_inputs UpperCamelCase :Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : List[str] = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) snake_case__ : Optional[Any] = ( { """feature-extraction""": TFDebertaVaModel, """fill-mask""": TFDebertaVaForMaskedLM, """question-answering""": TFDebertaVaForQuestionAnswering, """text-classification""": TFDebertaVaForSequenceClassification, """token-classification""": TFDebertaVaForTokenClassification, """zero-shot""": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) snake_case__ : Any = False snake_case__ : Union[str, Any] = False def _A ( self : Any ): UpperCamelCase :Tuple = TFDebertaVaModelTester(self ) UpperCamelCase :Optional[int] = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=37 ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : str ): UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) @slow def _A ( self : Tuple ): UpperCamelCase :Optional[int] = TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" ) self.assertIsNotNone(__lowerCamelCase ) @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @unittest.skip(reason="""Model not available yet""" ) def _A ( self : Union[str, Any] ): pass @slow def _A ( self : Optional[Any] ): UpperCamelCase :Dict = TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" ) UpperCamelCase :Any = tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) UpperCamelCase :Optional[Any] = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) UpperCamelCase :Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] UpperCamelCase :Tuple = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , __lowerCamelCase , atol=1E-4 )
38
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : int = { '''CarlCochet/trajectory-transformer-halfcheetah-medium-v2''': ( '''https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json''' ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """trajectory_transformer""" snake_case__ : Optional[Any] = ["""past_key_values"""] snake_case__ : Tuple = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Union[str, Any] , __lowerCamelCase : Any=100 , __lowerCamelCase : str=5 , __lowerCamelCase : str=1 , __lowerCamelCase : Optional[int]=1 , __lowerCamelCase : int=249 , __lowerCamelCase : str=6 , __lowerCamelCase : Dict=17 , __lowerCamelCase : Optional[Any]=25 , __lowerCamelCase : List[str]=4 , __lowerCamelCase : str=4 , __lowerCamelCase : Tuple=128 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : int=0.0006 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Any=1E-12 , __lowerCamelCase : int=1 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Tuple=1 , __lowerCamelCase : int=50_256 , __lowerCamelCase : Union[str, Any]=50_256 , **__lowerCamelCase : Dict , ): UpperCamelCase :Dict = vocab_size UpperCamelCase :int = action_weight UpperCamelCase :Tuple = reward_weight UpperCamelCase :str = value_weight UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :Tuple = block_size UpperCamelCase :Optional[int] = action_dim UpperCamelCase :int = observation_dim UpperCamelCase :List[str] = transition_dim UpperCamelCase :List[Any] = learning_rate UpperCamelCase :Optional[Any] = n_layer UpperCamelCase :Any = n_head UpperCamelCase :List[str] = n_embd UpperCamelCase :Any = embd_pdrop UpperCamelCase :str = attn_pdrop UpperCamelCase :Union[str, Any] = resid_pdrop UpperCamelCase :Optional[Any] = initializer_range UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Optional[int] = kaiming_initializer_range UpperCamelCase :Tuple = use_cache super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int , __magic_name__ : int ) -> float: """simple docstring""" UpperCamelCase :Tuple = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
38
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 3 ) -> qiskit.result.counts.Counts: """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): raise TypeError("""number of qubits must be a integer.""" ) if number_of_qubits <= 0: raise ValueError("""number of qubits must be > 0.""" ) if math.floor(__magic_name__ ) != number_of_qubits: raise ValueError("""number of qubits must be exact integer.""" ) if number_of_qubits > 10: raise ValueError("""number of qubits too large to simulate(>10).""" ) UpperCamelCase :int = QuantumRegister(__magic_name__ , """qr""" ) UpperCamelCase :str = ClassicalRegister(__magic_name__ , """cr""" ) UpperCamelCase :str = QuantumCircuit(__magic_name__ , __magic_name__ ) UpperCamelCase :List[Any] = number_of_qubits for i in range(__magic_name__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(__magic_name__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , __magic_name__ , __magic_name__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(__magic_name__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(__magic_name__ , __magic_name__ ) # simulate with 10000 shots UpperCamelCase :str = Aer.get_backend("""qasm_simulator""" ) UpperCamelCase :Dict = execute(__magic_name__ , __magic_name__ , shots=1_0000 ) return job.result().get_counts(__magic_name__ ) if __name__ == "__main__": print( F'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
38
1
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] ) -> Tuple: """simple docstring""" return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :Tuple = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=__magic_name__ ) UpperCamelCase :Union[str, Any] = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(__magic_name__ ) EnvironmentCommand.register_subcommand(__magic_name__ ) TestCommand.register_subcommand(__magic_name__ ) RunBeamCommand.register_subcommand(__magic_name__ ) DummyDataCommand.register_subcommand(__magic_name__ ) # Parse args UpperCamelCase , UpperCamelCase :List[str] = parser.parse_known_args() if not hasattr(__magic_name__ , """func""" ): parser.print_help() exit(1 ) UpperCamelCase :Tuple = parse_unknown_args(__magic_name__ ) # Run UpperCamelCase :str = args.func(__magic_name__ , **__magic_name__ ) service.run() if __name__ == "__main__": main()
38
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer UpperCAmelCase_ : Optional[Any] = ['''bert-base-uncased''', '''bert-base-cased'''] UpperCAmelCase_ : List[str] = '''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class _SCREAMING_SNAKE_CASE ( tf.keras.Model ): def __init__( self : List[str] , __lowerCamelCase : Union[str, Any] ): super().__init__() UpperCamelCase :Any = tokenizer UpperCamelCase :List[str] = AutoConfig.from_pretrained(__lowerCamelCase ) UpperCamelCase :List[str] = TFAutoModel.from_config(__lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : str ): UpperCamelCase :str = self.tokenizer(__lowerCamelCase ) UpperCamelCase :Any = self.bert(**__lowerCamelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Dict ): super().setUp() UpperCamelCase :int = [ BertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase :Any = [TFBertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(__lowerCamelCase , use_fast_bert_tokenizer=__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase :Any = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] UpperCamelCase :Union[str, Any] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _A ( self : Optional[int] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tokenizer(__lowerCamelCase , return_tensors="""tf""" , padding="""longest""" ) UpperCamelCase :str = tf_tokenizer(__lowerCamelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _A ( self : Dict ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :str = tf_tokenizer(self.paired_sentences ) UpperCamelCase :Any = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _A ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[Any] = tf.function(__lowerCamelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tf.constant(__lowerCamelCase ) UpperCamelCase :List[str] = compiled_tokenizer(__lowerCamelCase ) UpperCamelCase :Optional[Any] = tf_tokenizer(__lowerCamelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _A ( self : Tuple ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[str] = ModelToSave(tokenizer=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase :List[str] = Path(__lowerCamelCase ) / """saved.model""" model.save(__lowerCamelCase ) UpperCamelCase :List[Any] = tf.keras.models.load_model(__lowerCamelCase ) UpperCamelCase :Dict = loaded_model(__lowerCamelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
38
1
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) UpperCAmelCase_ : int = '''bert-base-cased''' UpperCAmelCase_ : Any = '''fp16''' UpperCAmelCase_ : str = '''bf16''' UpperCAmelCase_ : int = [FPaa, BFaa] @require_fsdp @require_cuda class _SCREAMING_SNAKE_CASE ( _a ): def _A ( self : List[Any] ): super().setUp() UpperCamelCase :Tuple = dict( ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , ) def _A ( self : List[str] ): from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__lowerCamelCase ): UpperCamelCase :Union[str, Any] = self.dist_env.copy() UpperCamelCase :List[Any] = F"""{i + 1}""" UpperCamelCase :List[Any] = strategy with mockenv_context(**__lowerCamelCase ): UpperCamelCase :List[str] = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def _A ( self : str ): from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__lowerCamelCase ): UpperCamelCase :str = self.dist_env.copy() UpperCamelCase :List[Any] = prefetch_policy with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Optional[int] = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def _A ( self : Union[str, Any] ): from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__lowerCamelCase ): UpperCamelCase :Any = self.dist_env.copy() UpperCamelCase :Tuple = state_dict_type with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Dict = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def _A ( self : Tuple ): UpperCamelCase :int = AutoModel.from_pretrained(__lowerCamelCase ) for policy in FSDP_AUTO_WRAP_POLICY: UpperCamelCase :Any = self.dist_env.copy() UpperCamelCase :Dict = policy if policy == "TRANSFORMER_BASED_WRAP": UpperCamelCase :Any = """BertLayer""" elif policy == "SIZE_BASED_WRAP": UpperCamelCase :Optional[Any] = """2000""" with mockenv_context(**__lowerCamelCase ): UpperCamelCase :int = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) UpperCamelCase :List[Any] = self.dist_env.copy() UpperCamelCase :Optional[int] = """TRANSFORMER_BASED_WRAP""" UpperCamelCase :int = """T5Layer""" with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Any = FullyShardedDataParallelPlugin() with self.assertRaises(__lowerCamelCase ) as cm: fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) ) UpperCamelCase :List[str] = self.dist_env.copy() UpperCamelCase :str = """SIZE_BASED_WRAP""" UpperCamelCase :int = """0""" with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Optional[Any] = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def _A ( self : str ): from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: UpperCamelCase :List[Any] = self.dist_env.copy() UpperCamelCase :Union[str, Any] = mp_dtype with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Dict = Accelerator() if mp_dtype == "fp16": UpperCamelCase :int = torch.floataa elif mp_dtype == "bf16": UpperCamelCase :Union[str, Any] = torch.bfloataa UpperCamelCase :Dict = MixedPrecision(param_dtype=__lowerCamelCase , reduce_dtype=__lowerCamelCase , buffer_dtype=__lowerCamelCase ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __lowerCamelCase ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , __lowerCamelCase ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__lowerCamelCase ) def _A ( self : Dict ): from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: UpperCamelCase :Union[str, Any] = self.dist_env.copy() UpperCamelCase :Union[str, Any] = str(__lowerCamelCase ).lower() with mockenv_context(**__lowerCamelCase ): UpperCamelCase :int = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__lowerCamelCase ) ) @require_fsdp @require_multi_gpu @slow class _SCREAMING_SNAKE_CASE ( _a ): def _A ( self : List[Any] ): super().setUp() UpperCamelCase :Optional[int] = 0.82 UpperCamelCase :Any = [ """fsdp_shard_grad_op_transformer_based_wrap""", """fsdp_full_shard_transformer_based_wrap""", ] UpperCamelCase :List[Any] = { """multi_gpu_fp16""": 3_200, """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2_000, """fsdp_full_shard_transformer_based_wrap_fp16""": 1_900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } UpperCamelCase :Optional[int] = 160 UpperCamelCase :Union[str, Any] = 160 UpperCamelCase :Tuple = inspect.getfile(accelerate.test_utils ) UpperCamelCase :str = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] ) def _A ( self : Optional[Any] ): UpperCamelCase :Optional[int] = os.path.join(self.test_scripts_folder , """test_performance.py""" ) UpperCamelCase :Any = ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""] for config in self.performance_configs: UpperCamelCase :Optional[Any] = cmd.copy() for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in config: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "fp32" in config: cmd_config.append("""--mixed_precision=no""" ) else: cmd_config.append("""--mixed_precision=fp16""" ) if "cpu_offload" in config: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--performance_lower_bound={self.performance_lower_bound}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) def _A ( self : int ): UpperCamelCase :Dict = os.path.join(self.test_scripts_folder , """test_checkpointing.py""" ) UpperCamelCase :List[str] = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp""", """--mixed_precision=fp16""", """--fsdp_transformer_layer_cls_to_wrap=BertLayer""", ] for i, strategy in enumerate(__lowerCamelCase ): UpperCamelCase :List[str] = cmd.copy() cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) if strategy != "FULL_SHARD": continue UpperCamelCase :Union[str, Any] = len(__lowerCamelCase ) for state_dict_type in FSDP_STATE_DICT_TYPE: UpperCamelCase :Dict = cmd_config[:state_dict_config_index] cmd_config.append(F"""--fsdp_state_dict_type={state_dict_type}""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", """--partial_train_epoch=1""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) UpperCamelCase :Optional[Any] = cmd_config[:-1] UpperCamelCase :int = os.path.join(self.tmpdir , """epoch_0""" ) cmd_config.extend( [ F"""--resume_from_checkpoint={resume_from_checkpoint}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" ) UpperCamelCase :Union[str, Any] = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): UpperCamelCase :List[str] = cmd.copy() if "fp16" in spec: cmd_config.extend(["""--mixed_precision=fp16"""] ) else: cmd_config.extend(["""--mixed_precision=no"""] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["""--use_fsdp"""] ) for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in spec: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "cpu_offload" in spec: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--peak_memory_upper_bound={peak_mem_upper_bound}""", F"""--n_train={self.n_train}""", F"""--n_val={self.n_val}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() )
38
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase_ : Any = '''Create a default config file for Accelerate with only a few flags set.''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int]="no" , __magic_name__ : str = default_json_config_file , __magic_name__ : bool = False ) -> str: """simple docstring""" UpperCamelCase :Any = Path(__magic_name__ ) path.parent.mkdir(parents=__magic_name__ , exist_ok=__magic_name__ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False UpperCamelCase :Dict = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) UpperCamelCase :Optional[Any] = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): UpperCamelCase :Union[str, Any] = torch.cuda.device_count() UpperCamelCase :List[Any] = num_gpus UpperCamelCase :Dict = False if num_gpus > 1: UpperCamelCase :Any = """MULTI_GPU""" else: UpperCamelCase :Any = """NO""" elif is_xpu_available() and use_xpu: UpperCamelCase :Optional[Any] = torch.xpu.device_count() UpperCamelCase :Optional[int] = num_xpus UpperCamelCase :int = False if num_xpus > 1: UpperCamelCase :Union[str, Any] = """MULTI_XPU""" else: UpperCamelCase :Union[str, Any] = """NO""" elif is_npu_available(): UpperCamelCase :List[Any] = torch.npu.device_count() UpperCamelCase :Optional[Any] = num_npus UpperCamelCase :Tuple = False if num_npus > 1: UpperCamelCase :Optional[Any] = """MULTI_NPU""" else: UpperCamelCase :List[Any] = """NO""" else: UpperCamelCase :Any = 0 UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[str] = """NO""" UpperCamelCase :int = ClusterConfig(**__magic_name__ ) config.to_json_file(__magic_name__ ) return path def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = parser.add_parser("""default""" , parents=__magic_name__ , help=__magic_name__ , formatter_class=__magic_name__ ) parser.add_argument( """--config_file""" , default=__magic_name__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=__magic_name__ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=__magic_name__ ) return parser def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
38
1
from collections.abc import Sequence from queue import Queue class _SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : str=None , __lowerCamelCase : Optional[Any]=None ): UpperCamelCase :List[Any] = start UpperCamelCase :str = end UpperCamelCase :Tuple = val UpperCamelCase :Tuple = (start + end) // 2 UpperCamelCase :str = left UpperCamelCase :Optional[int] = right def __repr__( self : List[str] ): return F"""SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})""" class _SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowerCamelCase : Sequence , __lowerCamelCase : List[Any] ): UpperCamelCase :int = collection UpperCamelCase :List[Any] = function if self.collection: UpperCamelCase :Tuple = self._build_tree(0 , len(__lowerCamelCase ) - 1 ) def _A ( self : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : int ): self._update_tree(self.root , __lowerCamelCase , __lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple ): return self._query_range(self.root , __lowerCamelCase , __lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : List[str] ): if start == end: return SegmentTreeNode(__lowerCamelCase , __lowerCamelCase , self.collection[start] ) UpperCamelCase :Dict = (start + end) // 2 UpperCamelCase :List[str] = self._build_tree(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = self._build_tree(mid + 1 , __lowerCamelCase ) return SegmentTreeNode(__lowerCamelCase , __lowerCamelCase , self.fn(left.val , right.val ) , __lowerCamelCase , __lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): if node.start == i and node.end == i: UpperCamelCase :List[Any] = val return if i <= node.mid: self._update_tree(node.left , __lowerCamelCase , __lowerCamelCase ) else: self._update_tree(node.right , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = self.fn(node.left.val , node.right.val ) def _A ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : int ): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , __lowerCamelCase , __lowerCamelCase ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , __lowerCamelCase , node.mid ) , self._query_range(node.right , node.mid + 1 , __lowerCamelCase ) , ) else: # range in right child tree return self._query_range(node.right , __lowerCamelCase , __lowerCamelCase ) def _A ( self : Optional[Any] ): if self.root is not None: UpperCamelCase :Union[str, Any] = Queue() queue.put(self.root ) while not queue.empty(): UpperCamelCase :Optional[int] = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) UpperCAmelCase_ : Optional[int] = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
38
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
1
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = { """task_specific_params""": { """summarization""": {"""length_penalty""": 1.0, """max_length""": 128, """min_length""": 12, """num_beams""": 4}, """summarization_cnn""": {"""length_penalty""": 2.0, """max_length""": 142, """min_length""": 56, """num_beams""": 4}, """summarization_xsum""": {"""length_penalty""": 1.0, """max_length""": 62, """min_length""": 11, """num_beams""": 6}, } } UpperCamelCase :Dict = { """task_specific_params.summarization.length_penalty""": 1.0, """task_specific_params.summarization.max_length""": 128, """task_specific_params.summarization.min_length""": 12, """task_specific_params.summarization.num_beams""": 4, """task_specific_params.summarization_cnn.length_penalty""": 2.0, """task_specific_params.summarization_cnn.max_length""": 142, """task_specific_params.summarization_cnn.min_length""": 56, """task_specific_params.summarization_cnn.num_beams""": 4, """task_specific_params.summarization_xsum.length_penalty""": 1.0, """task_specific_params.summarization_xsum.max_length""": 62, """task_specific_params.summarization_xsum.min_length""": 11, """task_specific_params.summarization_xsum.num_beams""": 6, } self.assertEqual(flatten_dict(__lowerCamelCase ) , __lowerCamelCase ) def _A ( self : Dict ): UpperCamelCase :List[Any] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , x.transpose() ) ) UpperCamelCase :List[Any] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def _A ( self : Optional[Any] ): UpperCamelCase :str = np.random.randn(3 , 4 ) UpperCamelCase :Optional[int] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , transpose(__lowerCamelCase ).numpy() ) ) UpperCamelCase :int = np.random.randn(3 , 4 , 5 ) UpperCamelCase :Dict = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , transpose(__lowerCamelCase , axes=(1, 2, 0) ).numpy() ) ) @require_tf def _A ( self : int ): UpperCamelCase :Any = np.random.randn(3 , 4 ) UpperCamelCase :Optional[Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , transpose(__lowerCamelCase ).numpy() ) ) UpperCamelCase :Optional[int] = np.random.randn(3 , 4 , 5 ) UpperCamelCase :Union[str, Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , transpose(__lowerCamelCase , axes=(1, 2, 0) ).numpy() ) ) @require_flax def _A ( self : int ): UpperCamelCase :List[str] = np.random.randn(3 , 4 ) UpperCamelCase :str = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , np.asarray(transpose(__lowerCamelCase ) ) ) ) UpperCamelCase :str = np.random.randn(3 , 4 , 5 ) UpperCamelCase :Optional[int] = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , np.asarray(transpose(__lowerCamelCase , axes=(1, 2, 0) ) ) ) ) def _A ( self : Union[str, Any] ): UpperCamelCase :Tuple = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , np.reshape(__lowerCamelCase , (4, 3) ) ) ) UpperCamelCase :List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , np.reshape(__lowerCamelCase , (12, 5) ) ) ) @require_torch def _A ( self : Dict ): UpperCamelCase :List[str] = np.random.randn(3 , 4 ) UpperCamelCase :List[str] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , reshape(__lowerCamelCase , (4, 3) ).numpy() ) ) UpperCamelCase :Optional[Any] = np.random.randn(3 , 4 , 5 ) UpperCamelCase :str = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , reshape(__lowerCamelCase , (12, 5) ).numpy() ) ) @require_tf def _A ( self : Dict ): UpperCamelCase :List[str] = np.random.randn(3 , 4 ) UpperCamelCase :Union[str, Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , reshape(__lowerCamelCase , (4, 3) ).numpy() ) ) UpperCamelCase :List[str] = np.random.randn(3 , 4 , 5 ) UpperCamelCase :Optional[Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , reshape(__lowerCamelCase , (12, 5) ).numpy() ) ) @require_flax def _A ( self : Any ): UpperCamelCase :int = np.random.randn(3 , 4 ) UpperCamelCase :Union[str, Any] = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , np.asarray(reshape(__lowerCamelCase , (4, 3) ) ) ) ) UpperCamelCase :int = np.random.randn(3 , 4 , 5 ) UpperCamelCase :Any = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , np.asarray(reshape(__lowerCamelCase , (12, 5) ) ) ) ) def _A ( self : Optional[int] ): UpperCamelCase :Optional[int] = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , np.squeeze(__lowerCamelCase ) ) ) UpperCamelCase :int = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , np.squeeze(__lowerCamelCase , axis=2 ) ) ) @require_torch def _A ( self : int ): UpperCamelCase :str = np.random.randn(1 , 3 , 4 ) UpperCamelCase :List[Any] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , squeeze(__lowerCamelCase ).numpy() ) ) UpperCamelCase :Any = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase :List[Any] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , squeeze(__lowerCamelCase , axis=2 ).numpy() ) ) @require_tf def _A ( self : Tuple ): UpperCamelCase :int = np.random.randn(1 , 3 , 4 ) UpperCamelCase :List[str] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , squeeze(__lowerCamelCase ).numpy() ) ) UpperCamelCase :int = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase :List[Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , squeeze(__lowerCamelCase , axis=2 ).numpy() ) ) @require_flax def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = np.random.randn(1 , 3 , 4 ) UpperCamelCase :Optional[int] = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , np.asarray(squeeze(__lowerCamelCase ) ) ) ) UpperCamelCase :Optional[int] = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase :Any = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , np.asarray(squeeze(__lowerCamelCase , axis=2 ) ) ) ) def _A ( self : List[Any] ): UpperCamelCase :int = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , np.expand_dims(__lowerCamelCase , axis=1 ) ) ) @require_torch def _A ( self : Optional[Any] ): UpperCamelCase :str = np.random.randn(3 , 4 ) UpperCamelCase :Optional[Any] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , expand_dims(__lowerCamelCase , axis=1 ).numpy() ) ) @require_tf def _A ( self : Tuple ): UpperCamelCase :str = np.random.randn(3 , 4 ) UpperCamelCase :List[str] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , expand_dims(__lowerCamelCase , axis=1 ).numpy() ) ) @require_flax def _A ( self : str ): UpperCamelCase :List[str] = np.random.randn(3 , 4 ) UpperCamelCase :List[Any] = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , np.asarray(expand_dims(__lowerCamelCase , axis=1 ) ) ) )
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, 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 _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = ShapEImgaImgPipeline snake_case__ : Optional[Any] = ["""image"""] snake_case__ : Union[str, Any] = ["""image"""] snake_case__ : Optional[Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case__ : List[str] = False @property def _A ( self : Any ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Optional[Any] ): return self.time_input_dim * 4 @property def _A ( self : Union[str, Any] ): return 8 @property def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCamelCase :Optional[int] = CLIPVisionModel(__lowerCamelCase ) return model @property def _A ( self : str ): UpperCamelCase :Optional[int] = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def _A ( self : Tuple ): torch.manual_seed(0 ) UpperCamelCase :Dict = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase :int = PriorTransformer(**__lowerCamelCase ) return model @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) UpperCamelCase :str = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase :List[str] = ShapERenderer(**__lowerCamelCase ) return model def _A ( self : str ): UpperCamelCase :int = self.dummy_prior UpperCamelCase :Any = self.dummy_image_encoder UpperCamelCase :Dict = self.dummy_image_processor UpperCamelCase :List[Any] = self.dummy_renderer UpperCamelCase :int = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__lowerCamelCase , clip_sample=__lowerCamelCase , clip_sample_range=1.0 , ) UpperCamelCase :Optional[Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def _A ( self : int , __lowerCamelCase : int , __lowerCamelCase : Any=0 ): UpperCamelCase :Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :List[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _A ( self : List[str] ): UpperCamelCase :Dict = """cpu""" UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) UpperCamelCase :Dict = output.images[0] UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase :Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : List[Any] ): # 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 : List[Any] ): UpperCamelCase :str = torch_device == """cpu""" UpperCamelCase :int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , ) def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :List[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = 1 UpperCamelCase :int = 2 UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase :str = batch_size * [inputs[key]] UpperCamelCase :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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Any ): UpperCamelCase :Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCamelCase :Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( __lowerCamelCase , generator=__lowerCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str ) -> str: """simple docstring""" return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
38
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record UpperCAmelCase_ : int = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' UpperCAmelCase_ : Optional[Any] = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' UpperCAmelCase_ : int = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any="binary" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = simple_accuracy(__magic_name__ , __magic_name__ ) UpperCamelCase :Dict = float(fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average=__magic_name__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = {} for id_pred, label in zip(__magic_name__ , __magic_name__ ): UpperCamelCase :str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCamelCase :Union[str, Any] = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase :Dict = [(pred, label)] UpperCamelCase , UpperCamelCase :Optional[int] = [], [] for question, preds_labels in question_map.items(): UpperCamelCase , UpperCamelCase :Optional[Any] = zip(*__magic_name__ ) UpperCamelCase :Optional[int] = fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average="""macro""" ) fas.append(__magic_name__ ) UpperCamelCase :int = int(sum(pred == label for pred, label in preds_labels ) == len(__magic_name__ ) ) ems.append(__magic_name__ ) UpperCamelCase :Optional[int] = float(sum(__magic_name__ ) / len(__magic_name__ ) ) UpperCamelCase :str = sum(__magic_name__ ) / len(__magic_name__ ) UpperCamelCase :Tuple = float(fa_score(y_true=__magic_name__ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : str ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _A ( self : Optional[Any] ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _A ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : str ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCamelCase :Optional[Any] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCamelCase :Tuple = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
38
1
import unittest from typing import Dict, List, Optional, Union import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BridgeTowerImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : int , __lowerCamelCase : Any , __lowerCamelCase : bool = True , __lowerCamelCase : Dict[str, int] = None , __lowerCamelCase : int = 32 , __lowerCamelCase : bool = True , __lowerCamelCase : Union[int, float] = 1 / 255 , __lowerCamelCase : bool = True , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073] , __lowerCamelCase : Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711] , __lowerCamelCase : bool = True , __lowerCamelCase : Any=7 , __lowerCamelCase : str=30 , __lowerCamelCase : Optional[Any]=400 , __lowerCamelCase : List[Any]=3 , ): UpperCamelCase :Dict = parent UpperCamelCase :Tuple = do_resize UpperCamelCase :str = size if size is not None else {"""shortest_edge""": 288} UpperCamelCase :Optional[Any] = size_divisor UpperCamelCase :str = do_rescale UpperCamelCase :Any = rescale_factor UpperCamelCase :Tuple = do_normalize UpperCamelCase :Dict = do_center_crop UpperCamelCase :List[str] = image_mean UpperCamelCase :int = image_std UpperCamelCase :Tuple = do_pad UpperCamelCase :Union[str, Any] = batch_size UpperCamelCase :int = num_channels UpperCamelCase :Optional[Any] = min_resolution UpperCamelCase :Tuple = max_resolution def _A ( self : str ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def _A ( self : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple=False ): if not batched: UpperCamelCase :str = self.size["""shortest_edge"""] UpperCamelCase :Union[str, Any] = image_inputs[0] if isinstance(__lowerCamelCase , Image.Image ): UpperCamelCase , UpperCamelCase :str = image.size else: UpperCamelCase , UpperCamelCase :Any = image.shape[1], image.shape[2] UpperCamelCase :Optional[Any] = size / min(__lowerCamelCase , __lowerCamelCase ) if h < w: UpperCamelCase , UpperCamelCase :int = size, scale * w else: UpperCamelCase , UpperCamelCase :Dict = scale * h, size UpperCamelCase :Optional[int] = int((1_333 / 800) * size ) if max(__lowerCamelCase , __lowerCamelCase ) > max_size: UpperCamelCase :Optional[Any] = max_size / max(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Tuple = newh * scale UpperCamelCase :Union[str, Any] = neww * scale UpperCamelCase , UpperCamelCase :Tuple = int(newh + 0.5 ), int(neww + 0.5 ) UpperCamelCase , UpperCamelCase :List[Any] = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: UpperCamelCase :List[Any] = [] for image in image_inputs: UpperCamelCase , UpperCamelCase :List[str] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCamelCase :Optional[Any] = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[0] )[0] UpperCamelCase :Union[str, Any] = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = BridgeTowerImageProcessor if is_vision_available() else None def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = BridgeTowerImageProcessingTester(self ) @property def _A ( self : Any ): return self.image_processor_tester.prepare_image_processor_dict() def _A ( self : str ): UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size_divisor""" ) ) def _A ( self : int ): pass def _A ( self : str ): # Initialize image processor UpperCamelCase :int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :Optional[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Optional[int] = 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 UpperCamelCase :Tuple = image_processing(__lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Optional[int] = 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 : Union[str, Any] ): # Initialize image processor UpperCamelCase :int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :Dict = 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 UpperCamelCase :Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Dict = 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 UpperCamelCase :List[str] = image_processing(__lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Optional[Any] = 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 : Dict ): # Initialize image processor UpperCamelCase :Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :Tuple = 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 UpperCamelCase :List[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Dict = 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 UpperCamelCase :List[str] = image_processing(__lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase :Any = 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, ) , )
38
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any=13 , __lowerCamelCase : Dict=3 , __lowerCamelCase : int=224 , __lowerCamelCase : Any=30 , __lowerCamelCase : Tuple=400 , __lowerCamelCase : int=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , ): UpperCamelCase :List[Any] = size if size is not None else {"""height""": 18, """width""": 18} UpperCamelCase :str = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :Dict = num_channels UpperCamelCase :str = image_size UpperCamelCase :Dict = min_resolution UpperCamelCase :str = max_resolution UpperCamelCase :Union[str, Any] = do_resize UpperCamelCase :Optional[Any] = size UpperCamelCase :Any = do_normalize UpperCamelCase :Optional[Any] = image_mean UpperCamelCase :Tuple = image_std def _A ( self : int ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : List[Any] = ViTImageProcessor if is_vision_available() else None def _A ( self : str ): UpperCamelCase :Tuple = EfficientFormerImageProcessorTester(self ) @property def _A ( self : List[str] ): return self.image_proc_tester.prepare_image_processor_dict() def _A ( self : int ): UpperCamelCase :List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) def _A ( self : Optional[int] ): pass def _A ( self : str ): # Initialize image_processor UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :List[str] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :List[Any] = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : Union[str, Any] ): # Initialize image_processor UpperCamelCase :Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase :Dict = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :Tuple = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : List[Any] ): # Initialize image_processor UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase :List[Any] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :str = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
38
1
import math UpperCAmelCase_ : List[str] = 10 UpperCAmelCase_ : Optional[Any] = 7 UpperCAmelCase_ : Optional[Any] = BALLS_PER_COLOUR * NUM_COLOURS def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 20 ) -> str: """simple docstring""" UpperCamelCase :str = math.comb(__magic_name__ , __magic_name__ ) UpperCamelCase :List[str] = math.comb(NUM_BALLS - BALLS_PER_COLOUR , __magic_name__ ) UpperCamelCase :Optional[int] = NUM_COLOURS * (1 - missing_colour / total) return f"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
38
from collections.abc import Generator from math import sin def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" if len(__magic_name__ ) != 32: raise ValueError("""Input must be of length 32""" ) UpperCamelCase :int = B"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bytes: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :Any = format(__magic_name__ , """08x""" )[-8:] UpperCamelCase :Union[str, Any] = B"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :str = B"""""" for char in message: bit_string += format(__magic_name__ , """08b""" ).encode("""utf-8""" ) UpperCamelCase :Any = format(len(__magic_name__ ) , """064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__magic_name__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> Generator[list[int], None, None]: """simple docstring""" if len(__magic_name__ ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 , len(__magic_name__ ) , 512 ): UpperCamelCase :Tuple = bit_string[pos : pos + 512] UpperCamelCase :Optional[int] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :List[str] = format(__magic_name__ , """032b""" ) UpperCamelCase :Any = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(__magic_name__ , 2 ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" return (a + b) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :Tuple = preprocess(__magic_name__ ) UpperCamelCase :List[str] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states UpperCamelCase :Union[str, Any] = 0X67_45_23_01 UpperCamelCase :Union[str, Any] = 0XEF_CD_AB_89 UpperCamelCase :List[str] = 0X98_BA_DC_FE UpperCamelCase :int = 0X10_32_54_76 UpperCamelCase :int = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__magic_name__ ): UpperCamelCase :Optional[Any] = aa UpperCamelCase :Any = ba UpperCamelCase :Tuple = ca UpperCamelCase :List[str] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f UpperCamelCase :int = d ^ (b & (c ^ d)) UpperCamelCase :Optional[int] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f UpperCamelCase :str = c ^ (d & (b ^ c)) UpperCamelCase :Union[str, Any] = (5 * i + 1) % 16 elif i <= 47: UpperCamelCase :str = b ^ c ^ d UpperCamelCase :Optional[int] = (3 * i + 5) % 16 else: UpperCamelCase :List[str] = c ^ (b | not_aa(__magic_name__ )) UpperCamelCase :int = (7 * i) % 16 UpperCamelCase :Dict = (f + a + added_consts[i] + block_words[g]) % 2**32 UpperCamelCase :Tuple = d UpperCamelCase :str = c UpperCamelCase :Tuple = b UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , left_rotate_aa(__magic_name__ , shift_amounts[i] ) ) # Add hashed chunk to running total UpperCamelCase :List[str] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :str = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :int = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
38
1
import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self : int ): UpperCamelCase :int = (0, 0) UpperCamelCase :List[str] = None UpperCamelCase :Union[str, Any] = 0 UpperCamelCase :Optional[Any] = 0 UpperCamelCase :Optional[Any] = 0 def __eq__( self : Union[str, Any] , __lowerCamelCase : int ): return self.position == cell.position def _A ( self : Optional[Any] ): print(self.position ) class _SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowerCamelCase : Any=(5, 5) ): UpperCamelCase :Tuple = np.zeros(__lowerCamelCase ) UpperCamelCase :str = world_size[0] UpperCamelCase :List[str] = world_size[1] def _A ( self : List[Any] ): print(self.w ) def _A ( self : Optional[Any] , __lowerCamelCase : str ): UpperCamelCase :str = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] UpperCamelCase :Optional[int] = cell.position[0] UpperCamelCase :Tuple = cell.position[1] UpperCamelCase :Optional[Any] = [] for n in neughbour_cord: UpperCamelCase :int = current_x + n[0] UpperCamelCase :Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: UpperCamelCase :List[str] = Cell() UpperCamelCase :str = (x, y) UpperCamelCase :int = cell neighbours.append(__lowerCamelCase ) return neighbours def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str , __magic_name__ : Optional[int] ) -> List[Any]: """simple docstring""" UpperCamelCase :List[str] = [] UpperCamelCase :List[str] = [] _open.append(__magic_name__ ) while _open: UpperCamelCase :Optional[Any] = np.argmin([n.f for n in _open] ) UpperCamelCase :Optional[Any] = _open[min_f] _closed.append(_open.pop(__magic_name__ ) ) if current == goal: break for n in world.get_neigbours(__magic_name__ ): for c in _closed: if c == n: continue UpperCamelCase :List[Any] = current.g + 1 UpperCamelCase , UpperCamelCase :Dict = n.position UpperCamelCase , UpperCamelCase :List[str] = goal.position UpperCamelCase :Any = (ya - ya) ** 2 + (xa - xa) ** 2 UpperCamelCase :Optional[int] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(__magic_name__ ) UpperCamelCase :int = [] while current.parent is not None: path.append(current.position ) UpperCamelCase :Optional[int] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": UpperCAmelCase_ : List[Any] = Gridworld() # Start position and goal UpperCAmelCase_ : List[str] = Cell() UpperCAmelCase_ : str = (0, 0) UpperCAmelCase_ : Tuple = Cell() UpperCAmelCase_ : int = (4, 4) print(F'''path from {start.position} to {goal.position}''') UpperCAmelCase_ : Tuple = astar(world, start, goal) # Just for visual reasons. for i in s: UpperCAmelCase_ : Union[str, Any] = 1 print(world.w)
38
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[Any] , __lowerCamelCase : Callable , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[dict] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : List[Any] , ): super().__init__( features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = Generator( cache_dir=__lowerCamelCase , features=__lowerCamelCase , generator=__lowerCamelCase , gen_kwargs=__lowerCamelCase , **__lowerCamelCase , ) def _A ( self : List[str] ): # Build iterable dataset if self.streaming: UpperCamelCase :Any = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: UpperCamelCase :Tuple = None UpperCamelCase :Dict = None UpperCamelCase :Dict = None UpperCamelCase :List[str] = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) UpperCamelCase :Tuple = self.builder.as_dataset( split="""train""" , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
38
1
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[Any] , __lowerCamelCase : Callable , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[dict] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : List[Any] , ): super().__init__( features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = Generator( cache_dir=__lowerCamelCase , features=__lowerCamelCase , generator=__lowerCamelCase , gen_kwargs=__lowerCamelCase , **__lowerCamelCase , ) def _A ( self : List[str] ): # Build iterable dataset if self.streaming: UpperCamelCase :Any = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: UpperCamelCase :Tuple = None UpperCamelCase :Dict = None UpperCamelCase :Dict = None UpperCamelCase :List[str] = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) UpperCamelCase :Tuple = self.builder.as_dataset( split="""train""" , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
38
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase_ : Union[str, Any] = 16 UpperCAmelCase_ : int = 32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 , __magic_name__ : str = "bert-base-cased" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = AutoTokenizer.from_pretrained(__magic_name__ ) UpperCamelCase :Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__magic_name__ : Tuple ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase :List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__magic_name__ , max_length=__magic_name__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase :List[Any] = datasets.map( __magic_name__ , batched=__magic_name__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__magic_name__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase :Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__magic_name__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__magic_name__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__magic_name__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase :List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) UpperCamelCase :List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase :Union[str, Any] = config["""lr"""] UpperCamelCase :List[str] = int(config["""num_epochs"""] ) UpperCamelCase :str = int(config["""seed"""] ) UpperCamelCase :Dict = int(config["""batch_size"""] ) UpperCamelCase :Union[str, Any] = args.model_name_or_path set_seed(__magic_name__ ) UpperCamelCase , UpperCamelCase :Dict = get_dataloaders(__magic_name__ , __magic_name__ , __magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase :List[str] = AutoModelForSequenceClassification.from_pretrained(__magic_name__ , return_dict=__magic_name__ ) # Instantiate optimizer UpperCamelCase :Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase :Optional[Any] = optimizer_cls(params=model.parameters() , lr=__magic_name__ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase :Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase :Any = 1 UpperCamelCase :Dict = (len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase :List[Any] = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=0 , num_training_steps=__magic_name__ , ) else: UpperCamelCase :Any = DummyScheduler(__magic_name__ , total_num_steps=__magic_name__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase :int = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase :Tuple = 0 # Now we train the model UpperCamelCase :Any = evaluate.load("""glue""" , """mrpc""" ) UpperCamelCase :Tuple = 0 UpperCamelCase :List[Any] = {} for epoch in range(__magic_name__ , __magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): UpperCamelCase :List[str] = model(**__magic_name__ ) UpperCamelCase :Dict = outputs.loss UpperCamelCase :Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__magic_name__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCamelCase :str = 0 for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__magic_name__ ) UpperCamelCase :List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase , UpperCamelCase :Optional[int] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__magic_name__ ) - 1: UpperCamelCase :Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) UpperCamelCase :List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __magic_name__ ) UpperCamelCase :Dict = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCamelCase :str = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :List[str] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__magic_name__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__magic_name__ , ) parser.add_argument( """--output_dir""" , type=__magic_name__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__magic_name__ , default=__magic_name__ , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__magic_name__ , default=3 , help="""Number of train epochs.""" , ) UpperCamelCase :str = parser.parse_args() UpperCamelCase :Any = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
38
1
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : str , __lowerCamelCase : pyspark.sql.DataFrame , __lowerCamelCase : Optional[NamedSplit] = None , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : bool = True , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : str = None , __lowerCamelCase : bool = True , __lowerCamelCase : str = "arrow" , **__lowerCamelCase : Dict , ): super().__init__( split=__lowerCamelCase , features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :List[Any] = load_from_cache_file UpperCamelCase :Tuple = file_format UpperCamelCase :Any = Spark( df=__lowerCamelCase , features=__lowerCamelCase , cache_dir=__lowerCamelCase , working_dir=__lowerCamelCase , **__lowerCamelCase , ) def _A ( self : str ): if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) UpperCamelCase :List[str] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=__lowerCamelCase , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
38
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[Any] = TransfoXLTokenizer snake_case__ : List[Any] = False snake_case__ : Tuple = False def _A ( self : str ): super().setUp() UpperCamelCase :Dict = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _A ( self : List[str] , **__lowerCamelCase : Any ): UpperCamelCase :Any = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : int ): UpperCamelCase :List[Any] = """<unk> UNwanted , running""" UpperCamelCase :int = """<unk> unwanted, running""" return input_text, output_text def _A ( self : Tuple ): UpperCamelCase :List[str] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__lowerCamelCase ) UpperCamelCase :Any = tokenizer.tokenize("""<unk> UNwanted , running""" ) self.assertListEqual(__lowerCamelCase , ["""<unk>""", """unwanted""", """,""", """running"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [0, 4, 8, 7] ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _A ( self : Tuple ): UpperCamelCase :Any = TransfoXLTokenizer(lower_case=__lowerCamelCase ) UpperCamelCase :Optional[int] = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" UpperCamelCase :Optional[int] = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(__lowerCamelCase ) , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = len(__lowerCamelCase ) tokenizer.add_tokens(["""new1""", """new2"""] ) tokenizer.move_added_token("""new1""" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , """new1""" )
38
1
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> str: """simple docstring""" UpperCamelCase :Tuple = FileLock(str(tmpdir / """foo.lock""" ) ) UpperCamelCase :Tuple = FileLock(str(tmpdir / """foo.lock""" ) ) UpperCamelCase :Dict = 0.01 with locka.acquire(): with pytest.raises(__magic_name__ ): UpperCamelCase :Optional[Any] = time.time() locka.acquire(__magic_name__ ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any ) -> Optional[int]: """simple docstring""" UpperCamelCase :Optional[int] = """a""" * 1000 + """.lock""" UpperCamelCase :Optional[Any] = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(""".lock""" ) assert not locka._lock_file.endswith(__magic_name__ ) assert len(os.path.basename(locka._lock_file ) ) <= 255 UpperCamelCase :Dict = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(__magic_name__ ): locka.acquire(0 )
38
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase_ : int = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[int] ) -> Dict: """simple docstring""" for attribute in key.split(""".""" ): UpperCamelCase :Dict = getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: UpperCamelCase :Optional[int] = getattr(__magic_name__ , __magic_name__ ).shape else: UpperCamelCase :Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCamelCase :str = value elif weight_type == "weight_g": UpperCamelCase :int = value elif weight_type == "weight_v": UpperCamelCase :int = value elif weight_type == "bias": UpperCamelCase :List[Any] = value else: UpperCamelCase :Any = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Dict = fairseq_model.state_dict() UpperCamelCase :int = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase :str = False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == """group""" , ) UpperCamelCase :Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase :Optional[int] = True if "*" in mapped_key: UpperCamelCase :List[Any] = name.split(__magic_name__ )[0].split(""".""" )[-2] UpperCamelCase :int = mapped_key.replace("""*""" , __magic_name__ ) if "weight_g" in name: UpperCamelCase :List[Any] = """weight_g""" elif "weight_v" in name: UpperCamelCase :List[Any] = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase :Any = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase :List[str] = """weight""" else: UpperCamelCase :Optional[int] = None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int , __magic_name__ : List[str] ) -> Dict: """simple docstring""" UpperCamelCase :Dict = full_name.split("""conv_layers.""" )[-1] UpperCamelCase :int = name.split(""".""" ) UpperCamelCase :str = int(items[0] ) UpperCamelCase :str = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCamelCase :Dict = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCamelCase :Union[str, Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : List[Any] , __magic_name__ : str=None ) -> int: """simple docstring""" UpperCamelCase :List[Any] = torch.load(__magic_name__ ) UpperCamelCase :List[Any] = WavLMConfigOrig(checkpoint["""cfg"""] ) UpperCamelCase :int = WavLMOrig(__magic_name__ ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: UpperCamelCase :List[Any] = WavLMConfig.from_pretrained(__magic_name__ ) else: UpperCamelCase :Any = WavLMConfig() UpperCamelCase :Dict = WavLMModel(__magic_name__ ) recursively_load_weights(__magic_name__ , __magic_name__ ) hf_wavlm.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') UpperCAmelCase_ : Optional[int] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
38
1
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Dict = ["""flax"""] def __init__( self : Optional[Any] , *__lowerCamelCase : str , **__lowerCamelCase : Tuple ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Optional[int] , *__lowerCamelCase : Optional[int] , **__lowerCamelCase : str ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Tuple , *__lowerCamelCase : Tuple , **__lowerCamelCase : int ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : List[str] = ["""flax"""] def __init__( self : int , *__lowerCamelCase : str , **__lowerCamelCase : int ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : List[Any] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : int ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : List[str] , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : str ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Optional[Any] = ["""flax"""] def __init__( self : Any , *__lowerCamelCase : Optional[int] , **__lowerCamelCase : Union[str, Any] ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Optional[int] , *__lowerCamelCase : str , **__lowerCamelCase : int ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : List[Any] , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : List[Any] ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : str = ["""flax"""] def __init__( self : Dict , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : Dict ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : List[str] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Optional[Any] ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : List[str] , *__lowerCamelCase : str , **__lowerCamelCase : Any ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : str = ["""flax"""] def __init__( self : int , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Optional[Any] ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Optional[int] , *__lowerCamelCase : int , **__lowerCamelCase : Tuple ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Optional[int] , *__lowerCamelCase : Any , **__lowerCamelCase : Dict ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Union[str, Any] = ["""flax"""] def __init__( self : List[str] , *__lowerCamelCase : str , **__lowerCamelCase : List[Any] ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : str , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Union[str, Any] ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Optional[Any] , *__lowerCamelCase : int , **__lowerCamelCase : List[str] ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : int = ["""flax"""] def __init__( self : Union[str, Any] , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Any , *__lowerCamelCase : Any , **__lowerCamelCase : str ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Union[str, Any] , *__lowerCamelCase : Tuple , **__lowerCamelCase : int ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Optional[Any] = ["""flax"""] def __init__( self : List[Any] , *__lowerCamelCase : str , **__lowerCamelCase : int ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : int , *__lowerCamelCase : List[str] , **__lowerCamelCase : List[str] ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Dict , *__lowerCamelCase : Dict , **__lowerCamelCase : int ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Dict = ["""flax"""] def __init__( self : List[str] , *__lowerCamelCase : str , **__lowerCamelCase : Tuple ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Optional[Any] , *__lowerCamelCase : str , **__lowerCamelCase : List[str] ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Union[str, Any] , *__lowerCamelCase : List[str] , **__lowerCamelCase : List[Any] ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : List[str] = ["""flax"""] def __init__( self : Dict , *__lowerCamelCase : int , **__lowerCamelCase : Optional[Any] ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : str , *__lowerCamelCase : Tuple , **__lowerCamelCase : Optional[Any] ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Optional[int] , *__lowerCamelCase : Any , **__lowerCamelCase : Optional[Any] ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : str = ["""flax"""] def __init__( self : int , *__lowerCamelCase : Tuple , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Optional[int] , *__lowerCamelCase : Tuple , **__lowerCamelCase : int ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Tuple , *__lowerCamelCase : str , **__lowerCamelCase : Optional[Any] ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Optional[Any] = ["""flax"""] def __init__( self : int , *__lowerCamelCase : List[Any] , **__lowerCamelCase : str ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Dict , *__lowerCamelCase : Any , **__lowerCamelCase : Union[str, Any] ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : List[Any] , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : int ): requires_backends(cls , ["""flax"""] ) class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Optional[int] = ["""flax"""] def __init__( self : List[str] , *__lowerCamelCase : str , **__lowerCamelCase : Optional[Any] ): requires_backends(self , ["""flax"""] ) @classmethod def _A ( cls : Union[str, Any] , *__lowerCamelCase : Optional[int] , **__lowerCamelCase : Union[str, Any] ): requires_backends(cls , ["""flax"""] ) @classmethod def _A ( cls : Any , *__lowerCamelCase : Tuple , **__lowerCamelCase : List[str] ): requires_backends(cls , ["""flax"""] )
38
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCAmelCase_ : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""bs4"""] ) super().__init__(**__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = [] UpperCamelCase :List[str] = [] UpperCamelCase :Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag UpperCamelCase :Optional[Any] = parent.find_all(child.name , recursive=__lowerCamelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCamelCase ) else next(i for i, s in enumerate(__lowerCamelCase , 1 ) if s is child ) ) UpperCamelCase :Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Any = BeautifulSoup(__lowerCamelCase , """html.parser""" ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Tuple = [] UpperCamelCase :Tuple = [] for element in html_code.descendants: if type(__lowerCamelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue UpperCamelCase :Any = html.unescape(__lowerCamelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = self.xpath_soup(__lowerCamelCase ) stringaxtag_seq.append(__lowerCamelCase ) stringaxsubs_seq.append(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Tuple = """""" for tagname, subs in zip(__lowerCamelCase , __lowerCamelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Any , __lowerCamelCase : Dict ): UpperCamelCase :Any = False # Check that strings has a valid type if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = True elif isinstance(__lowerCamelCase , (list, tuple) ): if len(__lowerCamelCase ) == 0 or isinstance(html_strings[0] , __lowerCamelCase ): UpperCamelCase :Any = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ F"""but is of type {type(__lowerCamelCase )}.""" ) UpperCamelCase :str = bool(isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(html_strings[0] , __lowerCamelCase )) ) if not is_batched: UpperCamelCase :Any = [html_strings] # Get nodes + xpaths UpperCamelCase :Union[str, Any] = [] UpperCamelCase :str = [] for html_string in html_strings: UpperCamelCase , UpperCamelCase , UpperCamelCase :int = self.get_three_from_single(__lowerCamelCase ) nodes.append(__lowerCamelCase ) UpperCamelCase :int = [] for node, tag_list, sub_list in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): UpperCamelCase :str = self.construct_xpath(__lowerCamelCase , __lowerCamelCase ) xpath_strings.append(__lowerCamelCase ) xpaths.append(__lowerCamelCase ) # return as Dict UpperCamelCase :Optional[int] = {"""nodes""": nodes, """xpaths""": xpaths} UpperCamelCase :Any = BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) return encoded_inputs
38
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ : Dict = { '''configuration_xlm_roberta_xl''': [ '''XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaXLConfig''', '''XLMRobertaXLOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = [ '''XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaXLForCausalLM''', '''XLMRobertaXLForMaskedLM''', '''XLMRobertaXLForMultipleChoice''', '''XLMRobertaXLForQuestionAnswering''', '''XLMRobertaXLForSequenceClassification''', '''XLMRobertaXLForTokenClassification''', '''XLMRobertaXLModel''', '''XLMRobertaXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys UpperCAmelCase_ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
38
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : list[int] ) -> bool: """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : list[int] , __magic_name__ : int ) -> bool: """simple docstring""" if curr_ind == len(__magic_name__ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__magic_name__ ) ): if valid_connection(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): # Insert current vertex into path as next transition UpperCamelCase :str = next_ver # Validate created path if util_hamilton_cycle(__magic_name__ , __magic_name__ , curr_ind + 1 ): return True # Backtrack UpperCamelCase :Union[str, Any] = -1 return False def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int = 0 ) -> list[int]: """simple docstring""" UpperCamelCase :Union[str, Any] = [-1] * (len(__magic_name__ ) + 1) # initialize start and end of path with starting index UpperCamelCase :Any = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__magic_name__ , __magic_name__ , 1 ) else []
38
1
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=_a ): snake_case__ : Dict = ["""transformers""", """torch""", """note_seq"""] def __init__( self : Union[str, Any] , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : Optional[Any] ): requires_backends(self , ["""transformers""", """torch""", """note_seq"""] ) @classmethod def _A ( cls : Tuple , *__lowerCamelCase : int , **__lowerCamelCase : List[Any] ): requires_backends(cls , ["""transformers""", """torch""", """note_seq"""] ) @classmethod def _A ( cls : Tuple , *__lowerCamelCase : int , **__lowerCamelCase : Tuple ): requires_backends(cls , ["""transformers""", """torch""", """note_seq"""] )
38
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : str=7 , __lowerCamelCase : Tuple=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Any=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : str=False , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : Any=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : List[Any]=12 , __lowerCamelCase : int=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Optional[int]="last" , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[str]=None , ): UpperCamelCase :int = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :str = seq_length UpperCamelCase :Optional[int] = is_training UpperCamelCase :Optional[int] = use_input_lengths UpperCamelCase :Union[str, Any] = use_token_type_ids UpperCamelCase :List[str] = use_labels UpperCamelCase :Dict = gelu_activation UpperCamelCase :Optional[int] = sinusoidal_embeddings UpperCamelCase :List[Any] = causal UpperCamelCase :Optional[int] = asm UpperCamelCase :List[str] = n_langs UpperCamelCase :int = vocab_size UpperCamelCase :List[Any] = n_special UpperCamelCase :List[Any] = hidden_size UpperCamelCase :List[str] = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :Tuple = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :List[str] = type_vocab_size UpperCamelCase :Union[str, Any] = type_sequence_label_size UpperCamelCase :int = initializer_range UpperCamelCase :List[str] = num_labels UpperCamelCase :Optional[int] = num_choices UpperCamelCase :Optional[Any] = summary_type UpperCamelCase :Tuple = use_proj UpperCamelCase :Optional[Any] = scope def _A ( self : List[str] ): UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Any = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :List[Any] = None if self.use_input_lengths: UpperCamelCase :Dict = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase :str = None if self.use_token_type_ids: UpperCamelCase :int = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase :Optional[int] = None UpperCamelCase :int = None UpperCamelCase :List[Any] = None if self.use_labels: UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :List[str] = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase :List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _A ( self : List[Any] ): return 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 , ) def _A ( self : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : int , ): UpperCamelCase :Tuple = FlaubertModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :int = model(__lowerCamelCase , lengths=__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :List[Any] = model(__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , ): UpperCamelCase :Any = FlaubertWithLMHeadModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Dict = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Any = FlaubertForQuestionAnsweringSimple(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) 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 _A ( self : str , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : str , ): UpperCamelCase :str = FlaubertForQuestionAnswering(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :Optional[int] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , p_mask=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , ) ((UpperCamelCase) , ) :int = result_with_labels.to_tuple() UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) ((UpperCamelCase) , ) :List[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , ): UpperCamelCase :Optional[int] = FlaubertForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Tuple = model(__lowerCamelCase ) UpperCamelCase :List[str] = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A ( self : Any , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Dict = self.num_labels UpperCamelCase :Tuple = FlaubertForTokenClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Union[str, Any] = self.num_choices UpperCamelCase :List[Any] = FlaubertForMultipleChoice(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A ( self : str ): UpperCamelCase :List[str] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :List[Any] = config_and_inputs UpperCamelCase :Union[str, Any] = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[int] = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _A ( self : int , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ): 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 _A ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ): UpperCamelCase :Tuple = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": UpperCamelCase :Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) UpperCamelCase :List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def _A ( self : str ): UpperCamelCase :List[Any] = FlaubertModelTester(self ) UpperCamelCase :Any = ConfigTester(self , config_class=__lowerCamelCase , emb_dim=37 ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__lowerCamelCase ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__lowerCamelCase ) def _A ( self : int ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__lowerCamelCase ) @slow def _A ( self : Any ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Optional[int] = FlaubertModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @slow @require_torch_gpu def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = model_class(config=__lowerCamelCase ) UpperCamelCase :str = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :str = torch.jit.trace( __lowerCamelCase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__lowerCamelCase , os.path.join(__lowerCamelCase , """traced_model.pt""" ) ) UpperCamelCase :int = torch.jit.load(os.path.join(__lowerCamelCase , """traced_model.pt""" ) , map_location=__lowerCamelCase ) loaded(inputs_dict["""input_ids"""].to(__lowerCamelCase ) , inputs_dict["""attention_mask"""].to(__lowerCamelCase ) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) UpperCamelCase :Optional[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): UpperCamelCase :Tuple = model(__lowerCamelCase )[0] UpperCamelCase :Union[str, Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :int = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
38
1
from __future__ import annotations import pandas as pd def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : list[int] , __magic_name__ : int ) -> list[int]: """simple docstring""" UpperCamelCase :List[str] = [0] * no_of_processes UpperCamelCase :str = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(__magic_name__ ): UpperCamelCase :Optional[int] = burst_time[i] UpperCamelCase :str = 0 UpperCamelCase :Tuple = 0 UpperCamelCase :Union[str, Any] = 9_9999_9999 UpperCamelCase :Optional[Any] = 0 UpperCamelCase :Optional[int] = False # Process until all processes are completed while complete != no_of_processes: for j in range(__magic_name__ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: UpperCamelCase :Dict = remaining_time[j] UpperCamelCase :Optional[Any] = j UpperCamelCase :List[str] = True if not check: increment_time += 1 continue remaining_time[short] -= 1 UpperCamelCase :List[str] = remaining_time[short] if minm == 0: UpperCamelCase :Any = 9_9999_9999 if remaining_time[short] == 0: complete += 1 UpperCamelCase :Dict = False # Find finish time of current process UpperCamelCase :Dict = increment_time + 1 # Calculate waiting time UpperCamelCase :Union[str, Any] = finish_time - arrival_time[short] UpperCamelCase :Optional[Any] = finar - burst_time[short] if waiting_time[short] < 0: UpperCamelCase :Optional[Any] = 0 # Increment time increment_time += 1 return waiting_time def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : list[int] ) -> list[int]: """simple docstring""" UpperCamelCase :Optional[Any] = [0] * no_of_processes for i in range(__magic_name__ ): UpperCamelCase :List[str] = burst_time[i] + waiting_time[i] return turn_around_time def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : list[int] , __magic_name__ : int ) -> None: """simple docstring""" UpperCamelCase :int = 0 UpperCamelCase :str = 0 for i in range(__magic_name__ ): UpperCamelCase :List[Any] = total_waiting_time + waiting_time[i] UpperCamelCase :str = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("""Average turn around time =""" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') UpperCAmelCase_ : Any = int(input()) UpperCAmelCase_ : Optional[int] = [0] * no_of_processes UpperCAmelCase_ : Any = [0] * no_of_processes UpperCAmelCase_ : Any = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) UpperCAmelCase_ , UpperCAmelCase_ : Dict = map(int, input().split()) UpperCAmelCase_ : List[str] = calculate_waitingtime(arrival_time, burst_time, no_of_processes) UpperCAmelCase_ : Tuple = burst_time UpperCAmelCase_ : List[str] = no_of_processes UpperCAmelCase_ : Union[str, Any] = waiting_time UpperCAmelCase_ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) UpperCAmelCase_ : Tuple = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
38
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """openai/whisper-base""" snake_case__ : Optional[int] = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) snake_case__ : Any = """transcriber""" snake_case__ : Optional[int] = WhisperProcessor snake_case__ : str = WhisperForConditionalGeneration snake_case__ : Optional[Any] = ["""audio"""] snake_case__ : Any = ["""text"""] def _A ( self : str , __lowerCamelCase : Dict ): return self.pre_processor(__lowerCamelCase , return_tensors="""pt""" ).input_features def _A ( self : Dict , __lowerCamelCase : List[Any] ): return self.model.generate(inputs=__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : Optional[Any] ): return self.pre_processor.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase )[0]
38
1
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) @dataclass class _SCREAMING_SNAKE_CASE : snake_case__ : str = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys() )} ) snake_case__ : str = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) snake_case__ : int = field( default=1_2_8 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) snake_case__ : bool = field( default=_a , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _A ( self : Dict ): UpperCamelCase :List[Any] = self.task_name.lower() class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """train""" snake_case__ : Union[str, Any] = """dev""" snake_case__ : Union[str, Any] = """test""" class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : GlueDataTrainingArguments snake_case__ : str snake_case__ : List[InputFeatures] def __init__( self : List[Any] , __lowerCamelCase : GlueDataTrainingArguments , __lowerCamelCase : PreTrainedTokenizerBase , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Union[str, Split] = Split.train , __lowerCamelCase : Optional[str] = None , ): warnings.warn( """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """ """library. You can have a look at this example script for pointers: """ """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" , __lowerCamelCase , ) UpperCamelCase :Tuple = args UpperCamelCase :Dict = glue_processors[args.task_name]() UpperCamelCase :Any = glue_output_modes[args.task_name] if isinstance(__lowerCamelCase , __lowerCamelCase ): try: UpperCamelCase :Any = Split[mode] except KeyError: raise KeyError("""mode is not a valid split name""" ) # Load data features from cache or dataset file UpperCamelCase :Optional[int] = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}""" , ) UpperCamelCase :Union[str, Any] = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) UpperCamelCase , UpperCamelCase :Dict = label_list[2], label_list[1] UpperCamelCase :Tuple = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. UpperCamelCase :str = cached_features_file + """.lock""" with FileLock(__lowerCamelCase ): if os.path.exists(__lowerCamelCase ) and not args.overwrite_cache: UpperCamelCase :List[Any] = time.time() UpperCamelCase :Optional[Any] = torch.load(__lowerCamelCase ) logger.info( F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start ) else: logger.info(F"""Creating features from dataset file at {args.data_dir}""" ) if mode == Split.dev: UpperCamelCase :int = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: UpperCamelCase :Optional[Any] = self.processor.get_test_examples(args.data_dir ) else: UpperCamelCase :str = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: UpperCamelCase :int = examples[:limit_length] UpperCamelCase :Optional[int] = glue_convert_examples_to_features( __lowerCamelCase , __lowerCamelCase , max_length=args.max_seq_length , label_list=__lowerCamelCase , output_mode=self.output_mode , ) UpperCamelCase :List[Any] = time.time() torch.save(self.features , __lowerCamelCase ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" ) def __len__( self : int ): return len(self.features ) def __getitem__( self : Optional[int] , __lowerCamelCase : Any ): return self.features[i] def _A ( self : int ): return self.label_list
38
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=_a ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) snake_case__ : ClassVar[Features] = Features({"""audio""": Audio()} ) snake_case__ : ClassVar[Features] = Features({"""transcription""": Value("""string""" )} ) snake_case__ : str = "audio" snake_case__ : str = "transcription" def _A ( self : List[str] , __lowerCamelCase : Dict ): if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) UpperCamelCase :int = copy.deepcopy(self ) UpperCamelCase :Any = self.input_schema.copy() UpperCamelCase :List[str] = features[self.audio_column] UpperCamelCase :List[Any] = input_schema return task_template @property def _A ( self : Optional[int] ): return {self.audio_column: "audio", self.transcription_column: "transcription"}
38
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
38
1
from itertools import permutations def SCREAMING_SNAKE_CASE_ ( __magic_name__ : tuple ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False UpperCamelCase :List[Any] = [7, 11, 13, 17] for i, test in enumerate(__magic_name__ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 10 ) -> int: """simple docstring""" return sum( int("""""".join(map(__magic_name__ , __magic_name__ ) ) ) for num in permutations(range(__magic_name__ ) ) if is_substring_divisible(__magic_name__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
38
import re import string import numpy as np import datasets UpperCAmelCase_ : Dict = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' UpperCAmelCase_ : Any = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' UpperCAmelCase_ : Tuple = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def _A ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : int=False , __lowerCamelCase : Optional[int]=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase :str = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in predictions] ) UpperCamelCase :Tuple = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in references] ) else: UpperCamelCase :Any = np.asarray(__lowerCamelCase ) UpperCamelCase :str = np.asarray(__lowerCamelCase ) if ignore_case: UpperCamelCase :Tuple = np.char.lower(__lowerCamelCase ) UpperCamelCase :Any = np.char.lower(__lowerCamelCase ) if ignore_punctuation: UpperCamelCase :Optional[int] = string.punctuation.maketrans("""""" , """""" , string.punctuation ) UpperCamelCase :Optional[Any] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :List[str] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) if ignore_numbers: UpperCamelCase :Tuple = string.digits.maketrans("""""" , """""" , string.digits ) UpperCamelCase :Dict = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :Tuple = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :int = predictions == references return {"exact_match": np.mean(__lowerCamelCase ) * 100}
38
1
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Dict = '''T5Config''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : jnp.array , __magic_name__ : int , __magic_name__ : int ) -> jnp.ndarray: """simple docstring""" UpperCamelCase :List[str] = jnp.zeros_like(__magic_name__ ) UpperCamelCase :str = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) UpperCamelCase :Tuple = shifted_input_ids.at[:, 0].set(__magic_name__ ) UpperCamelCase :int = jnp.where(shifted_input_ids == -100 , __magic_name__ , __magic_name__ ) return shifted_input_ids class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : List[Any] = """mt5""" snake_case__ : Optional[Any] = MTaConfig class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """mt5""" snake_case__ : Any = MTaConfig class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[Any] = """mt5""" snake_case__ : List[Any] = MTaConfig
38
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : str = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """layoutlmv3""" def __init__( self : List[Any] , __lowerCamelCase : Optional[Any]=50_265 , __lowerCamelCase : Dict=768 , __lowerCamelCase : Any=12 , __lowerCamelCase : int=12 , __lowerCamelCase : str=3_072 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=512 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Union[str, Any]=0.02 , __lowerCamelCase : Union[str, Any]=1E-5 , __lowerCamelCase : Any=1 , __lowerCamelCase : Optional[int]=0 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Dict=1_024 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=128 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : str=32 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=64 , __lowerCamelCase : List[str]=256 , __lowerCamelCase : Dict=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Tuple=224 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Dict=16 , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : Optional[Any] , ): super().__init__( 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 , initializer_range=__lowerCamelCase , layer_norm_eps=__lowerCamelCase , pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :int = max_ad_position_embeddings UpperCamelCase :Tuple = coordinate_size UpperCamelCase :List[Any] = shape_size UpperCamelCase :Union[str, Any] = has_relative_attention_bias UpperCamelCase :Any = rel_pos_bins UpperCamelCase :Optional[Any] = max_rel_pos UpperCamelCase :str = has_spatial_attention_bias UpperCamelCase :Tuple = rel_ad_pos_bins UpperCamelCase :Optional[int] = max_rel_ad_pos UpperCamelCase :Tuple = text_embed UpperCamelCase :str = visual_embed UpperCamelCase :Optional[Any] = input_size UpperCamelCase :str = num_channels UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[Any] = classifier_dropout class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = version.parse("""1.12""" ) @property def _A ( self : Optional[int] ): # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def _A ( self : str ): return 1E-5 @property def _A ( self : Dict ): return 12 def _A ( self : Dict , __lowerCamelCase : "ProcessorMixin" , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 40 , __lowerCamelCase : int = 40 , ): setattr(processor.image_processor , """apply_ocr""" , __lowerCamelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase :Optional[Any] = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase :Optional[int] = processor.tokenizer.num_special_tokens_to_add(__lowerCamelCase ) UpperCamelCase :int = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase :Any = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase :Optional[Any] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase :List[str] = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = dict( processor( __lowerCamelCase , text=__lowerCamelCase , boxes=__lowerCamelCase , return_tensors=__lowerCamelCase , ) ) return inputs
38
1
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Dict , __lowerCamelCase : Any=0.01 , __lowerCamelCase : Optional[Any]=1_000 ): UpperCamelCase :Dict = p_stop UpperCamelCase :Dict = max_length def __iter__( self : List[str] ): UpperCamelCase :Optional[Any] = 0 UpperCamelCase :int = False while not stop and count < self.max_length: yield count count += 1 UpperCamelCase :List[Any] = random.random() < self.p_stop class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any]=False , __lowerCamelCase : Optional[Any]=True ): UpperCamelCase :str = [ BatchSamplerShard(__lowerCamelCase , 2 , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) for i in range(2 ) ] UpperCamelCase :Union[str, Any] = [list(__lowerCamelCase ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(__lowerCamelCase ) for shard in batch_sampler_shards] , [len(__lowerCamelCase ) for e in expected] ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _A ( self : List[str] ): # Check the shards when the dataset is a round multiple of total batch size. UpperCamelCase :Optional[Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. UpperCamelCase :Tuple = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. UpperCamelCase :Any = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Dict = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :List[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. UpperCamelCase :Union[str, Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Dict = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :List[Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :int = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) def _A ( self : Dict ): # Check the shards when the dataset is a round multiple of batch size. UpperCamelCase :Any = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :List[str] = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. UpperCamelCase :Optional[int] = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :Tuple = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. UpperCamelCase :int = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[int] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :Tuple = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :List[str] = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :Dict = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :int = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) def _A ( self : Dict ): # Check the shards when the dataset is a round multiple of total batch size. UpperCamelCase :str = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. UpperCamelCase :Union[str, Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :int = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. UpperCamelCase :Tuple = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. UpperCamelCase :List[Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :str = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :Union[str, Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[int] = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) def _A ( self : List[Any] ): # Check the shards when the dataset is a round multiple of batch size. UpperCamelCase :Optional[int] = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :int = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Any = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. UpperCamelCase :int = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. UpperCamelCase :str = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :List[Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :int = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :List[str] = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :List[str] = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) def _A ( self : Dict ): UpperCamelCase :Tuple = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] UpperCamelCase :int = [BatchSamplerShard(__lowerCamelCase , 2 , __lowerCamelCase , even_batches=__lowerCamelCase ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def _A ( self : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : List[str]=False , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Tuple=False ): random.seed(__lowerCamelCase ) UpperCamelCase :Any = list(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ IterableDatasetShard( __lowerCamelCase , batch_size=__lowerCamelCase , drop_last=__lowerCamelCase , num_processes=__lowerCamelCase , process_index=__lowerCamelCase , split_batches=__lowerCamelCase , ) for i in range(__lowerCamelCase ) ] UpperCamelCase :Union[str, Any] = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(__lowerCamelCase ) iterable_dataset_lists.append(list(__lowerCamelCase ) ) UpperCamelCase :List[str] = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size UpperCamelCase :Dict = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(len(__lowerCamelCase ) % shard_batch_size == 0 ) UpperCamelCase :List[str] = [] for idx in range(0 , len(__lowerCamelCase ) , __lowerCamelCase ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(__lowerCamelCase ) < len(__lowerCamelCase ): reference += reference self.assertListEqual(__lowerCamelCase , reference[: len(__lowerCamelCase )] ) def _A ( self : int ): UpperCamelCase :Optional[int] = 42 UpperCamelCase :Optional[Any] = RandomIterableDataset() self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) # Edge case with a very small dataset UpperCamelCase :Optional[int] = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Union[str, Any] = BatchSampler(range(16 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = SkipBatchSampler(__lowerCamelCase , 2 ) self.assertListEqual(list(__lowerCamelCase ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _A ( self : Optional[Any] ): UpperCamelCase :Tuple = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _A ( self : int ): UpperCamelCase :Dict = DataLoader(list(range(16 ) ) , batch_size=4 ) UpperCamelCase :Union[str, Any] = skip_first_batches(__lowerCamelCase , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _A ( self : Any ): UpperCamelCase :Union[str, Any] = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def _A ( self : List[str] ): Accelerator() UpperCamelCase :Optional[int] = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Any = StableDiffusionXLImgaImgPipeline snake_case__ : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} snake_case__ : Tuple = PipelineTesterMixin.required_optional_params - {"""latents"""} snake_case__ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case__ : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS snake_case__ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=__lowerCamelCase , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) UpperCamelCase :Tuple = EulerDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCamelCase :Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=32 , ) UpperCamelCase :Any = CLIPTextModel(__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTextModelWithProjection(__lowerCamelCase ) UpperCamelCase :int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _A ( self : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any]=0 ): UpperCamelCase :Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) UpperCamelCase :List[str] = image / 2 + 0.5 if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :Any = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :List[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def _A ( self : str ): UpperCamelCase :List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :Optional[Any] = self.get_dummy_components() UpperCamelCase :List[Any] = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :Any = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = sd_pipe(**__lowerCamelCase ).images UpperCamelCase :Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :List[Any] = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : Dict ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _A ( self : Optional[Any] ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _A ( self : Union[str, Any] ): pass def _A ( self : Optional[int] ): UpperCamelCase :Union[str, Any] = self.get_dummy_components() UpperCamelCase :Dict = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :List[Any] = sd_pipe.to(__lowerCamelCase ) UpperCamelCase :List[str] = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) # forward without prompt embeds UpperCamelCase :List[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :int = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = negative_prompt UpperCamelCase :Union[str, Any] = 3 * [inputs["""prompt"""]] UpperCamelCase :Dict = sd_pipe(**__lowerCamelCase ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = 3 * [inputs.pop("""prompt""" )] ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = sd_pipe.encode_prompt(__lowerCamelCase , negative_prompt=__lowerCamelCase ) UpperCamelCase :Dict = sd_pipe( **__lowerCamelCase , prompt_embeds=__lowerCamelCase , negative_prompt_embeds=__lowerCamelCase , pooled_prompt_embeds=__lowerCamelCase , negative_pooled_prompt_embeds=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Tuple ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict="cpu" , __lowerCamelCase : List[Any]=torch.floataa , __lowerCamelCase : Tuple=0 ): UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = np.random.RandomState(__lowerCamelCase ).standard_normal((1, 4, 64, 64) ) UpperCamelCase :Dict = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase , dtype=__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _A ( self : Optional[Any] ): UpperCamelCase :Any = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = pipe(**__lowerCamelCase ).images UpperCamelCase :Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCamelCase :Union[str, Any] = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str ) -> List[str]: """simple docstring""" UpperCamelCase :str = [] UpperCamelCase :List[str] = set({"""(""", """[""", """{"""} ) UpperCamelCase :Any = set({""")""", """]""", """}"""} ) UpperCamelCase :str = {"""{""": """}""", """[""": """]""", """(""": """)"""} for i in range(len(__magic_name__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(__magic_name__ ) == 0 or (len(__magic_name__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(__magic_name__ ) == 0 def SCREAMING_SNAKE_CASE_ ( ) -> List[Any]: """simple docstring""" UpperCamelCase :int = input("""Enter sequence of brackets: """ ) if is_balanced(__magic_name__ ): print(__magic_name__ , """is balanced""" ) else: print(__magic_name__ , """is not balanced""" ) if __name__ == "__main__": main()
38
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : int = { '''CarlCochet/trajectory-transformer-halfcheetah-medium-v2''': ( '''https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json''' ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """trajectory_transformer""" snake_case__ : Optional[Any] = ["""past_key_values"""] snake_case__ : Tuple = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Union[str, Any] , __lowerCamelCase : Any=100 , __lowerCamelCase : str=5 , __lowerCamelCase : str=1 , __lowerCamelCase : Optional[int]=1 , __lowerCamelCase : int=249 , __lowerCamelCase : str=6 , __lowerCamelCase : Dict=17 , __lowerCamelCase : Optional[Any]=25 , __lowerCamelCase : List[str]=4 , __lowerCamelCase : str=4 , __lowerCamelCase : Tuple=128 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : int=0.0006 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Any=1E-12 , __lowerCamelCase : int=1 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Tuple=1 , __lowerCamelCase : int=50_256 , __lowerCamelCase : Union[str, Any]=50_256 , **__lowerCamelCase : Dict , ): UpperCamelCase :Dict = vocab_size UpperCamelCase :int = action_weight UpperCamelCase :Tuple = reward_weight UpperCamelCase :str = value_weight UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :Tuple = block_size UpperCamelCase :Optional[int] = action_dim UpperCamelCase :int = observation_dim UpperCamelCase :List[str] = transition_dim UpperCamelCase :List[Any] = learning_rate UpperCamelCase :Optional[Any] = n_layer UpperCamelCase :Any = n_head UpperCamelCase :List[str] = n_embd UpperCamelCase :Any = embd_pdrop UpperCamelCase :str = attn_pdrop UpperCamelCase :Union[str, Any] = resid_pdrop UpperCamelCase :Optional[Any] = initializer_range UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Optional[int] = kaiming_initializer_range UpperCamelCase :Tuple = use_cache super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str ) -> bool: """simple docstring""" if not all(x.isalpha() for x in string ): raise ValueError("""String must only contain alphabetic characters.""" ) UpperCamelCase :Union[str, Any] = sorted(string.lower() ) return len(__magic_name__ ) == len(set(__magic_name__ ) ) if __name__ == "__main__": UpperCAmelCase_ : Any = input('''Enter a string ''').strip() UpperCAmelCase_ : List[str] = is_isogram(input_str) print(F'''{input_str} is {"an" if isogram else "not an"} isogram.''')
38
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 3 ) -> qiskit.result.counts.Counts: """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): raise TypeError("""number of qubits must be a integer.""" ) if number_of_qubits <= 0: raise ValueError("""number of qubits must be > 0.""" ) if math.floor(__magic_name__ ) != number_of_qubits: raise ValueError("""number of qubits must be exact integer.""" ) if number_of_qubits > 10: raise ValueError("""number of qubits too large to simulate(>10).""" ) UpperCamelCase :int = QuantumRegister(__magic_name__ , """qr""" ) UpperCamelCase :str = ClassicalRegister(__magic_name__ , """cr""" ) UpperCamelCase :str = QuantumCircuit(__magic_name__ , __magic_name__ ) UpperCamelCase :List[Any] = number_of_qubits for i in range(__magic_name__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(__magic_name__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , __magic_name__ , __magic_name__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(__magic_name__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(__magic_name__ , __magic_name__ ) # simulate with 10000 shots UpperCamelCase :str = Aer.get_backend("""qasm_simulator""" ) UpperCamelCase :Dict = execute(__magic_name__ , __magic_name__ , shots=1_0000 ) return job.result().get_counts(__magic_name__ ) if __name__ == "__main__": print( F'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
38
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase_ : Dict = { '''configuration_mobilenet_v2''': [ '''MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileNetV2Config''', '''MobileNetV2OnnxConfig''', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = ['''MobileNetV2FeatureExtractor'''] UpperCAmelCase_ : Union[str, Any] = ['''MobileNetV2ImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ '''MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileNetV2ForImageClassification''', '''MobileNetV2ForSemanticSegmentation''', '''MobileNetV2Model''', '''MobileNetV2PreTrainedModel''', '''load_tf_weights_in_mobilenet_v2''', ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys UpperCAmelCase_ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer UpperCAmelCase_ : Optional[Any] = ['''bert-base-uncased''', '''bert-base-cased'''] UpperCAmelCase_ : List[str] = '''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class _SCREAMING_SNAKE_CASE ( tf.keras.Model ): def __init__( self : List[str] , __lowerCamelCase : Union[str, Any] ): super().__init__() UpperCamelCase :Any = tokenizer UpperCamelCase :List[str] = AutoConfig.from_pretrained(__lowerCamelCase ) UpperCamelCase :List[str] = TFAutoModel.from_config(__lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : str ): UpperCamelCase :str = self.tokenizer(__lowerCamelCase ) UpperCamelCase :Any = self.bert(**__lowerCamelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Dict ): super().setUp() UpperCamelCase :int = [ BertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase :Any = [TFBertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(__lowerCamelCase , use_fast_bert_tokenizer=__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase :Any = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] UpperCamelCase :Union[str, Any] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _A ( self : Optional[int] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tokenizer(__lowerCamelCase , return_tensors="""tf""" , padding="""longest""" ) UpperCamelCase :str = tf_tokenizer(__lowerCamelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _A ( self : Dict ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :str = tf_tokenizer(self.paired_sentences ) UpperCamelCase :Any = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _A ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[Any] = tf.function(__lowerCamelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tf.constant(__lowerCamelCase ) UpperCamelCase :List[str] = compiled_tokenizer(__lowerCamelCase ) UpperCamelCase :Optional[Any] = tf_tokenizer(__lowerCamelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _A ( self : Tuple ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[str] = ModelToSave(tokenizer=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase :List[str] = Path(__lowerCamelCase ) / """saved.model""" model.save(__lowerCamelCase ) UpperCamelCase :List[Any] = tf.keras.models.load_model(__lowerCamelCase ) UpperCamelCase :Dict = loaded_model(__lowerCamelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" if n == 1 or not isinstance(__magic_name__ , __magic_name__ ): return 0 elif n == 2: return 1 else: UpperCamelCase :List[Any] = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" UpperCamelCase :Dict = 0 UpperCamelCase :int = 2 while digits < n: index += 1 UpperCamelCase :Optional[Any] = len(str(fibonacci(__magic_name__ ) ) ) return index def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 1000 ) -> int: """simple docstring""" return fibonacci_digits_index(__magic_name__ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
38
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase_ : Any = '''Create a default config file for Accelerate with only a few flags set.''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int]="no" , __magic_name__ : str = default_json_config_file , __magic_name__ : bool = False ) -> str: """simple docstring""" UpperCamelCase :Any = Path(__magic_name__ ) path.parent.mkdir(parents=__magic_name__ , exist_ok=__magic_name__ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False UpperCamelCase :Dict = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) UpperCamelCase :Optional[Any] = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): UpperCamelCase :Union[str, Any] = torch.cuda.device_count() UpperCamelCase :List[Any] = num_gpus UpperCamelCase :Dict = False if num_gpus > 1: UpperCamelCase :Any = """MULTI_GPU""" else: UpperCamelCase :Any = """NO""" elif is_xpu_available() and use_xpu: UpperCamelCase :Optional[Any] = torch.xpu.device_count() UpperCamelCase :Optional[int] = num_xpus UpperCamelCase :int = False if num_xpus > 1: UpperCamelCase :Union[str, Any] = """MULTI_XPU""" else: UpperCamelCase :Union[str, Any] = """NO""" elif is_npu_available(): UpperCamelCase :List[Any] = torch.npu.device_count() UpperCamelCase :Optional[Any] = num_npus UpperCamelCase :Tuple = False if num_npus > 1: UpperCamelCase :Optional[Any] = """MULTI_NPU""" else: UpperCamelCase :List[Any] = """NO""" else: UpperCamelCase :Any = 0 UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[str] = """NO""" UpperCamelCase :int = ClusterConfig(**__magic_name__ ) config.to_json_file(__magic_name__ ) return path def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = parser.add_parser("""default""" , parents=__magic_name__ , help=__magic_name__ , formatter_class=__magic_name__ ) parser.add_argument( """--config_file""" , default=__magic_name__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=__magic_name__ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=__magic_name__ ) return parser def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
38
1
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Union[str, Any] = (DPMSolverSDEScheduler,) snake_case__ : str = 1_0 def _A ( self : Any , **__lowerCamelCase : Any ): UpperCamelCase :Any = { """num_train_timesteps""": 1_100, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """noise_sampler_seed""": 0, } config.update(**__lowerCamelCase ) return config def _A ( self : str ): for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=__lowerCamelCase ) def _A ( self : List[str] ): for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__lowerCamelCase , beta_end=__lowerCamelCase ) def _A ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__lowerCamelCase ) def _A ( self : str ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :str = self.scheduler_classes[0] UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :List[str] = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps ) UpperCamelCase :List[str] = self.dummy_model() UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCamelCase :Optional[int] = sample.to(__lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): UpperCamelCase :Optional[Any] = scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :List[str] = model(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :str = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :List[str] = output.prev_sample UpperCamelCase :Union[str, Any] = torch.sum(torch.abs(__lowerCamelCase ) ) UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = self.scheduler_classes[0] UpperCamelCase :int = self.get_scheduler_config(prediction_type="""v_prediction""" ) UpperCamelCase :Any = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps ) UpperCamelCase :Tuple = self.dummy_model() UpperCamelCase :Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCamelCase :Any = sample.to(__lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): UpperCamelCase :Union[str, Any] = scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Dict = model(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Dict = output.prev_sample UpperCamelCase :List[str] = torch.sum(torch.abs(__lowerCamelCase ) ) UpperCamelCase :Any = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def _A ( self : int ): UpperCamelCase :Dict = self.scheduler_classes[0] UpperCamelCase :str = self.get_scheduler_config() UpperCamelCase :Union[str, Any] = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps , device=__lowerCamelCase ) UpperCamelCase :Dict = self.dummy_model() UpperCamelCase :str = self.dummy_sample_deter.to(__lowerCamelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: UpperCamelCase :Any = scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = model(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :str = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :List[Any] = output.prev_sample UpperCamelCase :Tuple = torch.sum(torch.abs(__lowerCamelCase ) ) UpperCamelCase :List[str] = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def _A ( self : Optional[int] ): UpperCamelCase :int = self.scheduler_classes[0] UpperCamelCase :Dict = self.get_scheduler_config() UpperCamelCase :List[str] = scheduler_class(**__lowerCamelCase , use_karras_sigmas=__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps , device=__lowerCamelCase ) UpperCamelCase :int = self.dummy_model() UpperCamelCase :Optional[int] = self.dummy_sample_deter.to(__lowerCamelCase ) * scheduler.init_noise_sigma UpperCamelCase :List[Any] = sample.to(__lowerCamelCase ) for t in scheduler.timesteps: UpperCamelCase :List[Any] = scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = model(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Tuple = scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = output.prev_sample UpperCamelCase :Optional[int] = torch.sum(torch.abs(__lowerCamelCase ) ) UpperCamelCase :Any = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
38
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
1
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Dict="attention" ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :Any = params[f"""{prefix}/layers_{i}/{layer_name}/key/kernel"""] UpperCamelCase :str = params[f"""{prefix}/layers_{i}/{layer_name}/out/kernel"""] UpperCamelCase :Optional[int] = params[f"""{prefix}/layers_{i}/{layer_name}/query/kernel"""] UpperCamelCase :Optional[Any] = params[f"""{prefix}/layers_{i}/{layer_name}/value/kernel"""] return k, o, q, v def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : int=False ) -> Dict: """simple docstring""" if split_mlp_wi: UpperCamelCase :List[str] = params[f"""{prefix}/layers_{i}/mlp/wi_0/kernel"""] UpperCamelCase :Tuple = params[f"""{prefix}/layers_{i}/mlp/wi_1/kernel"""] UpperCamelCase :Optional[Any] = (wi_a, wi_a) else: UpperCamelCase :Union[str, Any] = params[f"""{prefix}/layers_{i}/mlp/wi/kernel"""] UpperCamelCase :str = params[f"""{prefix}/layers_{i}/mlp/wo/kernel"""] return wi, wo def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[Any] ) -> int: """simple docstring""" return params[f"""{prefix}/layers_{i}/{layer_name}/scale"""] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : dict , *, __magic_name__ : int , __magic_name__ : bool ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :str = traverse_util.flatten_dict(variables["""target"""] ) UpperCamelCase :Optional[int] = {"""/""".join(__magic_name__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase :List[str] = """encoder/layers_0/mlp/wi_0/kernel""" in old print("""Split MLP:""" , __magic_name__ ) UpperCamelCase :Tuple = collections.OrderedDict() # Shared embeddings. UpperCamelCase :str = old["""token_embedder/embedding"""] # Encoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :int = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = tax_attention_lookup(__magic_name__ , __magic_name__ , """encoder""" , """attention""" ) UpperCamelCase :List[str] = layer_norm UpperCamelCase :Tuple = k.T UpperCamelCase :List[Any] = o.T UpperCamelCase :Tuple = q.T UpperCamelCase :List[Any] = v.T # Block i, layer 1 (MLP). UpperCamelCase :str = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :int = tax_mlp_lookup(__magic_name__ , __magic_name__ , """encoder""" , __magic_name__ ) UpperCamelCase :Optional[int] = layer_norm if split_mlp_wi: UpperCamelCase :Optional[Any] = wi[0].T UpperCamelCase :Optional[Any] = wi[1].T else: UpperCamelCase :List[str] = wi.T UpperCamelCase :Any = wo.T UpperCamelCase :Union[str, Any] = old[ """encoder/relpos_bias/rel_embedding""" ].T UpperCamelCase :Union[str, Any] = old["""encoder/encoder_norm/scale"""] if not is_encoder_only: # Decoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :str = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_self_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """self_attention""" ) UpperCamelCase :int = layer_norm UpperCamelCase :List[str] = k.T UpperCamelCase :Optional[int] = o.T UpperCamelCase :Tuple = q.T UpperCamelCase :Union[str, Any] = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase :Tuple = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_cross_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[int] = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """encoder_decoder_attention""" ) UpperCamelCase :Tuple = layer_norm UpperCamelCase :List[Any] = k.T UpperCamelCase :Dict = o.T UpperCamelCase :str = q.T UpperCamelCase :Optional[Any] = v.T # Block i, layer 2 (MLP). UpperCamelCase :Tuple = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :Optional[Any] = tax_mlp_lookup(__magic_name__ , __magic_name__ , """decoder""" , __magic_name__ ) UpperCamelCase :int = layer_norm if split_mlp_wi: UpperCamelCase :Dict = wi[0].T UpperCamelCase :Union[str, Any] = wi[1].T else: UpperCamelCase :Tuple = wi.T UpperCamelCase :str = wo.T UpperCamelCase :Union[str, Any] = old["""decoder/decoder_norm/scale"""] UpperCamelCase :str = old[ """decoder/relpos_bias/rel_embedding""" ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase :Union[str, Any] = old["""decoder/logits_dense/kernel"""].T return new def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : bool ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :Optional[Any] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase :Optional[int] = state_dict["""shared.weight"""] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase :Dict = state_dict["""shared.weight"""] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("""Using shared word embeddings as lm_head.""" ) UpperCamelCase :List[Any] = state_dict["""shared.weight"""] return state_dict def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : List[str] ) -> int: """simple docstring""" UpperCamelCase :List[str] = checkpoints.load_tax_checkpoint(__magic_name__ ) UpperCamelCase :Tuple = convert_tax_to_pytorch(__magic_name__ , num_layers=config.num_layers , is_encoder_only=__magic_name__ ) UpperCamelCase :int = make_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ , strict=__magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : bool = False ) -> Tuple: """simple docstring""" UpperCamelCase :List[str] = TaConfig.from_json_file(__magic_name__ ) print(f"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase :Any = TaEncoderModel(__magic_name__ ) else: UpperCamelCase :str = TaForConditionalGeneration(__magic_name__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__magic_name__ ) # Verify that we can load the checkpoint. model.from_pretrained(__magic_name__ ) print("""Done""" ) if __name__ == "__main__": UpperCAmelCase_ : int = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis 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_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) UpperCAmelCase_ : Tuple = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, 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 _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = ShapEImgaImgPipeline snake_case__ : Optional[Any] = ["""image"""] snake_case__ : Union[str, Any] = ["""image"""] snake_case__ : Optional[Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case__ : List[str] = False @property def _A ( self : Any ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Optional[Any] ): return self.time_input_dim * 4 @property def _A ( self : Union[str, Any] ): return 8 @property def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCamelCase :Optional[int] = CLIPVisionModel(__lowerCamelCase ) return model @property def _A ( self : str ): UpperCamelCase :Optional[int] = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def _A ( self : Tuple ): torch.manual_seed(0 ) UpperCamelCase :Dict = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase :int = PriorTransformer(**__lowerCamelCase ) return model @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) UpperCamelCase :str = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase :List[str] = ShapERenderer(**__lowerCamelCase ) return model def _A ( self : str ): UpperCamelCase :int = self.dummy_prior UpperCamelCase :Any = self.dummy_image_encoder UpperCamelCase :Dict = self.dummy_image_processor UpperCamelCase :List[Any] = self.dummy_renderer UpperCamelCase :int = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__lowerCamelCase , clip_sample=__lowerCamelCase , clip_sample_range=1.0 , ) UpperCamelCase :Optional[Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def _A ( self : int , __lowerCamelCase : int , __lowerCamelCase : Any=0 ): UpperCamelCase :Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :List[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _A ( self : List[str] ): UpperCamelCase :Dict = """cpu""" UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) UpperCamelCase :Dict = output.images[0] UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase :Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : List[Any] ): # 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 : List[Any] ): UpperCamelCase :str = torch_device == """cpu""" UpperCamelCase :int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , ) def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :List[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = 1 UpperCamelCase :int = 2 UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase :str = batch_size * [inputs[key]] UpperCamelCase :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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Any ): UpperCamelCase :Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCamelCase :Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( __lowerCamelCase , generator=__lowerCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
38
1
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand UpperCAmelCase_ : Dict = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) UpperCAmelCase_ : List[Any] = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) UpperCAmelCase_ : Tuple = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) UpperCAmelCase_ : Union[str, Any] = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) UpperCAmelCase_ : Optional[int] = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 14]), ('''2H 5D 3C AS 5S''', False, [14, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [14, 13, 12, 11, 10]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) UpperCAmelCase_ : int = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) UpperCAmelCase_ : str = ( ('''JH AH TH KH QH''', 23), ('''JH 9H TH KH QH''', 22), ('''JC KH JS JD JH''', 21), ('''KH KC 3S 3H 3D''', 20), ('''8C 9C 5C 3C TC''', 19), ('''JS QS 9H TS KH''', 18), ('''7C 7S KH 2H 7H''', 17), ('''3C KH 5D 5S KH''', 16), ('''QH 8H KD JH 8S''', 15), ('''2D 6D 9D TH 7D''', 14), ) def SCREAMING_SNAKE_CASE_ ( ) -> Dict: """simple docstring""" UpperCamelCase , UpperCamelCase :Optional[int] = randrange(len(__magic_name__ ) ), randrange(len(__magic_name__ ) ) UpperCamelCase :List[Any] = ["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] UpperCamelCase , UpperCamelCase :Any = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 100 ) -> Tuple: """simple docstring""" return (generate_random_hand() for _ in range(__magic_name__ )) @pytest.mark.parametrize("""hand, expected""" , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : int ) -> Any: """simple docstring""" assert PokerHand(__magic_name__ )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : str ) -> str: """simple docstring""" assert PokerHand(__magic_name__ )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any] ) -> int: """simple docstring""" UpperCamelCase :str = PokerHand(__magic_name__ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""" , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Tuple , __magic_name__ : Optional[Any] ) -> List[str]: """simple docstring""" assert PokerHand(__magic_name__ )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : Dict ) -> int: """simple docstring""" assert PokerHand(__magic_name__ )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : str , __magic_name__ : int ) -> Optional[Any]: """simple docstring""" assert PokerHand(__magic_name__ ).compare_with(PokerHand(__magic_name__ ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" , generate_random_hands() ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : Tuple , __magic_name__ : Dict ) -> int: """simple docstring""" assert PokerHand(__magic_name__ ).compare_with(PokerHand(__magic_name__ ) ) == expected def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" UpperCamelCase :Union[str, Any] = [PokerHand(__magic_name__ ) for hand in SORTED_HANDS] UpperCamelCase :Dict = poker_hands.copy() shuffle(__magic_name__ ) UpperCamelCase :str = chain(sorted(__magic_name__ ) ) for index, hand in enumerate(__magic_name__ ): assert hand == poker_hands[index] def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: """simple docstring""" UpperCamelCase :Dict = [PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=__magic_name__ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :Any = PokerHand("""2C 4S AS 3D 5C""" ) UpperCamelCase :Dict = True UpperCamelCase :int = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def SCREAMING_SNAKE_CASE_ ( ) -> str: """simple docstring""" UpperCamelCase :List[Any] = 0 UpperCamelCase :Dict = os.path.abspath(os.path.dirname(__magic_name__ ) ) UpperCamelCase :str = os.path.join(__magic_name__ , """poker_hands.txt""" ) with open(__magic_name__ ) as file_hand: for line in file_hand: UpperCamelCase :str = line[:14].strip() UpperCamelCase :Dict = line[15:].strip() UpperCamelCase , UpperCamelCase :Any = PokerHand(__magic_name__ ), PokerHand(__magic_name__ ) UpperCamelCase :Optional[Any] = player.compare_with(__magic_name__ ) if output == "Win": answer += 1 assert answer == 376
38
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record UpperCAmelCase_ : int = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' UpperCAmelCase_ : Optional[Any] = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' UpperCAmelCase_ : int = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any="binary" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = simple_accuracy(__magic_name__ , __magic_name__ ) UpperCamelCase :Dict = float(fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average=__magic_name__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = {} for id_pred, label in zip(__magic_name__ , __magic_name__ ): UpperCamelCase :str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCamelCase :Union[str, Any] = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase :Dict = [(pred, label)] UpperCamelCase , UpperCamelCase :Optional[int] = [], [] for question, preds_labels in question_map.items(): UpperCamelCase , UpperCamelCase :Optional[Any] = zip(*__magic_name__ ) UpperCamelCase :Optional[int] = fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average="""macro""" ) fas.append(__magic_name__ ) UpperCamelCase :int = int(sum(pred == label for pred, label in preds_labels ) == len(__magic_name__ ) ) ems.append(__magic_name__ ) UpperCamelCase :Optional[int] = float(sum(__magic_name__ ) / len(__magic_name__ ) ) UpperCamelCase :str = sum(__magic_name__ ) / len(__magic_name__ ) UpperCamelCase :Tuple = float(fa_score(y_true=__magic_name__ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : str ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _A ( self : Optional[Any] ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _A ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : str ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCamelCase :Optional[Any] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCamelCase :Tuple = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
38
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, 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 _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = ShapEImgaImgPipeline snake_case__ : Optional[Any] = ["""image"""] snake_case__ : Union[str, Any] = ["""image"""] snake_case__ : Optional[Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case__ : List[str] = False @property def _A ( self : Any ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Optional[Any] ): return self.time_input_dim * 4 @property def _A ( self : Union[str, Any] ): return 8 @property def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCamelCase :Optional[int] = CLIPVisionModel(__lowerCamelCase ) return model @property def _A ( self : str ): UpperCamelCase :Optional[int] = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def _A ( self : Tuple ): torch.manual_seed(0 ) UpperCamelCase :Dict = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase :int = PriorTransformer(**__lowerCamelCase ) return model @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) UpperCamelCase :str = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase :List[str] = ShapERenderer(**__lowerCamelCase ) return model def _A ( self : str ): UpperCamelCase :int = self.dummy_prior UpperCamelCase :Any = self.dummy_image_encoder UpperCamelCase :Dict = self.dummy_image_processor UpperCamelCase :List[Any] = self.dummy_renderer UpperCamelCase :int = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__lowerCamelCase , clip_sample=__lowerCamelCase , clip_sample_range=1.0 , ) UpperCamelCase :Optional[Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def _A ( self : int , __lowerCamelCase : int , __lowerCamelCase : Any=0 ): UpperCamelCase :Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :List[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _A ( self : List[str] ): UpperCamelCase :Dict = """cpu""" UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) UpperCamelCase :Dict = output.images[0] UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase :Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : List[Any] ): # 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 : List[Any] ): UpperCamelCase :str = torch_device == """cpu""" UpperCamelCase :int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , ) def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :List[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = 1 UpperCamelCase :int = 2 UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase :str = batch_size * [inputs[key]] UpperCamelCase :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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Any ): UpperCamelCase :Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCamelCase :Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( __lowerCamelCase , generator=__lowerCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
38
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any=13 , __lowerCamelCase : Dict=3 , __lowerCamelCase : int=224 , __lowerCamelCase : Any=30 , __lowerCamelCase : Tuple=400 , __lowerCamelCase : int=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , ): UpperCamelCase :List[Any] = size if size is not None else {"""height""": 18, """width""": 18} UpperCamelCase :str = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :Dict = num_channels UpperCamelCase :str = image_size UpperCamelCase :Dict = min_resolution UpperCamelCase :str = max_resolution UpperCamelCase :Union[str, Any] = do_resize UpperCamelCase :Optional[Any] = size UpperCamelCase :Any = do_normalize UpperCamelCase :Optional[Any] = image_mean UpperCamelCase :Tuple = image_std def _A ( self : int ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : List[Any] = ViTImageProcessor if is_vision_available() else None def _A ( self : str ): UpperCamelCase :Tuple = EfficientFormerImageProcessorTester(self ) @property def _A ( self : List[str] ): return self.image_proc_tester.prepare_image_processor_dict() def _A ( self : int ): UpperCamelCase :List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) def _A ( self : Optional[int] ): pass def _A ( self : str ): # Initialize image_processor UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :List[str] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :List[Any] = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : Union[str, Any] ): # Initialize image_processor UpperCamelCase :Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase :Dict = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :Tuple = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : List[Any] ): # Initialize image_processor UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase :List[Any] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :str = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
38
1
from math import factorial def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 100 ) -> int: """simple docstring""" return sum(int(__magic_name__ ) for x in str(factorial(__magic_name__ ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
38
from collections.abc import Generator from math import sin def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" if len(__magic_name__ ) != 32: raise ValueError("""Input must be of length 32""" ) UpperCamelCase :int = B"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bytes: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :Any = format(__magic_name__ , """08x""" )[-8:] UpperCamelCase :Union[str, Any] = B"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :str = B"""""" for char in message: bit_string += format(__magic_name__ , """08b""" ).encode("""utf-8""" ) UpperCamelCase :Any = format(len(__magic_name__ ) , """064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__magic_name__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> Generator[list[int], None, None]: """simple docstring""" if len(__magic_name__ ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 , len(__magic_name__ ) , 512 ): UpperCamelCase :Tuple = bit_string[pos : pos + 512] UpperCamelCase :Optional[int] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :List[str] = format(__magic_name__ , """032b""" ) UpperCamelCase :Any = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(__magic_name__ , 2 ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" return (a + b) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :Tuple = preprocess(__magic_name__ ) UpperCamelCase :List[str] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states UpperCamelCase :Union[str, Any] = 0X67_45_23_01 UpperCamelCase :Union[str, Any] = 0XEF_CD_AB_89 UpperCamelCase :List[str] = 0X98_BA_DC_FE UpperCamelCase :int = 0X10_32_54_76 UpperCamelCase :int = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__magic_name__ ): UpperCamelCase :Optional[Any] = aa UpperCamelCase :Any = ba UpperCamelCase :Tuple = ca UpperCamelCase :List[str] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f UpperCamelCase :int = d ^ (b & (c ^ d)) UpperCamelCase :Optional[int] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f UpperCamelCase :str = c ^ (d & (b ^ c)) UpperCamelCase :Union[str, Any] = (5 * i + 1) % 16 elif i <= 47: UpperCamelCase :str = b ^ c ^ d UpperCamelCase :Optional[int] = (3 * i + 5) % 16 else: UpperCamelCase :List[str] = c ^ (b | not_aa(__magic_name__ )) UpperCamelCase :int = (7 * i) % 16 UpperCamelCase :Dict = (f + a + added_consts[i] + block_words[g]) % 2**32 UpperCamelCase :Tuple = d UpperCamelCase :str = c UpperCamelCase :Tuple = b UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , left_rotate_aa(__magic_name__ , shift_amounts[i] ) ) # Add hashed chunk to running total UpperCamelCase :List[str] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :str = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :int = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
38
1
import copy import re class _SCREAMING_SNAKE_CASE : snake_case__ : str = """hp""" snake_case__ : Dict = {} snake_case__ : Tuple = None @classmethod def _A ( cls : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int ): UpperCamelCase :List[str] = prefix UpperCamelCase :List[str] = defaults cls.build_naming_info() @staticmethod def _A ( __lowerCamelCase : Tuple , __lowerCamelCase : Tuple ): if len(__lowerCamelCase ) == 0: return "" UpperCamelCase :Union[str, Any] = None if any(char.isdigit() for char in word ): raise Exception(F"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__lowerCamelCase ) + 1 ): UpperCamelCase :Any = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCamelCase :Optional[Any] = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__lowerCamelCase : Optional[Any] ): UpperCamelCase :Optional[int] = """""" while integer != 0: UpperCamelCase :List[str] = chr(ord("""A""" ) + integer % 10 ) + s integer //= 10 return s UpperCamelCase :Tuple = 0 while True: UpperCamelCase :List[Any] = word + """#""" + int_to_alphabetic(__lowerCamelCase ) if sword in info["reverse_short_word"]: continue else: UpperCamelCase :List[str] = sword break UpperCamelCase :Dict = short_word UpperCamelCase :Optional[Any] = word return short_word @staticmethod def _A ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Any = param_name.split("""_""" ) UpperCamelCase :int = [TrialShortNamer.shortname_for_word(__lowerCamelCase , __lowerCamelCase ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCamelCase :Tuple = ["""""", """_"""] for separator in separators: UpperCamelCase :List[str] = separator.join(__lowerCamelCase ) if shortname not in info["reverse_short_param"]: UpperCamelCase :List[Any] = shortname UpperCamelCase :List[Any] = param_name return shortname return param_name @staticmethod def _A ( __lowerCamelCase : str , __lowerCamelCase : Dict ): UpperCamelCase :Dict = TrialShortNamer.shortname_for_key(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Dict = short_name UpperCamelCase :int = param_name @classmethod def _A ( cls : Tuple ): if cls.NAMING_INFO is not None: return UpperCamelCase :Optional[Any] = { """short_word""": {}, """reverse_short_word""": {}, """short_param""": {}, """reverse_short_param""": {}, } UpperCamelCase :Any = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :int = info @classmethod def _A ( cls : Dict , __lowerCamelCase : Optional[Any] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCamelCase :Any = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCamelCase :int = cls.NAMING_INFO["""short_param"""][k] if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = 1 if v else 0 UpperCamelCase :int = """""" if isinstance(__lowerCamelCase , (int, float) ) else """-""" UpperCamelCase :Dict = F"""{key}{sep}{v}""" name.append(__lowerCamelCase ) return "_".join(__lowerCamelCase ) @classmethod def _A ( cls : Tuple , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCamelCase :Union[str, Any] = [] else: UpperCamelCase :Any = repr.split("""_""" ) UpperCamelCase :List[str] = {} for value in values: if "-" in value: UpperCamelCase , UpperCamelCase :Dict = value.split("""-""" ) else: UpperCamelCase :Union[str, Any] = re.sub("""[0-9.]""" , """""" , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = float(re.sub("""[^0-9.]""" , """""" , __lowerCamelCase ) ) UpperCamelCase :Any = cls.NAMING_INFO["""reverse_short_param"""][p_k] UpperCamelCase :str = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCamelCase :Tuple = cls.DEFAULTS[k] return parameters
38
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[Any] , __lowerCamelCase : Callable , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[dict] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : List[Any] , ): super().__init__( features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = Generator( cache_dir=__lowerCamelCase , features=__lowerCamelCase , generator=__lowerCamelCase , gen_kwargs=__lowerCamelCase , **__lowerCamelCase , ) def _A ( self : List[str] ): # Build iterable dataset if self.streaming: UpperCamelCase :Any = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: UpperCamelCase :Tuple = None UpperCamelCase :Dict = None UpperCamelCase :Dict = None UpperCamelCase :List[str] = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) UpperCamelCase :Tuple = self.builder.as_dataset( split="""train""" , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
38
1
import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor UpperCAmelCase_ : List[str] = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[Any] , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : str ): warnings.warn( """The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ChineseCLIPImageProcessor instead.""" , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
38
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase_ : Union[str, Any] = 16 UpperCAmelCase_ : int = 32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 , __magic_name__ : str = "bert-base-cased" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = AutoTokenizer.from_pretrained(__magic_name__ ) UpperCamelCase :Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__magic_name__ : Tuple ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase :List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__magic_name__ , max_length=__magic_name__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase :List[Any] = datasets.map( __magic_name__ , batched=__magic_name__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__magic_name__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase :Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__magic_name__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__magic_name__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__magic_name__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase :List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) UpperCamelCase :List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase :Union[str, Any] = config["""lr"""] UpperCamelCase :List[str] = int(config["""num_epochs"""] ) UpperCamelCase :str = int(config["""seed"""] ) UpperCamelCase :Dict = int(config["""batch_size"""] ) UpperCamelCase :Union[str, Any] = args.model_name_or_path set_seed(__magic_name__ ) UpperCamelCase , UpperCamelCase :Dict = get_dataloaders(__magic_name__ , __magic_name__ , __magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase :List[str] = AutoModelForSequenceClassification.from_pretrained(__magic_name__ , return_dict=__magic_name__ ) # Instantiate optimizer UpperCamelCase :Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase :Optional[Any] = optimizer_cls(params=model.parameters() , lr=__magic_name__ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase :Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase :Any = 1 UpperCamelCase :Dict = (len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase :List[Any] = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=0 , num_training_steps=__magic_name__ , ) else: UpperCamelCase :Any = DummyScheduler(__magic_name__ , total_num_steps=__magic_name__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase :int = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase :Tuple = 0 # Now we train the model UpperCamelCase :Any = evaluate.load("""glue""" , """mrpc""" ) UpperCamelCase :Tuple = 0 UpperCamelCase :List[Any] = {} for epoch in range(__magic_name__ , __magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): UpperCamelCase :List[str] = model(**__magic_name__ ) UpperCamelCase :Dict = outputs.loss UpperCamelCase :Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__magic_name__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCamelCase :str = 0 for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__magic_name__ ) UpperCamelCase :List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase , UpperCamelCase :Optional[int] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__magic_name__ ) - 1: UpperCamelCase :Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) UpperCamelCase :List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __magic_name__ ) UpperCamelCase :Dict = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCamelCase :str = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :List[str] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__magic_name__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__magic_name__ , ) parser.add_argument( """--output_dir""" , type=__magic_name__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__magic_name__ , default=__magic_name__ , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__magic_name__ , default=3 , help="""Number of train epochs.""" , ) UpperCamelCase :str = parser.parse_args() UpperCamelCase :Any = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
38
1
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin UpperCAmelCase_ : Optional[Any] = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class _SCREAMING_SNAKE_CASE : def __init__( self : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str=16 , __lowerCamelCase : Any=13 , __lowerCamelCase : Optional[Any]=7 , __lowerCamelCase : Dict=14 , __lowerCamelCase : Any=10 , __lowerCamelCase : Optional[int]=19 , __lowerCamelCase : Optional[int]=5 , __lowerCamelCase : str=4 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Optional[int]=16 , __lowerCamelCase : str=2 , __lowerCamelCase : List[Any]=4 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Optional[int]="gelu" , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Optional[int]=[1, 2, 3, 4, 5] , __lowerCamelCase : Tuple=25 , __lowerCamelCase : str=5 , ): UpperCamelCase :Any = d_model UpperCamelCase :Dict = parent UpperCamelCase :List[str] = batch_size UpperCamelCase :Optional[int] = prediction_length UpperCamelCase :List[str] = context_length UpperCamelCase :List[Any] = cardinality UpperCamelCase :Tuple = num_time_features UpperCamelCase :List[Any] = lags_sequence UpperCamelCase :List[str] = embedding_dimension UpperCamelCase :Optional[int] = is_training UpperCamelCase :List[str] = hidden_size UpperCamelCase :List[Any] = num_hidden_layers UpperCamelCase :Tuple = num_attention_heads UpperCamelCase :int = intermediate_size UpperCamelCase :Union[str, Any] = hidden_act UpperCamelCase :Optional[Any] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = context_length UpperCamelCase :Tuple = prediction_length + label_length UpperCamelCase :Tuple = label_length UpperCamelCase :List[str] = moving_average UpperCamelCase :Any = autocorrelation_factor def _A ( self : str ): return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def _A ( self : List[Any] , __lowerCamelCase : Union[str, Any] ): UpperCamelCase :str = config.context_length + max(config.lags_sequence ) UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) UpperCamelCase :int = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) UpperCamelCase :Dict = floats_tensor([self.batch_size, _past_length] ) UpperCamelCase :Optional[Any] = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs UpperCamelCase :List[Any] = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) UpperCamelCase :Any = floats_tensor([self.batch_size, config.prediction_length] ) UpperCamelCase :Union[str, Any] = { """past_values""": past_values, """static_categorical_features""": static_categorical_features, """past_time_features""": past_time_features, """past_observed_mask""": past_observed_mask, """future_time_features""": future_time_features, """future_values""": future_values, } return inputs_dict def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.get_config() UpperCamelCase :Dict = self.prepare_autoformer_inputs_dict(__lowerCamelCase ) return config, inputs_dict def _A ( self : Optional[Any] ): UpperCamelCase , UpperCamelCase :Tuple = self.prepare_config_and_inputs() return config, inputs_dict def _A ( self : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : int ): UpperCamelCase :str = AutoformerModel(config=__lowerCamelCase ).to(__lowerCamelCase ).eval() UpperCamelCase :Optional[int] = model(**__lowerCamelCase ) UpperCamelCase :str = outputs.encoder_last_hidden_state UpperCamelCase :List[Any] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :List[Any] = model.get_encoder() encoder.save_pretrained(__lowerCamelCase ) UpperCamelCase :List[Any] = AutoformerEncoder.from_pretrained(__lowerCamelCase ).to(__lowerCamelCase ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = model.create_network_inputs(**__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Any = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) UpperCamelCase :Tuple = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) UpperCamelCase :Optional[int] = encoder(inputs_embeds=__lowerCamelCase )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) UpperCamelCase :str = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) UpperCamelCase :Optional[int] = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) UpperCamelCase :Dict = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) UpperCamelCase :Any = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Optional[int] = model.get_decoder() decoder.save_pretrained(__lowerCamelCase ) UpperCamelCase :Optional[Any] = AutoformerDecoder.from_pretrained(__lowerCamelCase ).to(__lowerCamelCase ) UpperCamelCase :Optional[int] = decoder( trend=__lowerCamelCase , inputs_embeds=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : List[Any] = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () snake_case__ : str = (AutoformerForPrediction,) if is_torch_available() else () snake_case__ : List[Any] = {"""feature-extraction""": AutoformerModel} if is_torch_available() else {} snake_case__ : Optional[int] = False snake_case__ : List[str] = False snake_case__ : Any = False snake_case__ : Tuple = False snake_case__ : int = False snake_case__ : Optional[int] = False def _A ( self : Any ): UpperCamelCase :Any = AutoformerModelTester(self ) UpperCamelCase :Optional[int] = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def _A ( self : Dict ): self.config_tester.run_common_tests() def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(__lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = model_class.from_pretrained(__lowerCamelCase , output_loading_info=__lowerCamelCase ) self.assertEqual(info["""missing_keys"""] , [] ) def _A ( self : str ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__lowerCamelCase ) @unittest.skip(reason="""Model has no tokens embeddings""" ) def _A ( self : List[Any] ): pass def _A ( self : Dict ): UpperCamelCase :List[Any] = inspect.signature(getattr(__lowerCamelCase , """forward""" ) ) # The main input is the name of the argument after `self` UpperCamelCase :Optional[int] = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase , UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :int = model_class(__lowerCamelCase ) UpperCamelCase :List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Optional[int] = [*signature.parameters.keys()] UpperCamelCase :List[str] = [ """past_values""", """past_time_features""", """past_observed_mask""", """static_categorical_features""", """static_real_features""", """future_values""", """future_time_features""", ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append("""future_observed_mask""" ) expected_arg_names.extend( [ """decoder_attention_mask""", """head_mask""", """decoder_head_mask""", """cross_attn_head_mask""", """encoder_outputs""", """past_key_values""", """output_hidden_states""", """output_attentions""", """use_cache""", """return_dict""", ] ) self.assertListEqual(arg_names[: len(__lowerCamelCase )] , __lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = True UpperCamelCase :Optional[int] = getattr(self.model_tester , """seq_length""" , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = getattr(self.model_tester , """decoder_seq_length""" , __lowerCamelCase ) UpperCamelCase :List[str] = getattr(self.model_tester , """encoder_seq_length""" , __lowerCamelCase ) UpperCamelCase :str = getattr(self.model_tester , """d_model""" , __lowerCamelCase ) UpperCamelCase :str = getattr(self.model_tester , """num_attention_heads""" , __lowerCamelCase ) UpperCamelCase :List[Any] = d_model // num_attention_heads for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = True UpperCamelCase :Tuple = False UpperCamelCase :List[str] = True UpperCamelCase :Any = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :List[Any] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) UpperCamelCase :int = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCamelCase :List[Any] = True UpperCamelCase :Tuple = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :Dict = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) UpperCamelCase :List[Any] = outputs.encoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) UpperCamelCase :int = len(__lowerCamelCase ) UpperCamelCase :Dict = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(__lowerCamelCase , __lowerCamelCase ) # decoder attentions UpperCamelCase :Optional[int] = outputs.decoder_attentions self.assertIsInstance(__lowerCamelCase , (list, tuple) ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions UpperCamelCase :Union[str, Any] = outputs.cross_attentions self.assertIsInstance(__lowerCamelCase , (list, tuple) ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine UpperCamelCase :Dict = True UpperCamelCase :Optional[Any] = True UpperCamelCase :Tuple = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase :str = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + 2 , len(__lowerCamelCase ) ) UpperCamelCase :Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def _A ( self : str ): super().test_retain_grad_hidden_states_attentions() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict="train-batch.pt" ) -> int: """simple docstring""" UpperCamelCase :Tuple = hf_hub_download(repo_id="""hf-internal-testing/tourism-monthly-batch""" , filename=__magic_name__ , repo_type="""dataset""" ) UpperCamelCase :Optional[int] = torch.load(__magic_name__ , map_location=__magic_name__ ) return batch @require_torch @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : str ): UpperCamelCase :Optional[Any] = AutoformerModel.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(__lowerCamelCase ) UpperCamelCase :int = prepare_batch() with torch.no_grad(): UpperCamelCase :Any = model( past_values=batch["""past_values"""] , past_time_features=batch["""past_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , static_categorical_features=batch["""static_categorical_features"""] , future_values=batch["""future_values"""] , future_time_features=batch["""future_time_features"""] , )[0] UpperCamelCase :int = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :Optional[int] = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=__lowerCamelCase ) self.assertTrue(torch.allclose(output[0, :3, :3] , __lowerCamelCase , atol=__lowerCamelCase ) ) def _A ( self : Union[str, Any] ): UpperCamelCase :str = AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(__lowerCamelCase ) UpperCamelCase :Any = prepare_batch("""val-batch.pt""" ) with torch.no_grad(): UpperCamelCase :Optional[Any] = model( past_values=batch["""past_values"""] , past_time_features=batch["""past_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , static_categorical_features=batch["""static_categorical_features"""] , ).encoder_last_hidden_state UpperCamelCase :str = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=__lowerCamelCase ) self.assertTrue(torch.allclose(output[0, :3, :3] , __lowerCamelCase , atol=__lowerCamelCase ) ) def _A ( self : Dict ): UpperCamelCase :List[str] = AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(__lowerCamelCase ) UpperCamelCase :str = prepare_batch("""val-batch.pt""" ) with torch.no_grad(): UpperCamelCase :str = model.generate( static_categorical_features=batch["""static_categorical_features"""] , past_time_features=batch["""past_time_features"""] , past_values=batch["""past_values"""] , future_time_features=batch["""future_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , ) UpperCamelCase :Union[str, Any] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , __lowerCamelCase ) UpperCamelCase :Any = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , __lowerCamelCase , rtol=1E-1 ) )
38
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[Any] = TransfoXLTokenizer snake_case__ : List[Any] = False snake_case__ : Tuple = False def _A ( self : str ): super().setUp() UpperCamelCase :Dict = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _A ( self : List[str] , **__lowerCamelCase : Any ): UpperCamelCase :Any = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : int ): UpperCamelCase :List[Any] = """<unk> UNwanted , running""" UpperCamelCase :int = """<unk> unwanted, running""" return input_text, output_text def _A ( self : Tuple ): UpperCamelCase :List[str] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__lowerCamelCase ) UpperCamelCase :Any = tokenizer.tokenize("""<unk> UNwanted , running""" ) self.assertListEqual(__lowerCamelCase , ["""<unk>""", """unwanted""", """,""", """running"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [0, 4, 8, 7] ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _A ( self : Tuple ): UpperCamelCase :Any = TransfoXLTokenizer(lower_case=__lowerCamelCase ) UpperCamelCase :Optional[int] = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" UpperCamelCase :Optional[int] = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(__lowerCamelCase ) , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = len(__lowerCamelCase ) tokenizer.add_tokens(["""new1""", """new2"""] ) tokenizer.move_added_token("""new1""" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , """new1""" )
38
1
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html UpperCAmelCase_ : Tuple = '''platform''' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : List[str]=None , __magic_name__ : List[str]=None , __magic_name__ : int=None , __magic_name__ : Optional[int]=None , __magic_name__ : int=None , __magic_name__ : int=None , ) -> Optional[Any]: """simple docstring""" if attention_mask is None: UpperCamelCase :List[str] = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: UpperCamelCase :Union[str, Any] = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: UpperCamelCase :int = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase :Union[str, Any] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase :List[Any] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class _SCREAMING_SNAKE_CASE : def __init__( self : str , __lowerCamelCase : Dict , __lowerCamelCase : Any=13 , __lowerCamelCase : str=7 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : int=99 , __lowerCamelCase : List[Any]=16 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Dict=4 , __lowerCamelCase : int="gelu" , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Optional[Any]=0.1 , __lowerCamelCase : Optional[int]=32 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Dict=1 , __lowerCamelCase : List[Any]=0 , __lowerCamelCase : int=0.02 , ): UpperCamelCase :List[str] = parent UpperCamelCase :Any = batch_size UpperCamelCase :Dict = seq_length UpperCamelCase :Union[str, Any] = is_training UpperCamelCase :Union[str, Any] = use_labels UpperCamelCase :int = vocab_size UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :str = num_hidden_layers UpperCamelCase :Tuple = num_attention_heads UpperCamelCase :List[Any] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :Optional[Any] = attention_probs_dropout_prob UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :Optional[int] = eos_token_id UpperCamelCase :Any = pad_token_id UpperCamelCase :Dict = bos_token_id UpperCamelCase :Tuple = initializer_range def _A ( self : Tuple ): UpperCamelCase :Dict = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) UpperCamelCase :Any = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) UpperCamelCase :Union[str, Any] = shift_tokens_right(__lowerCamelCase , 1 , 2 ) UpperCamelCase :Tuple = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=__lowerCamelCase , ) UpperCamelCase :List[Any] = prepare_blenderbot_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, inputs_dict def _A ( self : Dict ): UpperCamelCase , UpperCamelCase :int = self.prepare_config_and_inputs() return config, inputs_dict def _A ( self : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ): UpperCamelCase :Optional[Any] = 20 UpperCamelCase :List[Any] = model_class_name(__lowerCamelCase ) UpperCamelCase :List[str] = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase , UpperCamelCase :List[str] = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase :Optional[Any] = model.init_cache(decoder_input_ids.shape[0] , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) UpperCamelCase :int = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase :Optional[Any] = model.decode( decoder_input_ids[:, :-1] , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase , decoder_position_ids=__lowerCamelCase , ) UpperCamelCase :Tuple = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase :Optional[int] = model.decode( decoder_input_ids[:, -1:] , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__lowerCamelCase , ) UpperCamelCase :Tuple = model.decode(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Dict = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def _A ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ): UpperCamelCase :str = 20 UpperCamelCase :str = model_class_name(__lowerCamelCase ) UpperCamelCase :int = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase , UpperCamelCase :Optional[int] = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase :int = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) UpperCamelCase :str = model.init_cache(decoder_input_ids.shape[0] , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase :int = model.decode( decoder_input_ids[:, :-1] , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase , decoder_position_ids=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase :Union[str, Any] = model.decode( decoder_input_ids[:, -1:] , __lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__lowerCamelCase , decoder_position_ids=__lowerCamelCase , ) UpperCamelCase :Tuple = model.decode(__lowerCamelCase , __lowerCamelCase , decoder_attention_mask=__lowerCamelCase ) UpperCamelCase :Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case__ : Optional[Any] = 9_9 def _A ( self : List[str] ): UpperCamelCase :int = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) UpperCamelCase :Dict = input_ids.shape[0] UpperCamelCase :List[str] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def _A ( self : List[str] ): UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = self._get_config_and_data() UpperCamelCase :List[Any] = FlaxBlenderbotForConditionalGeneration(__lowerCamelCase ) UpperCamelCase :List[Any] = lm_model(input_ids=__lowerCamelCase ) UpperCamelCase :str = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["""logits"""].shape , __lowerCamelCase ) def _A ( self : Dict ): UpperCamelCase :List[str] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) UpperCamelCase :List[Any] = FlaxBlenderbotForConditionalGeneration(__lowerCamelCase ) UpperCamelCase :List[str] = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) UpperCamelCase :Optional[int] = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) UpperCamelCase :List[Any] = lm_model(input_ids=__lowerCamelCase , decoder_input_ids=__lowerCamelCase ) UpperCamelCase :Tuple = (*summary.shape, config.vocab_size) self.assertEqual(outputs["""logits"""].shape , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :int = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) UpperCamelCase :Optional[int] = shift_tokens_right(__lowerCamelCase , 1 , 2 ) UpperCamelCase :Dict = np.equal(__lowerCamelCase , 1 ).astype(np.floataa ).sum() UpperCamelCase :Dict = np.equal(__lowerCamelCase , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(__lowerCamelCase , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase , _a ): snake_case__ : Optional[int] = True snake_case__ : Optional[int] = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def _A ( self : Optional[Any] ): UpperCamelCase :List[str] = FlaxBlenderbotModelTester(self ) def _A ( self : Any ): UpperCamelCase , UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _A ( self : List[str] ): UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase :Any = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :List[str] = model_class(__lowerCamelCase ) @jax.jit def encode_jitted(__lowerCamelCase : Any , __lowerCamelCase : str=None , **__lowerCamelCase : Any ): return model.encode(input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase ) with self.subTest("""JIT Enabled""" ): UpperCamelCase :Optional[Any] = encode_jitted(**__lowerCamelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase :str = encode_jitted(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def _A ( self : Optional[int] ): UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase :Tuple = model_class(__lowerCamelCase ) UpperCamelCase :str = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) UpperCamelCase :Optional[int] = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(__lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple ): return model.decode( decoder_input_ids=__lowerCamelCase , decoder_attention_mask=__lowerCamelCase , encoder_outputs=__lowerCamelCase , ) with self.subTest("""JIT Enabled""" ): UpperCamelCase :int = decode_jitted(**__lowerCamelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase :str = decode_jitted(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def _A ( self : str ): for model_class_name in self.all_model_classes: UpperCamelCase :List[Any] = model_class_name.from_pretrained("""facebook/blenderbot-400M-distill""" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids UpperCamelCase :List[str] = np.ones((1, 1) ) * model.config.eos_token_id UpperCamelCase :Tuple = model(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @unittest.skipUnless(jax_device != """cpu""" , """3B test too slow on CPU.""" ) @slow def _A ( self : Any ): UpperCamelCase :Any = {"""num_beams""": 1, """early_stopping""": True, """min_length""": 15, """max_length""": 25} UpperCamelCase :List[Any] = {"""skip_special_tokens""": True, """clean_up_tokenization_spaces""": True} UpperCamelCase :Any = FlaxBlenderbotForConditionalGeneration.from_pretrained("""facebook/blenderbot-3B""" , from_pt=__lowerCamelCase ) UpperCamelCase :Optional[Any] = BlenderbotTokenizer.from_pretrained("""facebook/blenderbot-3B""" ) UpperCamelCase :Any = ["""Sam"""] UpperCamelCase :Union[str, Any] = tokenizer(__lowerCamelCase , return_tensors="""jax""" ) UpperCamelCase :Union[str, Any] = model.generate(**__lowerCamelCase , **__lowerCamelCase ) UpperCamelCase :List[Any] = """Sam is a great name. It means \"sun\" in Gaelic.""" UpperCamelCase :List[Any] = tokenizer.batch_decode(__lowerCamelCase , **__lowerCamelCase ) assert generated_txt[0].strip() == tgt_text
38
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase_ : int = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[int] ) -> Dict: """simple docstring""" for attribute in key.split(""".""" ): UpperCamelCase :Dict = getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: UpperCamelCase :Optional[int] = getattr(__magic_name__ , __magic_name__ ).shape else: UpperCamelCase :Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCamelCase :str = value elif weight_type == "weight_g": UpperCamelCase :int = value elif weight_type == "weight_v": UpperCamelCase :int = value elif weight_type == "bias": UpperCamelCase :List[Any] = value else: UpperCamelCase :Any = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Dict = fairseq_model.state_dict() UpperCamelCase :int = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase :str = False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == """group""" , ) UpperCamelCase :Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase :Optional[int] = True if "*" in mapped_key: UpperCamelCase :List[Any] = name.split(__magic_name__ )[0].split(""".""" )[-2] UpperCamelCase :int = mapped_key.replace("""*""" , __magic_name__ ) if "weight_g" in name: UpperCamelCase :List[Any] = """weight_g""" elif "weight_v" in name: UpperCamelCase :List[Any] = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase :Any = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase :List[str] = """weight""" else: UpperCamelCase :Optional[int] = None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int , __magic_name__ : List[str] ) -> Dict: """simple docstring""" UpperCamelCase :Dict = full_name.split("""conv_layers.""" )[-1] UpperCamelCase :int = name.split(""".""" ) UpperCamelCase :str = int(items[0] ) UpperCamelCase :str = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCamelCase :Dict = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCamelCase :Union[str, Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : List[Any] , __magic_name__ : str=None ) -> int: """simple docstring""" UpperCamelCase :List[Any] = torch.load(__magic_name__ ) UpperCamelCase :List[Any] = WavLMConfigOrig(checkpoint["""cfg"""] ) UpperCamelCase :int = WavLMOrig(__magic_name__ ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: UpperCamelCase :List[Any] = WavLMConfig.from_pretrained(__magic_name__ ) else: UpperCamelCase :Any = WavLMConfig() UpperCamelCase :Dict = WavLMModel(__magic_name__ ) recursively_load_weights(__magic_name__ , __magic_name__ ) hf_wavlm.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') UpperCAmelCase_ : Optional[int] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
38
1
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 SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any ) -> int: """simple docstring""" UpperCamelCase :int = filter(lambda __magic_name__ : p.requires_grad , model.parameters() ) UpperCamelCase :List[str] = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCAmelCase_ : str = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : Dict ) -> Dict: """simple docstring""" if metric == "rouge2": UpperCamelCase :Tuple = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": UpperCamelCase :List[Any] = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": UpperCamelCase :Tuple = """{val_avg_em:.4f}-{step_count}""" elif metric == "loss": UpperCamelCase :Dict = """{val_avg_loss:.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.""" ) UpperCamelCase :List[str] = ModelCheckpoint( dirpath=__magic_name__ , filename=__magic_name__ , monitor=f"""val_{metric}""" , mode="""max""" , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str ) -> Optional[int]: """simple docstring""" return EarlyStopping( monitor=f"""val_{metric}""" , mode="""min""" if """loss""" in metric else """max""" , patience=__magic_name__ , verbose=__magic_name__ , ) class _SCREAMING_SNAKE_CASE ( pl.Callback ): def _A ( self : str , __lowerCamelCase : List[Any] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = {F"""lr_group_{i}""": param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__lowerCamelCase ) @rank_zero_only def _A ( self : List[str] , __lowerCamelCase : pl.Trainer , __lowerCamelCase : pl.LightningModule , __lowerCamelCase : str , __lowerCamelCase : List[str]=True ): logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) UpperCamelCase :str = 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 UpperCamelCase :Union[str, Any] = Path(pl_module.hparams.output_dir ) if type_path == "test": UpperCamelCase :Dict = od / """test_results.txt""" UpperCamelCase :str = 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. UpperCamelCase :Any = od / F"""{type_path}_results/{trainer.global_step:05d}.txt""" UpperCamelCase :List[str] = od / F"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=__lowerCamelCase ) generations_file.parent.mkdir(exist_ok=__lowerCamelCase ) with open(__lowerCamelCase , """a+""" ) as writer: for key in sorted(__lowerCamelCase ): if key in ["log", "progress_bar", "preds"]: continue UpperCamelCase :int = metrics[key] if isinstance(__lowerCamelCase , torch.Tensor ): UpperCamelCase :Any = val.item() UpperCamelCase :Union[str, Any] = F"""{key}: {val:.6f}\n""" writer.write(__lowerCamelCase ) if not save_generations: return if "preds" in metrics: UpperCamelCase :Any = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(__lowerCamelCase ) @rank_zero_only def _A ( self : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : str ): try: UpperCamelCase :Union[str, Any] = pl_module.model.model.num_parameters() except AttributeError: UpperCamelCase :int = pl_module.model.num_parameters() UpperCamelCase :Union[str, Any] = count_trainable_parameters(__lowerCamelCase ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1E6, """grad_mp""": n_trainable_pars / 1E6} ) @rank_zero_only def _A ( self : List[str] , __lowerCamelCase : pl.Trainer , __lowerCamelCase : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__lowerCamelCase , __lowerCamelCase , """test""" ) @rank_zero_only def _A ( self : Optional[int] , __lowerCamelCase : pl.Trainer , __lowerCamelCase : Union[str, Any] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
38
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCAmelCase_ : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""bs4"""] ) super().__init__(**__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = [] UpperCamelCase :List[str] = [] UpperCamelCase :Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag UpperCamelCase :Optional[Any] = parent.find_all(child.name , recursive=__lowerCamelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCamelCase ) else next(i for i, s in enumerate(__lowerCamelCase , 1 ) if s is child ) ) UpperCamelCase :Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Any = BeautifulSoup(__lowerCamelCase , """html.parser""" ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Tuple = [] UpperCamelCase :Tuple = [] for element in html_code.descendants: if type(__lowerCamelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue UpperCamelCase :Any = html.unescape(__lowerCamelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = self.xpath_soup(__lowerCamelCase ) stringaxtag_seq.append(__lowerCamelCase ) stringaxsubs_seq.append(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Tuple = """""" for tagname, subs in zip(__lowerCamelCase , __lowerCamelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Any , __lowerCamelCase : Dict ): UpperCamelCase :Any = False # Check that strings has a valid type if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = True elif isinstance(__lowerCamelCase , (list, tuple) ): if len(__lowerCamelCase ) == 0 or isinstance(html_strings[0] , __lowerCamelCase ): UpperCamelCase :Any = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ F"""but is of type {type(__lowerCamelCase )}.""" ) UpperCamelCase :str = bool(isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(html_strings[0] , __lowerCamelCase )) ) if not is_batched: UpperCamelCase :Any = [html_strings] # Get nodes + xpaths UpperCamelCase :Union[str, Any] = [] UpperCamelCase :str = [] for html_string in html_strings: UpperCamelCase , UpperCamelCase , UpperCamelCase :int = self.get_three_from_single(__lowerCamelCase ) nodes.append(__lowerCamelCase ) UpperCamelCase :int = [] for node, tag_list, sub_list in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): UpperCamelCase :str = self.construct_xpath(__lowerCamelCase , __lowerCamelCase ) xpath_strings.append(__lowerCamelCase ) xpaths.append(__lowerCamelCase ) # return as Dict UpperCamelCase :Optional[int] = {"""nodes""": nodes, """xpaths""": xpaths} UpperCamelCase :Any = BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) return encoded_inputs
38
1
from collections import deque from .hash_table import HashTable class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Union[str, Any] , *__lowerCamelCase : Dict , **__lowerCamelCase : str ): super().__init__(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] ): UpperCamelCase :List[Any] = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__lowerCamelCase ) UpperCamelCase :List[str] = self.values[key] def _A ( self : List[Any] ): return ( sum(self.charge_factor - len(__lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def _A ( self : Tuple , __lowerCamelCase : Dict , __lowerCamelCase : Dict=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__lowerCamelCase ) == 0 ): return key return super()._collision_resolution(__lowerCamelCase , __lowerCamelCase )
38
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : list[int] ) -> bool: """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : list[int] , __magic_name__ : int ) -> bool: """simple docstring""" if curr_ind == len(__magic_name__ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__magic_name__ ) ): if valid_connection(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): # Insert current vertex into path as next transition UpperCamelCase :str = next_ver # Validate created path if util_hamilton_cycle(__magic_name__ , __magic_name__ , curr_ind + 1 ): return True # Backtrack UpperCamelCase :Union[str, Any] = -1 return False def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int = 0 ) -> list[int]: """simple docstring""" UpperCamelCase :Union[str, Any] = [-1] * (len(__magic_name__ ) + 1) # initialize start and end of path with starting index UpperCamelCase :Any = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__magic_name__ , __magic_name__ , 1 ) else []
38
1
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _SCREAMING_SNAKE_CASE : def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int]=13 , __lowerCamelCase : List[str]=7 , __lowerCamelCase : List[str]=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : int=False , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=99 , __lowerCamelCase : Optional[int]=32 , __lowerCamelCase : Dict=5 , __lowerCamelCase : List[Any]=4 , __lowerCamelCase : List[str]=37 , __lowerCamelCase : Union[str, Any]="gelu" , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Tuple=512 , __lowerCamelCase : str=16 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : str=4 , __lowerCamelCase : Union[str, Any]=None , ): UpperCamelCase :Dict = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :List[str] = seq_length UpperCamelCase :Optional[int] = is_training UpperCamelCase :int = use_input_mask UpperCamelCase :List[str] = use_token_type_ids UpperCamelCase :int = use_labels UpperCamelCase :int = vocab_size UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :Optional[Any] = num_hidden_layers UpperCamelCase :Dict = num_attention_heads UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :int = hidden_act UpperCamelCase :Dict = hidden_dropout_prob UpperCamelCase :int = attention_probs_dropout_prob UpperCamelCase :int = max_position_embeddings UpperCamelCase :List[str] = type_vocab_size UpperCamelCase :Union[str, Any] = type_sequence_label_size UpperCamelCase :Dict = initializer_range UpperCamelCase :Tuple = num_labels UpperCamelCase :Optional[Any] = num_choices UpperCamelCase :Optional[Any] = scope def _A ( self : Union[str, Any] ): UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Optional[int] = None if self.use_input_mask: UpperCamelCase :Tuple = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :Optional[Any] = None if self.use_token_type_ids: UpperCamelCase :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase :str = None UpperCamelCase :Optional[Any] = None UpperCamelCase :List[Any] = None if self.use_labels: UpperCamelCase :List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :int = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _A ( self : Optional[Any] ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , ) def _A ( self : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ): UpperCamelCase :Optional[Any] = LlamaModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :List[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase ) UpperCamelCase :Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : str , ): UpperCamelCase :Optional[int] = True UpperCamelCase :Any = LlamaModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :List[Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , ) UpperCamelCase :Optional[Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , ) UpperCamelCase :Dict = model(__lowerCamelCase , attention_mask=__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : str , ): UpperCamelCase :str = LlamaForCausalLM(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :List[str] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : str , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , ): UpperCamelCase :str = True UpperCamelCase :List[Any] = True UpperCamelCase :Optional[Any] = LlamaForCausalLM(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() # first forward pass UpperCamelCase :Any = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , use_cache=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase :str = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase :List[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and UpperCamelCase :Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase :List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) UpperCamelCase :Optional[Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , output_hidden_states=__lowerCamelCase , )["""hidden_states"""][0] UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase , output_hidden_states=__lowerCamelCase , )["""hidden_states"""][0] # select random slice UpperCamelCase :int = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase :str = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase :List[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) ) def _A ( self : Any ): UpperCamelCase :Union[str, Any] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Tuple = config_and_inputs UpperCamelCase :Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , _a , unittest.TestCase ): snake_case__ : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () snake_case__ : List[str] = (LlamaForCausalLM,) if is_torch_available() else () snake_case__ : Any = ( { """feature-extraction""": LlamaModel, """text-classification""": LlamaForSequenceClassification, """text-generation""": LlamaForCausalLM, """zero-shot""": LlamaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : Tuple = False def _A ( self : str ): UpperCamelCase :str = LlamaModelTester(self ) UpperCamelCase :Optional[Any] = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=37 ) def _A ( self : Tuple ): self.config_tester.run_common_tests() def _A ( self : List[str] ): UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _A ( self : List[str] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase :Any = type self.model_tester.create_and_check_model(*__lowerCamelCase ) def _A ( self : List[str] ): UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = 3 UpperCamelCase :Dict = input_dict["""input_ids"""] UpperCamelCase :List[Any] = input_ids.ne(1 ).to(__lowerCamelCase ) UpperCamelCase :List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase :Dict = LlamaForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _A ( self : Optional[Any] ): UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :List[str] = 3 UpperCamelCase :Optional[int] = """single_label_classification""" UpperCamelCase :Optional[Any] = input_dict["""input_ids"""] UpperCamelCase :Union[str, Any] = input_ids.ne(1 ).to(__lowerCamelCase ) UpperCamelCase :Optional[int] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase :Union[str, Any] = LlamaForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Union[str, Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _A ( self : List[str] ): UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = 3 UpperCamelCase :Optional[Any] = """multi_label_classification""" UpperCamelCase :List[str] = input_dict["""input_ids"""] UpperCamelCase :str = input_ids.ne(1 ).to(__lowerCamelCase ) UpperCamelCase :Tuple = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase :Tuple = LlamaForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""LLaMA buffers include complex numbers, which breaks this test""" ) def _A ( self : Union[str, Any] ): pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _A ( self : Optional[int] , __lowerCamelCase : Optional[int] ): UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :str = ids_tensor([1, 10] , config.vocab_size ) UpperCamelCase :Optional[int] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights UpperCamelCase :Dict = LlamaModel(__lowerCamelCase ) original_model.to(__lowerCamelCase ) original_model.eval() UpperCamelCase :Any = original_model(__lowerCamelCase ).last_hidden_state UpperCamelCase :Union[str, Any] = original_model(__lowerCamelCase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights UpperCamelCase :List[str] = {"""type""": scaling_type, """factor""": 10.0} UpperCamelCase :List[str] = LlamaModel(__lowerCamelCase ) scaled_model.to(__lowerCamelCase ) scaled_model.eval() UpperCamelCase :Union[str, Any] = scaled_model(__lowerCamelCase ).last_hidden_state UpperCamelCase :List[str] = scaled_model(__lowerCamelCase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-5 ) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _A ( self : List[str] ): UpperCamelCase :Any = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] UpperCamelCase :Tuple = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf""" , device_map="""auto""" ) UpperCamelCase :str = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 UpperCamelCase :Dict = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) , __lowerCamelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off UpperCamelCase :str = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __lowerCamelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _A ( self : Tuple ): UpperCamelCase :Dict = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] UpperCamelCase :Tuple = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf""" , device_map="""auto""" ) UpperCamelCase :List[Any] = model(torch.tensor(__lowerCamelCase ) ) # Expected mean on dim = -1 UpperCamelCase :Tuple = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) , __lowerCamelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off UpperCamelCase :List[Any] = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __lowerCamelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def _A ( self : Optional[int] ): UpperCamelCase :Union[str, Any] = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] UpperCamelCase :Dict = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" , device_map="""auto""" ) UpperCamelCase :Union[str, Any] = model(torch.tensor(__lowerCamelCase ) ) # Expected mean on dim = -1 UpperCamelCase :Tuple = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) , __lowerCamelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off UpperCamelCase :Optional[Any] = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , __lowerCamelCase , atol=1E-2 , rtol=1E-2 ) @unittest.skip( """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test""" ) @slow def _A ( self : Union[str, Any] ): UpperCamelCase :Dict = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] UpperCamelCase :Union[str, Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf""" , device_map="""auto""" ) UpperCamelCase :Optional[Any] = model(torch.tensor(__lowerCamelCase ) ) UpperCamelCase :Any = torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , __lowerCamelCase , atol=1E-2 , rtol=1E-2 ) # fmt: off UpperCamelCase :str = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __lowerCamelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Model is curently gated""" ) @slow def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" UpperCamelCase :str = """Simply put, the theory of relativity states that """ UpperCamelCase :Optional[int] = LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ) UpperCamelCase :Union[str, Any] = tokenizer.encode(__lowerCamelCase , return_tensors="""pt""" ) UpperCamelCase :int = LlamaForCausalLM.from_pretrained( """meta-llama/Llama-2-13b-chat-hf""" , device_map="""sequential""" , use_safetensors=__lowerCamelCase ) # greedy generation outputs UpperCamelCase :Any = model.generate(__lowerCamelCase , max_new_tokens=64 , top_p=__lowerCamelCase , temperature=1 , do_sample=__lowerCamelCase ) UpperCamelCase :List[Any] = tokenizer.decode(generated_ids[0] , skip_special_tokens=__lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase )
38
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : str=7 , __lowerCamelCase : Tuple=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Any=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : str=False , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : Any=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : List[Any]=12 , __lowerCamelCase : int=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Optional[int]="last" , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[str]=None , ): UpperCamelCase :int = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :str = seq_length UpperCamelCase :Optional[int] = is_training UpperCamelCase :Optional[int] = use_input_lengths UpperCamelCase :Union[str, Any] = use_token_type_ids UpperCamelCase :List[str] = use_labels UpperCamelCase :Dict = gelu_activation UpperCamelCase :Optional[int] = sinusoidal_embeddings UpperCamelCase :List[Any] = causal UpperCamelCase :Optional[int] = asm UpperCamelCase :List[str] = n_langs UpperCamelCase :int = vocab_size UpperCamelCase :List[Any] = n_special UpperCamelCase :List[Any] = hidden_size UpperCamelCase :List[str] = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :Tuple = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :List[str] = type_vocab_size UpperCamelCase :Union[str, Any] = type_sequence_label_size UpperCamelCase :int = initializer_range UpperCamelCase :List[str] = num_labels UpperCamelCase :Optional[int] = num_choices UpperCamelCase :Optional[Any] = summary_type UpperCamelCase :Tuple = use_proj UpperCamelCase :Optional[Any] = scope def _A ( self : List[str] ): UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Any = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :List[Any] = None if self.use_input_lengths: UpperCamelCase :Dict = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase :str = None if self.use_token_type_ids: UpperCamelCase :int = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase :Optional[int] = None UpperCamelCase :int = None UpperCamelCase :List[Any] = None if self.use_labels: UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :List[str] = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase :List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _A ( self : List[Any] ): return 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 , ) def _A ( self : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : int , ): UpperCamelCase :Tuple = FlaubertModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :int = model(__lowerCamelCase , lengths=__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :List[Any] = model(__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , ): UpperCamelCase :Any = FlaubertWithLMHeadModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Dict = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Any = FlaubertForQuestionAnsweringSimple(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) 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 _A ( self : str , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : str , ): UpperCamelCase :str = FlaubertForQuestionAnswering(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :Optional[int] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , p_mask=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , ) ((UpperCamelCase) , ) :int = result_with_labels.to_tuple() UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) ((UpperCamelCase) , ) :List[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , ): UpperCamelCase :Optional[int] = FlaubertForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Tuple = model(__lowerCamelCase ) UpperCamelCase :List[str] = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A ( self : Any , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Dict = self.num_labels UpperCamelCase :Tuple = FlaubertForTokenClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Union[str, Any] = self.num_choices UpperCamelCase :List[Any] = FlaubertForMultipleChoice(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A ( self : str ): UpperCamelCase :List[str] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :List[Any] = config_and_inputs UpperCamelCase :Union[str, Any] = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[int] = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _A ( self : int , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ): 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 _A ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ): UpperCamelCase :Tuple = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": UpperCamelCase :Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) UpperCamelCase :List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def _A ( self : str ): UpperCamelCase :List[Any] = FlaubertModelTester(self ) UpperCamelCase :Any = ConfigTester(self , config_class=__lowerCamelCase , emb_dim=37 ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__lowerCamelCase ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__lowerCamelCase ) def _A ( self : int ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__lowerCamelCase ) @slow def _A ( self : Any ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Optional[int] = FlaubertModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @slow @require_torch_gpu def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = model_class(config=__lowerCamelCase ) UpperCamelCase :str = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :str = torch.jit.trace( __lowerCamelCase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__lowerCamelCase , os.path.join(__lowerCamelCase , """traced_model.pt""" ) ) UpperCamelCase :int = torch.jit.load(os.path.join(__lowerCamelCase , """traced_model.pt""" ) , map_location=__lowerCamelCase ) loaded(inputs_dict["""input_ids"""].to(__lowerCamelCase ) , inputs_dict["""attention_mask"""].to(__lowerCamelCase ) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) UpperCamelCase :Optional[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): UpperCamelCase :Tuple = model(__lowerCamelCase )[0] UpperCamelCase :Union[str, Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :int = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
38
1
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters UpperCAmelCase_ : Optional[Any] = (7_20, 12_80) # Height, Width UpperCAmelCase_ : List[str] = (0.4, 0.6) # if height or width lower than this scale, drop it. UpperCAmelCase_ : int = 1 / 1_00 UpperCAmelCase_ : int = '''''' UpperCAmelCase_ : List[str] = '''''' UpperCAmelCase_ : Optional[Any] = '''''' UpperCAmelCase_ : str = 2_50 def SCREAMING_SNAKE_CASE_ ( ) -> None: """simple docstring""" UpperCamelCase , UpperCamelCase :int = get_dataset(__magic_name__ , __magic_name__ ) for index in range(__magic_name__ ): UpperCamelCase :int = random.sample(range(len(__magic_name__ ) ) , 4 ) UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = update_image_and_anno( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , filter_scale=__magic_name__ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' UpperCamelCase :List[Any] = random_chars(32 ) UpperCamelCase :Any = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] UpperCamelCase :Tuple = f"""{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}""" cva.imwrite(f"""{file_root}.jpg""" , __magic_name__ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"""Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}""" ) UpperCamelCase :List[str] = [] for anno in new_annos: UpperCamelCase :int = anno[3] - anno[1] UpperCamelCase :Optional[int] = anno[4] - anno[2] UpperCamelCase :List[Any] = anno[1] + width / 2 UpperCamelCase :Union[str, Any] = anno[2] + height / 2 UpperCamelCase :int = f"""{anno[0]} {x_center} {y_center} {width} {height}""" annos_list.append(__magic_name__ ) with open(f"""{file_root}.txt""" , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : str ) -> tuple[list, list]: """simple docstring""" UpperCamelCase :Tuple = [] UpperCamelCase :str = [] for label_file in glob.glob(os.path.join(__magic_name__ , """*.txt""" ) ): UpperCamelCase :Optional[Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__magic_name__ ) as in_file: UpperCamelCase :Union[str, Any] = in_file.readlines() UpperCamelCase :Union[str, Any] = os.path.join(__magic_name__ , f"""{label_name}.jpg""" ) UpperCamelCase :str = [] for obj_list in obj_lists: UpperCamelCase :Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) UpperCamelCase :Optional[Any] = float(obj[1] ) - float(obj[3] ) / 2 UpperCamelCase :int = float(obj[2] ) - float(obj[4] ) / 2 UpperCamelCase :Optional[Any] = float(obj[1] ) + float(obj[3] ) / 2 UpperCamelCase :str = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__magic_name__ ) labels.append(__magic_name__ ) return img_paths, labels def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list , __magic_name__ : list , __magic_name__ : list[int] , __magic_name__ : tuple[int, int] , __magic_name__ : tuple[float, float] , __magic_name__ : float = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" UpperCamelCase :List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) UpperCamelCase :Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) UpperCamelCase :Optional[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) UpperCamelCase :Dict = int(scale_x * output_size[1] ) UpperCamelCase :List[Any] = int(scale_y * output_size[0] ) UpperCamelCase :Any = [] UpperCamelCase :Optional[int] = [] for i, index in enumerate(__magic_name__ ): UpperCamelCase :Optional[int] = all_img_list[index] path_list.append(__magic_name__ ) UpperCamelCase :str = all_annos[index] UpperCamelCase :List[Any] = cva.imread(__magic_name__ ) if i == 0: # top-left UpperCamelCase :Union[str, Any] = cva.resize(__magic_name__ , (divid_point_x, divid_point_y) ) UpperCamelCase :Tuple = img for bbox in img_annos: UpperCamelCase :str = bbox[1] * scale_x UpperCamelCase :List[str] = bbox[2] * scale_y UpperCamelCase :Dict = bbox[3] * scale_x UpperCamelCase :List[Any] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right UpperCamelCase :int = cva.resize(__magic_name__ , (output_size[1] - divid_point_x, divid_point_y) ) UpperCamelCase :Tuple = img for bbox in img_annos: UpperCamelCase :List[str] = scale_x + bbox[1] * (1 - scale_x) UpperCamelCase :str = bbox[2] * scale_y UpperCamelCase :Tuple = scale_x + bbox[3] * (1 - scale_x) UpperCamelCase :Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left UpperCamelCase :List[str] = cva.resize(__magic_name__ , (divid_point_x, output_size[0] - divid_point_y) ) UpperCamelCase :Optional[Any] = img for bbox in img_annos: UpperCamelCase :Tuple = bbox[1] * scale_x UpperCamelCase :Dict = scale_y + bbox[2] * (1 - scale_y) UpperCamelCase :List[Any] = bbox[3] * scale_x UpperCamelCase :int = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right UpperCamelCase :List[str] = cva.resize( __magic_name__ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) UpperCamelCase :Any = img for bbox in img_annos: UpperCamelCase :Any = scale_x + bbox[1] * (1 - scale_x) UpperCamelCase :List[Any] = scale_y + bbox[2] * (1 - scale_y) UpperCamelCase :List[Any] = scale_x + bbox[3] * (1 - scale_x) UpperCamelCase :List[str] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: UpperCamelCase :List[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 SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" UpperCamelCase :int = ascii_lowercase + digits return "".join(random.choice(__magic_name__ ) for _ in range(__magic_name__ ) ) if __name__ == "__main__": main() print('''DONE ✅''')
38
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """openai/whisper-base""" snake_case__ : Optional[int] = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) snake_case__ : Any = """transcriber""" snake_case__ : Optional[int] = WhisperProcessor snake_case__ : str = WhisperForConditionalGeneration snake_case__ : Optional[Any] = ["""audio"""] snake_case__ : Any = ["""text"""] def _A ( self : str , __lowerCamelCase : Dict ): return self.pre_processor(__lowerCamelCase , return_tensors="""pt""" ).input_features def _A ( self : Dict , __lowerCamelCase : List[Any] ): return self.model.generate(inputs=__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : Optional[Any] ): return self.pre_processor.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase )[0]
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str ) -> str: """simple docstring""" UpperCamelCase :int = 0 # if input_string is "aba" than new_input_string become "a|b|a" UpperCamelCase :Dict = """""" UpperCamelCase :int = """""" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(__magic_name__ ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring UpperCamelCase , UpperCamelCase :str = 0, 0 # length[i] shows the length of palindromic substring with center i UpperCamelCase :str = [1 for i in range(len(__magic_name__ ) )] # for each character in new_string find corresponding palindromic string UpperCamelCase :List[Any] = 0 for j in range(len(__magic_name__ ) ): UpperCamelCase :str = 1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(__magic_name__ ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 UpperCamelCase :str = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: UpperCamelCase :Optional[int] = j - k + 1 # noqa: E741 UpperCamelCase :Tuple = j + k - 1 # update max_length and start position if max_length < length[j]: UpperCamelCase :int = length[j] UpperCamelCase :Dict = j # create that string UpperCamelCase :List[Any] = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
38
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=_a ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) snake_case__ : ClassVar[Features] = Features({"""audio""": Audio()} ) snake_case__ : ClassVar[Features] = Features({"""transcription""": Value("""string""" )} ) snake_case__ : str = "audio" snake_case__ : str = "transcription" def _A ( self : List[str] , __lowerCamelCase : Dict ): if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) UpperCamelCase :int = copy.deepcopy(self ) UpperCamelCase :Any = self.input_schema.copy() UpperCamelCase :List[str] = features[self.audio_column] UpperCamelCase :List[Any] = input_schema return task_template @property def _A ( self : Optional[int] ): return {self.audio_column: "audio", self.transcription_column: "transcription"}
38
1
import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCAmelCase_ : Dict = logging.getLogger(__name__) UpperCAmelCase_ : Optional[Any] = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) UpperCAmelCase_ : str = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _SCREAMING_SNAKE_CASE : snake_case__ : Optional[str] = field( default=_a , metadata={ """help""": ( """The model checkpoint for weights initialization. Leave None if you want to train a model from""" """ scratch.""" ) } , ) snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(_a )} , ) snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class _SCREAMING_SNAKE_CASE : snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """The input training data file (a text file)."""} ) snake_case__ : Optional[str] = field( default=_a , metadata={ """help""": ( """The input training data files (multiple files in glob format). """ """Very often splitting large files to smaller files can prevent tokenizer going out of memory""" ) } , ) snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , ) snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """An optional input train ref data file for whole word mask in Chinese."""} , ) snake_case__ : Optional[str] = field( default=_a , metadata={"""help""": """An optional input eval ref data file for whole word mask in Chinese."""} , ) snake_case__ : bool = field( default=_a , metadata={"""help""": """Whether distinct lines of text in the dataset are to be handled as distinct sequences."""} , ) snake_case__ : bool = field( default=_a , metadata={"""help""": """Train with masked-language modeling loss instead of language modeling."""} ) snake_case__ : bool = field(default=_a , metadata={"""help""": """Whether ot not to use whole word mask."""} ) snake_case__ : float = field( default=0.15 , metadata={"""help""": """Ratio of tokens to mask for masked language modeling loss"""} ) snake_case__ : float = field( default=1 / 6 , metadata={ """help""": ( """Ratio of length of a span of masked tokens to surrounding context length for permutation language""" """ modeling.""" ) } , ) snake_case__ : int = field( default=5 , metadata={"""help""": """Maximum length of a span of masked tokens for permutation language modeling."""} ) snake_case__ : int = field( default=-1 , metadata={ """help""": ( """Optional input sequence length after tokenization.""" """The training dataset will be truncated in block of this size for training.""" """Default to the model max input length for single sentence inputs (take into account special tokens).""" ) } , ) snake_case__ : bool = field( default=_a , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : DataTrainingArguments , __magic_name__ : PreTrainedTokenizer , __magic_name__ : bool = False , __magic_name__ : Optional[str] = None , ) -> List[Any]: """simple docstring""" def _dataset(__magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any]=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=__magic_name__ , file_path=__magic_name__ , block_size=args.block_size , ref_path=__magic_name__ , ) return LineByLineTextDataset(tokenizer=__magic_name__ , file_path=__magic_name__ , block_size=args.block_size ) else: return TextDataset( tokenizer=__magic_name__ , file_path=__magic_name__ , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=__magic_name__ , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(__magic_name__ ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: """simple docstring""" UpperCamelCase :List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , __magic_name__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: UpperCamelCase :Tuple = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: UpperCamelCase :Dict = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: UpperCamelCase :Tuple = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: UpperCamelCase :int = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: UpperCamelCase :Dict = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) UpperCamelCase :Any = AutoModelWithLMHead.from_config(__magic_name__ ) model.resize_token_embeddings(len(__magic_name__ ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: UpperCamelCase :Dict = tokenizer.max_len # Our input block size will be the max possible for the model else: UpperCamelCase :int = min(data_args.block_size , tokenizer.max_len ) # Get datasets UpperCamelCase :Optional[int] = ( get_dataset(__magic_name__ , tokenizer=__magic_name__ , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) UpperCamelCase :Any = ( get_dataset(__magic_name__ , tokenizer=__magic_name__ , evaluate=__magic_name__ , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": UpperCamelCase :int = DataCollatorForPermutationLanguageModeling( tokenizer=__magic_name__ , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: UpperCamelCase :str = DataCollatorForWholeWordMask( tokenizer=__magic_name__ , mlm_probability=data_args.mlm_probability ) else: UpperCamelCase :Any = DataCollatorForLanguageModeling( tokenizer=__magic_name__ , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer UpperCamelCase :List[Any] = Trainer( model=__magic_name__ , args=__magic_name__ , data_collator=__magic_name__ , train_dataset=__magic_name__ , eval_dataset=__magic_name__ , prediction_loss_only=__magic_name__ , ) # Training if training_args.do_train: UpperCamelCase :Optional[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=__magic_name__ ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation UpperCamelCase :Optional[int] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) UpperCamelCase :List[Any] = trainer.evaluate() UpperCamelCase :List[Any] = math.exp(eval_output["""eval_loss"""] ) UpperCamelCase :Optional[Any] = {"""perplexity""": perplexity} UpperCamelCase :Tuple = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(__magic_name__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , __magic_name__ , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(__magic_name__ ) return results def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] ) -> int: """simple docstring""" main() if __name__ == "__main__": main()
38
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
38
1
import sys import turtle def SCREAMING_SNAKE_CASE_ ( __magic_name__ : tuple[float, float] , __magic_name__ : tuple[float, float] ) -> tuple[float, float]: """simple docstring""" return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : tuple[float, float] , __magic_name__ : tuple[float, float] , __magic_name__ : tuple[float, float] , __magic_name__ : int , ) -> None: """simple docstring""" my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(__magic_name__ , get_mid(__magic_name__ , __magic_name__ ) , get_mid(__magic_name__ , __magic_name__ ) , depth - 1 ) triangle(__magic_name__ , get_mid(__magic_name__ , __magic_name__ ) , get_mid(__magic_name__ , __magic_name__ ) , depth - 1 ) triangle(__magic_name__ , get_mid(__magic_name__ , __magic_name__ ) , get_mid(__magic_name__ , __magic_name__ ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( '''Correct format for using this script: ''' '''python fractals.py <int:depth_for_fractal>''' ) UpperCAmelCase_ : str = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('''red''') UpperCAmelCase_ : int = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
38
import re import string import numpy as np import datasets UpperCAmelCase_ : Dict = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' UpperCAmelCase_ : Any = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' UpperCAmelCase_ : Tuple = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def _A ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : int=False , __lowerCamelCase : Optional[int]=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase :str = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in predictions] ) UpperCamelCase :Tuple = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in references] ) else: UpperCamelCase :Any = np.asarray(__lowerCamelCase ) UpperCamelCase :str = np.asarray(__lowerCamelCase ) if ignore_case: UpperCamelCase :Tuple = np.char.lower(__lowerCamelCase ) UpperCamelCase :Any = np.char.lower(__lowerCamelCase ) if ignore_punctuation: UpperCamelCase :Optional[int] = string.punctuation.maketrans("""""" , """""" , string.punctuation ) UpperCamelCase :Optional[Any] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :List[str] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) if ignore_numbers: UpperCamelCase :Tuple = string.digits.maketrans("""""" , """""" , string.digits ) UpperCamelCase :Dict = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :Tuple = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :int = predictions == references return {"exact_match": np.mean(__lowerCamelCase ) * 100}
38
1
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 UpperCAmelCase_ : str = transforms.Compose( [ transforms.Resize((2_56, 2_56)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" if isinstance(__magic_name__ , torch.Tensor ): return image elif isinstance(__magic_name__ , PIL.Image.Image ): UpperCamelCase :Union[str, Any] = [image] UpperCamelCase :Tuple = [trans(img.convert("""RGB""" ) ) for img in image] UpperCamelCase :int = torch.stack(__magic_name__ ) return image class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Any ): super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase :List[Any] = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) def _A ( self : Dict , __lowerCamelCase : List[str] ): if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""" ) def _A ( self : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ): # get the original timestep using init_timestep UpperCamelCase :Optional[Any] = min(int(num_inference_steps * strength ) , __lowerCamelCase ) UpperCamelCase :Dict = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase :str = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _A ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int]=None ): 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 )}""" ) UpperCamelCase :Tuple = 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.""" ) UpperCamelCase :Tuple = init_latents.shape UpperCamelCase :List[str] = randn_tensor(__lowerCamelCase , generator=__lowerCamelCase , device=__lowerCamelCase , dtype=__lowerCamelCase ) # get latents print("""add noise to latents at timestep""" , __lowerCamelCase ) UpperCamelCase :List[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Tuple = init_latents return latents @torch.no_grad() def __call__( self : Tuple , __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 = 50 , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[str] = "pil" , __lowerCamelCase : bool = True , ): self.check_inputs(__lowerCamelCase ) # 2. Preprocess image UpperCamelCase :Any = preprocess(__lowerCamelCase ) # 3. set timesteps self.scheduler.set_timesteps(__lowerCamelCase , device=self.device ) UpperCamelCase , UpperCamelCase :Dict = self.get_timesteps(__lowerCamelCase , __lowerCamelCase , self.device ) UpperCamelCase :List[Any] = timesteps[:1].repeat(__lowerCamelCase ) # 4. Prepare latent variables UpperCamelCase :str = self.prepare_latents(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , self.unet.dtype , self.device , __lowerCamelCase ) UpperCamelCase :List[str] = latents # 5. Denoising loop for t in self.progress_bar(__lowerCamelCase ): # 1. predict noise model_output UpperCamelCase :List[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 UpperCamelCase :Union[str, Any] = self.scheduler.step( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , eta=__lowerCamelCase , use_clipped_model_output=__lowerCamelCase , generator=__lowerCamelCase , ).prev_sample UpperCamelCase :Dict = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase :List[str] = self.numpy_to_pil(__lowerCamelCase ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=__lowerCamelCase )
38
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : str = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """layoutlmv3""" def __init__( self : List[Any] , __lowerCamelCase : Optional[Any]=50_265 , __lowerCamelCase : Dict=768 , __lowerCamelCase : Any=12 , __lowerCamelCase : int=12 , __lowerCamelCase : str=3_072 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=512 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Union[str, Any]=0.02 , __lowerCamelCase : Union[str, Any]=1E-5 , __lowerCamelCase : Any=1 , __lowerCamelCase : Optional[int]=0 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Dict=1_024 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=128 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : str=32 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=64 , __lowerCamelCase : List[str]=256 , __lowerCamelCase : Dict=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Tuple=224 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Dict=16 , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : Optional[Any] , ): super().__init__( 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 , initializer_range=__lowerCamelCase , layer_norm_eps=__lowerCamelCase , pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :int = max_ad_position_embeddings UpperCamelCase :Tuple = coordinate_size UpperCamelCase :List[Any] = shape_size UpperCamelCase :Union[str, Any] = has_relative_attention_bias UpperCamelCase :Any = rel_pos_bins UpperCamelCase :Optional[Any] = max_rel_pos UpperCamelCase :str = has_spatial_attention_bias UpperCamelCase :Tuple = rel_ad_pos_bins UpperCamelCase :Optional[int] = max_rel_ad_pos UpperCamelCase :Tuple = text_embed UpperCamelCase :str = visual_embed UpperCamelCase :Optional[Any] = input_size UpperCamelCase :str = num_channels UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[Any] = classifier_dropout class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = version.parse("""1.12""" ) @property def _A ( self : Optional[int] ): # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def _A ( self : str ): return 1E-5 @property def _A ( self : Dict ): return 12 def _A ( self : Dict , __lowerCamelCase : "ProcessorMixin" , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 40 , __lowerCamelCase : int = 40 , ): setattr(processor.image_processor , """apply_ocr""" , __lowerCamelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase :Optional[Any] = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase :Optional[int] = processor.tokenizer.num_special_tokens_to_add(__lowerCamelCase ) UpperCamelCase :int = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase :Any = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase :Optional[Any] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase :List[str] = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = dict( processor( __lowerCamelCase , text=__lowerCamelCase , boxes=__lowerCamelCase , return_tensors=__lowerCamelCase , ) ) return inputs
38
1
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : int ) -> Tuple: """simple docstring""" return params[f"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : Any="attention" ) -> str: """simple docstring""" UpperCamelCase :str = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :] ) UpperCamelCase :Optional[Any] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) UpperCamelCase :Dict = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :] ) UpperCamelCase :List[str] = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) UpperCamelCase :List[str] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :] ) UpperCamelCase :int = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) UpperCamelCase :Optional[Any] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :] ) UpperCamelCase :int = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Any=False ) -> Tuple: """simple docstring""" if split_mlp_wi: UpperCamelCase :Optional[Any] = params[f"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] UpperCamelCase :List[str] = params[f"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] UpperCamelCase :Dict = (wi_a, wi_a) else: UpperCamelCase :Union[str, Any] = params[f"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] UpperCamelCase :Tuple = params[f"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : List[str] ) -> List[str]: """simple docstring""" return params[f"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : dict , *, __magic_name__ : int , __magic_name__ : bool , __magic_name__ : bool = False ) -> Dict: """simple docstring""" UpperCamelCase :Dict = traverse_util.flatten_dict(variables["""target"""] ) UpperCamelCase :int = {"""/""".join(__magic_name__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase :str = """encoder/encoder/mlp/wi_0/kernel""" in old print("""Split MLP:""" , __magic_name__ ) UpperCamelCase :Optional[int] = collections.OrderedDict() # Shared embeddings. UpperCamelCase :Dict = old["""token_embedder/embedding"""] # Encoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :Optional[int] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = tax_attention_lookup(__magic_name__ , __magic_name__ , """encoder""" , """attention""" ) UpperCamelCase :Union[str, Any] = layer_norm UpperCamelCase :Tuple = k.T UpperCamelCase :Optional[Any] = o.T UpperCamelCase :Dict = q.T UpperCamelCase :List[str] = v.T # Block i, layer 1 (MLP). UpperCamelCase :Optional[Any] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :Dict = tax_mlp_lookup(__magic_name__ , __magic_name__ , """encoder""" , __magic_name__ ) UpperCamelCase :List[Any] = layer_norm if split_mlp_wi: UpperCamelCase :Any = wi[0].T UpperCamelCase :Optional[Any] = wi[1].T else: UpperCamelCase :Optional[int] = wi.T UpperCamelCase :Any = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :Optional[Any] = tax_relpos_bias_lookup( __magic_name__ , __magic_name__ , """encoder""" ).T UpperCamelCase :Tuple = old["""encoder/encoder_norm/scale"""] if not scalable_attention: UpperCamelCase :Dict = tax_relpos_bias_lookup( __magic_name__ , 0 , """encoder""" ).T UpperCamelCase :Tuple = tax_relpos_bias_lookup( __magic_name__ , 0 , """decoder""" ).T if not is_encoder_only: # Decoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :Dict = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_self_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """self_attention""" ) UpperCamelCase :int = layer_norm UpperCamelCase :Optional[Any] = k.T UpperCamelCase :Tuple = o.T UpperCamelCase :Optional[Any] = q.T UpperCamelCase :int = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase :str = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_cross_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Tuple = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """encoder_decoder_attention""" ) UpperCamelCase :str = layer_norm UpperCamelCase :List[str] = k.T UpperCamelCase :Optional[int] = o.T UpperCamelCase :Union[str, Any] = q.T UpperCamelCase :Tuple = v.T # Block i, layer 2 (MLP). UpperCamelCase :Optional[Any] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :Optional[int] = tax_mlp_lookup(__magic_name__ , __magic_name__ , """decoder""" , __magic_name__ ) UpperCamelCase :str = layer_norm if split_mlp_wi: UpperCamelCase :Any = wi[0].T UpperCamelCase :int = wi[1].T else: UpperCamelCase :List[str] = wi.T UpperCamelCase :Union[str, Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :Union[str, Any] = tax_relpos_bias_lookup(__magic_name__ , __magic_name__ , """decoder""" ).T UpperCamelCase :int = old["""decoder/decoder_norm/scale"""] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase :Optional[Any] = old["""decoder/logits_dense/kernel"""].T return new def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] , __magic_name__ : bool ) -> List[Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase :int = state_dict["""shared.weight"""] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase :List[str] = state_dict["""shared.weight"""] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("""Using shared word embeddings as lm_head.""" ) UpperCamelCase :Optional[Any] = state_dict["""shared.weight"""] return state_dict def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : List[str] ) -> int: """simple docstring""" UpperCamelCase :Any = checkpoints.load_tax_checkpoint(__magic_name__ ) UpperCamelCase :int = convert_tax_to_pytorch( __magic_name__ , num_layers=config.num_layers , is_encoder_only=__magic_name__ , scalable_attention=__magic_name__ ) UpperCamelCase :Any = make_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ , strict=__magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : bool = False , __magic_name__ : bool = False , ) -> Dict: """simple docstring""" UpperCamelCase :Optional[Any] = MTaConfig.from_json_file(__magic_name__ ) print(f"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase :List[str] = UMTaEncoderModel(__magic_name__ ) else: UpperCamelCase :List[Any] = UMTaForConditionalGeneration(__magic_name__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__magic_name__ ) # Verify that we can load the checkpoint. model.from_pretrained(__magic_name__ ) print("""Done""" ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis 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_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) UpperCAmelCase_ : Tuple = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Any = StableDiffusionXLImgaImgPipeline snake_case__ : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} snake_case__ : Tuple = PipelineTesterMixin.required_optional_params - {"""latents"""} snake_case__ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case__ : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS snake_case__ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=__lowerCamelCase , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) UpperCamelCase :Tuple = EulerDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCamelCase :Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=32 , ) UpperCamelCase :Any = CLIPTextModel(__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTextModelWithProjection(__lowerCamelCase ) UpperCamelCase :int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _A ( self : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any]=0 ): UpperCamelCase :Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) UpperCamelCase :List[str] = image / 2 + 0.5 if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :Any = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :List[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def _A ( self : str ): UpperCamelCase :List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :Optional[Any] = self.get_dummy_components() UpperCamelCase :List[Any] = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :Any = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = sd_pipe(**__lowerCamelCase ).images UpperCamelCase :Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :List[Any] = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : Dict ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _A ( self : Optional[Any] ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _A ( self : Union[str, Any] ): pass def _A ( self : Optional[int] ): UpperCamelCase :Union[str, Any] = self.get_dummy_components() UpperCamelCase :Dict = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :List[Any] = sd_pipe.to(__lowerCamelCase ) UpperCamelCase :List[str] = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) # forward without prompt embeds UpperCamelCase :List[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :int = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = negative_prompt UpperCamelCase :Union[str, Any] = 3 * [inputs["""prompt"""]] UpperCamelCase :Dict = sd_pipe(**__lowerCamelCase ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = 3 * [inputs.pop("""prompt""" )] ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = sd_pipe.encode_prompt(__lowerCamelCase , negative_prompt=__lowerCamelCase ) UpperCamelCase :Dict = sd_pipe( **__lowerCamelCase , prompt_embeds=__lowerCamelCase , negative_prompt_embeds=__lowerCamelCase , pooled_prompt_embeds=__lowerCamelCase , negative_pooled_prompt_embeds=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Tuple ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict="cpu" , __lowerCamelCase : List[Any]=torch.floataa , __lowerCamelCase : Tuple=0 ): UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = np.random.RandomState(__lowerCamelCase ).standard_normal((1, 4, 64, 64) ) UpperCamelCase :Dict = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase , dtype=__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _A ( self : Optional[Any] ): UpperCamelCase :Any = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = pipe(**__lowerCamelCase ).images UpperCamelCase :Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCamelCase :Union[str, Any] = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
38
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase_ : int = { '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : str = [ '''GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GraphormerForGraphClassification''', '''GraphormerModel''', '''GraphormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys UpperCAmelCase_ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : int = { '''CarlCochet/trajectory-transformer-halfcheetah-medium-v2''': ( '''https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json''' ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """trajectory_transformer""" snake_case__ : Optional[Any] = ["""past_key_values"""] snake_case__ : Tuple = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Union[str, Any] , __lowerCamelCase : Any=100 , __lowerCamelCase : str=5 , __lowerCamelCase : str=1 , __lowerCamelCase : Optional[int]=1 , __lowerCamelCase : int=249 , __lowerCamelCase : str=6 , __lowerCamelCase : Dict=17 , __lowerCamelCase : Optional[Any]=25 , __lowerCamelCase : List[str]=4 , __lowerCamelCase : str=4 , __lowerCamelCase : Tuple=128 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : int=0.0006 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Any=1E-12 , __lowerCamelCase : int=1 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Tuple=1 , __lowerCamelCase : int=50_256 , __lowerCamelCase : Union[str, Any]=50_256 , **__lowerCamelCase : Dict , ): UpperCamelCase :Dict = vocab_size UpperCamelCase :int = action_weight UpperCamelCase :Tuple = reward_weight UpperCamelCase :str = value_weight UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :Tuple = block_size UpperCamelCase :Optional[int] = action_dim UpperCamelCase :int = observation_dim UpperCamelCase :List[str] = transition_dim UpperCamelCase :List[Any] = learning_rate UpperCamelCase :Optional[Any] = n_layer UpperCamelCase :Any = n_head UpperCamelCase :List[str] = n_embd UpperCamelCase :Any = embd_pdrop UpperCamelCase :str = attn_pdrop UpperCamelCase :Union[str, Any] = resid_pdrop UpperCamelCase :Optional[Any] = initializer_range UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Optional[int] = kaiming_initializer_range UpperCamelCase :Tuple = use_cache super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list ) -> int: """simple docstring""" if not grid or not grid[0]: raise TypeError("""The grid does not contain the appropriate information""" ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] UpperCamelCase :List[Any] = grid[0] for row_n in range(1 , len(__magic_name__ ) ): UpperCamelCase :List[str] = grid[row_n] UpperCamelCase :List[Any] = fill_row(__magic_name__ , __magic_name__ ) UpperCamelCase :Tuple = grid[row_n] return grid[-1][-1] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list , __magic_name__ : list ) -> list: """simple docstring""" current_row[0] += row_above[0] for cell_n in range(1 , len(__magic_name__ ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
38
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 3 ) -> qiskit.result.counts.Counts: """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): raise TypeError("""number of qubits must be a integer.""" ) if number_of_qubits <= 0: raise ValueError("""number of qubits must be > 0.""" ) if math.floor(__magic_name__ ) != number_of_qubits: raise ValueError("""number of qubits must be exact integer.""" ) if number_of_qubits > 10: raise ValueError("""number of qubits too large to simulate(>10).""" ) UpperCamelCase :int = QuantumRegister(__magic_name__ , """qr""" ) UpperCamelCase :str = ClassicalRegister(__magic_name__ , """cr""" ) UpperCamelCase :str = QuantumCircuit(__magic_name__ , __magic_name__ ) UpperCamelCase :List[Any] = number_of_qubits for i in range(__magic_name__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(__magic_name__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , __magic_name__ , __magic_name__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(__magic_name__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(__magic_name__ , __magic_name__ ) # simulate with 10000 shots UpperCamelCase :str = Aer.get_backend("""qasm_simulator""" ) UpperCamelCase :Dict = execute(__magic_name__ , __magic_name__ , shots=1_0000 ) return job.result().get_counts(__magic_name__ ) if __name__ == "__main__": print( F'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
38
1
from __future__ import annotations import queue class _SCREAMING_SNAKE_CASE : def __init__( self : int , __lowerCamelCase : Union[str, Any] ): UpperCamelCase :Optional[Any] = data UpperCamelCase :Dict = None UpperCamelCase :List[Any] = None def SCREAMING_SNAKE_CASE_ ( ) -> TreeNode: """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) UpperCamelCase :List[str] = input("""Enter the value of the root node: """ ).strip().lower() UpperCamelCase :queue.Queue = queue.Queue() UpperCamelCase :int = TreeNode(int(__magic_name__ ) ) q.put(__magic_name__ ) while not q.empty(): UpperCamelCase :Any = q.get() UpperCamelCase :Union[str, Any] = f"""Enter the left node of {node_found.data}: """ UpperCamelCase :Tuple = input(__magic_name__ ).strip().lower() or """n""" if check == "n": return tree_node UpperCamelCase :int = TreeNode(int(__magic_name__ ) ) UpperCamelCase :List[Any] = left_node q.put(__magic_name__ ) UpperCamelCase :Optional[Any] = f"""Enter the right node of {node_found.data}: """ UpperCamelCase :Any = input(__magic_name__ ).strip().lower() or """n""" if check == "n": return tree_node UpperCamelCase :Union[str, Any] = TreeNode(int(__magic_name__ ) ) UpperCamelCase :Any = right_node q.put(__magic_name__ ) raise def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return UpperCamelCase :queue.Queue = queue.Queue() q.put(__magic_name__ ) while not q.empty(): UpperCamelCase :Optional[Any] = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return UpperCamelCase :queue.Queue = queue.Queue() q.put(__magic_name__ ) while not q.empty(): UpperCamelCase :str = [] while not q.empty(): UpperCamelCase :List[Any] = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return UpperCamelCase :list[TreeNode] = [] UpperCamelCase :List[Any] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__magic_name__ ) UpperCamelCase :Optional[int] = n.left # end of while means current node doesn't have left child UpperCamelCase :Dict = stack.pop() # start to traverse its right child UpperCamelCase :Union[str, Any] = n.right def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return UpperCamelCase :list[TreeNode] = [] UpperCamelCase :List[Any] = node while n or stack: while n: stack.append(__magic_name__ ) UpperCamelCase :str = n.left UpperCamelCase :List[str] = stack.pop() print(n.data , end=""",""" ) UpperCamelCase :str = n.right def SCREAMING_SNAKE_CASE_ ( __magic_name__ : TreeNode ) -> None: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or not node: return UpperCamelCase , UpperCamelCase :str = [], [] UpperCamelCase :Any = node stacka.append(__magic_name__ ) while stacka: # to find the reversed order of post order, store it in stack2 UpperCamelCase :Optional[Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__magic_name__ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str = "" , __magic_name__ : Any=50 , __magic_name__ : Optional[Any]="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char UpperCamelCase , UpperCamelCase :Union[str, Any] = divmod(width - len(__magic_name__ ) - 2 , 2 ) return f"""{left * char} {s} {(left + extra) * char}""" if __name__ == "__main__": import doctest doctest.testmod() print(prompt('''Binary Tree Traversals''')) UpperCAmelCase_ : TreeNode = build_tree() print(prompt('''Pre Order Traversal''')) pre_order(node) print(prompt() + '''\n''') print(prompt('''In Order Traversal''')) in_order(node) print(prompt() + '''\n''') print(prompt('''Post Order Traversal''')) post_order(node) print(prompt() + '''\n''') print(prompt('''Level Order Traversal''')) level_order(node) print(prompt() + '''\n''') print(prompt('''Actual Level Order Traversal''')) level_order_actual(node) print('''*''' * 50 + '''\n''') print(prompt('''Pre Order Traversal - Iteration Version''')) pre_order_iter(node) print(prompt() + '''\n''') print(prompt('''In Order Traversal - Iteration Version''')) in_order_iter(node) print(prompt() + '''\n''') print(prompt('''Post Order Traversal - Iteration Version''')) post_order_iter(node) print(prompt())
38
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer UpperCAmelCase_ : Optional[Any] = ['''bert-base-uncased''', '''bert-base-cased'''] UpperCAmelCase_ : List[str] = '''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class _SCREAMING_SNAKE_CASE ( tf.keras.Model ): def __init__( self : List[str] , __lowerCamelCase : Union[str, Any] ): super().__init__() UpperCamelCase :Any = tokenizer UpperCamelCase :List[str] = AutoConfig.from_pretrained(__lowerCamelCase ) UpperCamelCase :List[str] = TFAutoModel.from_config(__lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : str ): UpperCamelCase :str = self.tokenizer(__lowerCamelCase ) UpperCamelCase :Any = self.bert(**__lowerCamelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Dict ): super().setUp() UpperCamelCase :int = [ BertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase :Any = [TFBertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(__lowerCamelCase , use_fast_bert_tokenizer=__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase :Any = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] UpperCamelCase :Union[str, Any] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _A ( self : Optional[int] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tokenizer(__lowerCamelCase , return_tensors="""tf""" , padding="""longest""" ) UpperCamelCase :str = tf_tokenizer(__lowerCamelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _A ( self : Dict ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :str = tf_tokenizer(self.paired_sentences ) UpperCamelCase :Any = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _A ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[Any] = tf.function(__lowerCamelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tf.constant(__lowerCamelCase ) UpperCamelCase :List[str] = compiled_tokenizer(__lowerCamelCase ) UpperCamelCase :Optional[Any] = tf_tokenizer(__lowerCamelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _A ( self : Tuple ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[str] = ModelToSave(tokenizer=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase :List[str] = Path(__lowerCamelCase ) / """saved.model""" model.save(__lowerCamelCase ) UpperCamelCase :List[Any] = tf.keras.models.load_model(__lowerCamelCase ) UpperCamelCase :Dict = loaded_model(__lowerCamelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
38
1
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar UpperCAmelCase_ : Any = TypeVar('''T''') class _SCREAMING_SNAKE_CASE ( Generic[T] ): snake_case__ : deque[T] # Cache store of keys snake_case__ : set[T] # References of the keys in cache snake_case__ : int = 1_0 # Maximum capacity of cache def __init__( self : Optional[int] , __lowerCamelCase : int ): UpperCamelCase :int = deque() UpperCamelCase :Any = set() if not n: UpperCamelCase :Union[str, Any] = sys.maxsize elif n < 0: raise ValueError("""n should be an integer greater than 0.""" ) else: UpperCamelCase :Tuple = n def _A ( self : List[Any] , __lowerCamelCase : T ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: UpperCamelCase :Any = self.dq_store.pop() self.key_reference.remove(__lowerCamelCase ) else: self.dq_store.remove(__lowerCamelCase ) self.dq_store.appendleft(__lowerCamelCase ) self.key_reference.add(__lowerCamelCase ) def _A ( self : int ): for k in self.dq_store: print(__lowerCamelCase ) def __repr__( self : Optional[int] ): return F"""LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}""" if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ : LRUCache[str | int] = LRUCache(4) lru_cache.refer('''A''') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('''A''') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
38
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase_ : Any = '''Create a default config file for Accelerate with only a few flags set.''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int]="no" , __magic_name__ : str = default_json_config_file , __magic_name__ : bool = False ) -> str: """simple docstring""" UpperCamelCase :Any = Path(__magic_name__ ) path.parent.mkdir(parents=__magic_name__ , exist_ok=__magic_name__ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False UpperCamelCase :Dict = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) UpperCamelCase :Optional[Any] = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): UpperCamelCase :Union[str, Any] = torch.cuda.device_count() UpperCamelCase :List[Any] = num_gpus UpperCamelCase :Dict = False if num_gpus > 1: UpperCamelCase :Any = """MULTI_GPU""" else: UpperCamelCase :Any = """NO""" elif is_xpu_available() and use_xpu: UpperCamelCase :Optional[Any] = torch.xpu.device_count() UpperCamelCase :Optional[int] = num_xpus UpperCamelCase :int = False if num_xpus > 1: UpperCamelCase :Union[str, Any] = """MULTI_XPU""" else: UpperCamelCase :Union[str, Any] = """NO""" elif is_npu_available(): UpperCamelCase :List[Any] = torch.npu.device_count() UpperCamelCase :Optional[Any] = num_npus UpperCamelCase :Tuple = False if num_npus > 1: UpperCamelCase :Optional[Any] = """MULTI_NPU""" else: UpperCamelCase :List[Any] = """NO""" else: UpperCamelCase :Any = 0 UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[str] = """NO""" UpperCamelCase :int = ClusterConfig(**__magic_name__ ) config.to_json_file(__magic_name__ ) return path def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = parser.add_parser("""default""" , parents=__magic_name__ , help=__magic_name__ , formatter_class=__magic_name__ ) parser.add_argument( """--config_file""" , default=__magic_name__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=__magic_name__ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=__magic_name__ ) return parser def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
38
1
from __future__ import annotations import bisect def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : int = 0 , __magic_name__ : int = -1 ) -> int: """simple docstring""" if hi < 0: UpperCamelCase :Optional[int] = len(__magic_name__ ) while lo < hi: UpperCamelCase :Tuple = lo + (hi - lo) // 2 if sorted_collection[mid] < item: UpperCamelCase :Optional[Any] = mid + 1 else: UpperCamelCase :Optional[int] = mid return lo def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : int = 0 , __magic_name__ : int = -1 ) -> int: """simple docstring""" if hi < 0: UpperCamelCase :int = len(__magic_name__ ) while lo < hi: UpperCamelCase :List[Any] = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: UpperCamelCase :str = mid + 1 else: UpperCamelCase :Dict = mid return lo def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : int = 0 , __magic_name__ : int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_left(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : int = 0 , __magic_name__ : int = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_right(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int ) -> int | None: """simple docstring""" UpperCamelCase :List[Any] = 0 UpperCamelCase :Tuple = len(__magic_name__ ) - 1 while left <= right: UpperCamelCase :Any = left + (right - left) // 2 UpperCamelCase :str = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: UpperCamelCase :str = midpoint - 1 else: UpperCamelCase :Any = midpoint + 1 return None def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int ) -> int | None: """simple docstring""" UpperCamelCase :int = bisect.bisect_left(__magic_name__ , __magic_name__ ) if index != len(__magic_name__ ) and sorted_collection[index] == item: return index return None def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int ) -> int | None: """simple docstring""" if right < left: return None UpperCamelCase :Union[str, Any] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(__magic_name__ , __magic_name__ , __magic_name__ , midpoint - 1 ) else: return binary_search_by_recursion(__magic_name__ , __magic_name__ , midpoint + 1 , __magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : List[Any] = input('''Enter numbers separated by comma:\n''').strip() UpperCAmelCase_ : List[Any] = sorted(int(item) for item in user_input.split(''',''')) UpperCAmelCase_ : Dict = int(input('''Enter a single number to be found in the list:\n''')) UpperCAmelCase_ : Optional[Any] = binary_search(collection, target) if result is None: print(F'''{target} was not found in {collection}.''') else: print(F'''{target} was found at position {result} in {collection}.''')
38
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
1
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def SCREAMING_SNAKE_CASE_ ( ) -> List[str]: """simple docstring""" raise RuntimeError("""CUDA out of memory.""" ) class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] ): super().__init__() UpperCamelCase :Any = nn.Linear(3 , 4 ) UpperCamelCase :Optional[Any] = nn.BatchNormad(4 ) UpperCamelCase :Any = nn.Linear(4 , 5 ) def _A ( self : Any , __lowerCamelCase : str ): return self.lineara(self.batchnorm(self.lineara(__lowerCamelCase ) ) ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : int ): UpperCamelCase :Union[str, Any] = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__lowerCamelCase : List[str] ): nonlocal batch_sizes batch_sizes.append(__lowerCamelCase ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(__lowerCamelCase , [128, 64, 32, 16, 8] ) def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] ): nonlocal batch_sizes batch_sizes.append(__lowerCamelCase ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga UpperCamelCase , UpperCamelCase :str = mock_training_loop_function("""hello""" ) self.assertListEqual(__lowerCamelCase , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, """hello"""] ) def _A ( self : Tuple ): @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(__lowerCamelCase : List[Any] ): pass with self.assertRaises(__lowerCamelCase ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def _A ( self : Optional[Any] ): @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(__lowerCamelCase : Optional[int] ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(__lowerCamelCase ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def _A ( self : Optional[int] ): @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(__lowerCamelCase ) as cm: mock_training_loop_function(128 , """hello""" , """world""" ) self.assertIn("""Batch size was passed into `f`""" , cm.exception.args[0] ) self.assertIn("""`f(arg1='hello', arg2='world')""" , cm.exception.args[0] ) def _A ( self : Optional[Any] ): @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(__lowerCamelCase : str ): raise ValueError("""Oops, we had an error!""" ) with self.assertRaises(__lowerCamelCase ) as cm: mock_training_loop_function() self.assertIn("""Oops, we had an error!""" , cm.exception.args[0] ) @require_cuda def _A ( self : str ): UpperCamelCase :List[str] = torch.cuda.memory_allocated() UpperCamelCase :Optional[int] = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , __lowerCamelCase ) UpperCamelCase :List[Any] = release_memory(__lowerCamelCase ) self.assertEqual(torch.cuda.memory_allocated() , __lowerCamelCase )
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, 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 _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = ShapEImgaImgPipeline snake_case__ : Optional[Any] = ["""image"""] snake_case__ : Union[str, Any] = ["""image"""] snake_case__ : Optional[Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case__ : List[str] = False @property def _A ( self : Any ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Optional[Any] ): return self.time_input_dim * 4 @property def _A ( self : Union[str, Any] ): return 8 @property def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCamelCase :Optional[int] = CLIPVisionModel(__lowerCamelCase ) return model @property def _A ( self : str ): UpperCamelCase :Optional[int] = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def _A ( self : Tuple ): torch.manual_seed(0 ) UpperCamelCase :Dict = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase :int = PriorTransformer(**__lowerCamelCase ) return model @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) UpperCamelCase :str = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase :List[str] = ShapERenderer(**__lowerCamelCase ) return model def _A ( self : str ): UpperCamelCase :int = self.dummy_prior UpperCamelCase :Any = self.dummy_image_encoder UpperCamelCase :Dict = self.dummy_image_processor UpperCamelCase :List[Any] = self.dummy_renderer UpperCamelCase :int = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__lowerCamelCase , clip_sample=__lowerCamelCase , clip_sample_range=1.0 , ) UpperCamelCase :Optional[Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def _A ( self : int , __lowerCamelCase : int , __lowerCamelCase : Any=0 ): UpperCamelCase :Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :List[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _A ( self : List[str] ): UpperCamelCase :Dict = """cpu""" UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) UpperCamelCase :Dict = output.images[0] UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase :Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : List[Any] ): # 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 : List[Any] ): UpperCamelCase :str = torch_device == """cpu""" UpperCamelCase :int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , ) def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :List[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = 1 UpperCamelCase :int = 2 UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase :str = batch_size * [inputs[key]] UpperCamelCase :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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Any ): UpperCamelCase :Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCamelCase :Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( __lowerCamelCase , generator=__lowerCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] ) -> list[int]: """simple docstring""" UpperCamelCase :List[str] = len(__magic_name__ ) for i in range(__magic_name__ ): for j in range(i + 1 , __magic_name__ ): if numbers[j] < numbers[i]: UpperCamelCase , UpperCamelCase :Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": UpperCAmelCase_ : Any = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase_ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(exchange_sort(unsorted))
38
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record UpperCAmelCase_ : int = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' UpperCAmelCase_ : Optional[Any] = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' UpperCAmelCase_ : int = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any="binary" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = simple_accuracy(__magic_name__ , __magic_name__ ) UpperCamelCase :Dict = float(fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average=__magic_name__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = {} for id_pred, label in zip(__magic_name__ , __magic_name__ ): UpperCamelCase :str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCamelCase :Union[str, Any] = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase :Dict = [(pred, label)] UpperCamelCase , UpperCamelCase :Optional[int] = [], [] for question, preds_labels in question_map.items(): UpperCamelCase , UpperCamelCase :Optional[Any] = zip(*__magic_name__ ) UpperCamelCase :Optional[int] = fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average="""macro""" ) fas.append(__magic_name__ ) UpperCamelCase :int = int(sum(pred == label for pred, label in preds_labels ) == len(__magic_name__ ) ) ems.append(__magic_name__ ) UpperCamelCase :Optional[int] = float(sum(__magic_name__ ) / len(__magic_name__ ) ) UpperCamelCase :str = sum(__magic_name__ ) / len(__magic_name__ ) UpperCamelCase :Tuple = float(fa_score(y_true=__magic_name__ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : str ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _A ( self : Optional[Any] ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _A ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : str ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCamelCase :Optional[Any] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCamelCase :Tuple = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
38
1
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE_ ( ) -> str: """simple docstring""" UpperCamelCase :Optional[Any] = HfArgumentParser(__magic_name__ ) UpperCamelCase :Any = parser.parse_args_into_dataclasses()[0] UpperCamelCase :str = TensorFlowBenchmark(args=__magic_name__ ) try: UpperCamelCase :List[str] = parser.parse_args_into_dataclasses()[0] except ValueError as e: UpperCamelCase :Optional[Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" UpperCamelCase :List[Any] = """ """.join(str(__magic_name__ ).split(""" """ )[:-1] ) UpperCamelCase :int = """""" UpperCamelCase :Optional[Any] = eval(str(__magic_name__ ).split(""" """ )[-1] ) UpperCamelCase :Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__magic_name__ ) if len(__magic_name__ ) > 0: UpperCamelCase :Optional[int] = full_error_msg + begin_error_msg + str(__magic_name__ ) raise ValueError(__magic_name__ ) benchmark.run() if __name__ == "__main__": main()
38
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any=13 , __lowerCamelCase : Dict=3 , __lowerCamelCase : int=224 , __lowerCamelCase : Any=30 , __lowerCamelCase : Tuple=400 , __lowerCamelCase : int=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , ): UpperCamelCase :List[Any] = size if size is not None else {"""height""": 18, """width""": 18} UpperCamelCase :str = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :Dict = num_channels UpperCamelCase :str = image_size UpperCamelCase :Dict = min_resolution UpperCamelCase :str = max_resolution UpperCamelCase :Union[str, Any] = do_resize UpperCamelCase :Optional[Any] = size UpperCamelCase :Any = do_normalize UpperCamelCase :Optional[Any] = image_mean UpperCamelCase :Tuple = image_std def _A ( self : int ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : List[Any] = ViTImageProcessor if is_vision_available() else None def _A ( self : str ): UpperCamelCase :Tuple = EfficientFormerImageProcessorTester(self ) @property def _A ( self : List[str] ): return self.image_proc_tester.prepare_image_processor_dict() def _A ( self : int ): UpperCamelCase :List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) def _A ( self : Optional[int] ): pass def _A ( self : str ): # Initialize image_processor UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :List[str] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :List[Any] = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : Union[str, Any] ): # Initialize image_processor UpperCamelCase :Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase :Dict = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :Tuple = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : List[Any] ): # Initialize image_processor UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase :List[Any] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :str = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
38
1
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : List[Any] = ConsistencyModelPipeline snake_case__ : List[str] = UNCONDITIONAL_IMAGE_GENERATION_PARAMS snake_case__ : int = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt snake_case__ : List[Any] = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _A ( self : Any ): UpperCamelCase :Dict = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet""" , ) return unet @property def _A ( self : Optional[Any] ): UpperCamelCase :str = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet_class_cond""" , ) return unet def _A ( self : List[str] , __lowerCamelCase : Any=False ): if class_cond: UpperCamelCase :Optional[int] = self.dummy_cond_unet else: UpperCamelCase :List[str] = self.dummy_uncond_unet # Default to CM multistep sampler UpperCamelCase :str = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) UpperCamelCase :Dict = { """unet""": unet, """scheduler""": scheduler, } return components def _A ( self : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : str=0 ): if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :Optional[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :int = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[int] = { """batch_size""": 1, """num_inference_steps""": None, """timesteps""": [22, 0], """generator""": generator, """output_type""": """np""", } return inputs def _A ( self : Union[str, Any] ): UpperCamelCase :Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :Optional[int] = self.get_dummy_components() UpperCamelCase :Tuple = ConsistencyModelPipeline(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :List[Any] = pipe(**__lowerCamelCase ).images assert image.shape == (1, 32, 32, 3) UpperCamelCase :str = image[0, -3:, -3:, -1] UpperCamelCase :Any = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _A ( self : int ): UpperCamelCase :List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :List[Any] = self.get_dummy_components(class_cond=__lowerCamelCase ) UpperCamelCase :List[str] = ConsistencyModelPipeline(**__lowerCamelCase ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :List[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = 0 UpperCamelCase :List[str] = pipe(**__lowerCamelCase ).images assert image.shape == (1, 32, 32, 3) UpperCamelCase :Dict = image[0, -3:, -3:, -1] UpperCamelCase :Tuple = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _A ( self : int ): UpperCamelCase :List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :Dict = self.get_dummy_components() UpperCamelCase :int = ConsistencyModelPipeline(**__lowerCamelCase ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Dict = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Tuple = 1 UpperCamelCase :int = None UpperCamelCase :Optional[Any] = pipe(**__lowerCamelCase ).images assert image.shape == (1, 32, 32, 3) UpperCamelCase :Union[str, Any] = image[0, -3:, -3:, -1] UpperCamelCase :Union[str, Any] = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _A ( self : int ): UpperCamelCase :Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :str = self.get_dummy_components(class_cond=__lowerCamelCase ) UpperCamelCase :str = ConsistencyModelPipeline(**__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Tuple = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Dict = 1 UpperCamelCase :str = None UpperCamelCase :int = 0 UpperCamelCase :Tuple = pipe(**__lowerCamelCase ).images assert image.shape == (1, 32, 32, 3) UpperCamelCase :List[str] = image[0, -3:, -3:, -1] UpperCamelCase :Dict = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : List[str] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Tuple , __lowerCamelCase : List[str]=0 , __lowerCamelCase : List[Any]=False , __lowerCamelCase : Tuple="cpu" , __lowerCamelCase : Dict=torch.floataa , __lowerCamelCase : Optional[int]=(1, 3, 64, 64) ): UpperCamelCase :str = torch.manual_seed(__lowerCamelCase ) UpperCamelCase :Dict = { """num_inference_steps""": None, """timesteps""": [22, 0], """class_labels""": 0, """generator""": generator, """output_type""": """np""", } if get_fixed_latents: UpperCamelCase :Optional[Any] = self.get_fixed_latents(seed=__lowerCamelCase , device=__lowerCamelCase , dtype=__lowerCamelCase , shape=__lowerCamelCase ) UpperCamelCase :Tuple = latents return inputs def _A ( self : Tuple , __lowerCamelCase : List[Any]=0 , __lowerCamelCase : Union[str, Any]="cpu" , __lowerCamelCase : str=torch.floataa , __lowerCamelCase : List[str]=(1, 3, 64, 64) ): if type(__lowerCamelCase ) == str: UpperCamelCase :Tuple = torch.device(__lowerCamelCase ) UpperCamelCase :List[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = randn_tensor(__lowerCamelCase , generator=__lowerCamelCase , device=__lowerCamelCase , dtype=__lowerCamelCase ) return latents def _A ( self : str ): UpperCamelCase :Tuple = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) UpperCamelCase :Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) UpperCamelCase :List[str] = ConsistencyModelPipeline(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) pipe.to(torch_device=__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :List[str] = self.get_inputs() UpperCamelCase :Dict = pipe(**__lowerCamelCase ).images assert image.shape == (1, 64, 64, 3) UpperCamelCase :str = image[0, -3:, -3:, -1] UpperCamelCase :List[Any] = np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _A ( self : Union[str, Any] ): UpperCamelCase :Tuple = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) UpperCamelCase :Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) UpperCamelCase :Tuple = ConsistencyModelPipeline(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) pipe.to(torch_device=__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :List[str] = self.get_inputs() UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[Any] = None UpperCamelCase :Any = pipe(**__lowerCamelCase ).images assert image.shape == (1, 64, 64, 3) UpperCamelCase :Optional[int] = image[0, -3:, -3:, -1] UpperCamelCase :Optional[int] = np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 @require_torch_a def _A ( self : int ): UpperCamelCase :Any = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) UpperCamelCase :Dict = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) UpperCamelCase :Dict = ConsistencyModelPipeline(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) pipe.to(torch_device=__lowerCamelCase , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :List[Any] = self.get_inputs(get_fixed_latents=__lowerCamelCase , device=__lowerCamelCase ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__lowerCamelCase , enable_math=__lowerCamelCase , enable_mem_efficient=__lowerCamelCase ): UpperCamelCase :Optional[int] = pipe(**__lowerCamelCase ).images assert image.shape == (1, 64, 64, 3) UpperCamelCase :Optional[int] = image[0, -3:, -3:, -1] UpperCamelCase :Dict = np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @require_torch_a def _A ( self : List[Any] ): UpperCamelCase :Any = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) UpperCamelCase :str = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) UpperCamelCase :Union[str, Any] = ConsistencyModelPipeline(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) pipe.to(torch_device=__lowerCamelCase , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[int] = self.get_inputs(get_fixed_latents=__lowerCamelCase , device=__lowerCamelCase ) UpperCamelCase :Optional[Any] = 1 UpperCamelCase :Any = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__lowerCamelCase , enable_math=__lowerCamelCase , enable_mem_efficient=__lowerCamelCase ): UpperCamelCase :Union[str, Any] = pipe(**__lowerCamelCase ).images assert image.shape == (1, 64, 64, 3) UpperCamelCase :Optional[int] = image[0, -3:, -3:, -1] UpperCamelCase :Dict = np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
38
from collections.abc import Generator from math import sin def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" if len(__magic_name__ ) != 32: raise ValueError("""Input must be of length 32""" ) UpperCamelCase :int = B"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bytes: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :Any = format(__magic_name__ , """08x""" )[-8:] UpperCamelCase :Union[str, Any] = B"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :str = B"""""" for char in message: bit_string += format(__magic_name__ , """08b""" ).encode("""utf-8""" ) UpperCamelCase :Any = format(len(__magic_name__ ) , """064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__magic_name__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> Generator[list[int], None, None]: """simple docstring""" if len(__magic_name__ ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 , len(__magic_name__ ) , 512 ): UpperCamelCase :Tuple = bit_string[pos : pos + 512] UpperCamelCase :Optional[int] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :List[str] = format(__magic_name__ , """032b""" ) UpperCamelCase :Any = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(__magic_name__ , 2 ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" return (a + b) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :Tuple = preprocess(__magic_name__ ) UpperCamelCase :List[str] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states UpperCamelCase :Union[str, Any] = 0X67_45_23_01 UpperCamelCase :Union[str, Any] = 0XEF_CD_AB_89 UpperCamelCase :List[str] = 0X98_BA_DC_FE UpperCamelCase :int = 0X10_32_54_76 UpperCamelCase :int = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__magic_name__ ): UpperCamelCase :Optional[Any] = aa UpperCamelCase :Any = ba UpperCamelCase :Tuple = ca UpperCamelCase :List[str] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f UpperCamelCase :int = d ^ (b & (c ^ d)) UpperCamelCase :Optional[int] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f UpperCamelCase :str = c ^ (d & (b ^ c)) UpperCamelCase :Union[str, Any] = (5 * i + 1) % 16 elif i <= 47: UpperCamelCase :str = b ^ c ^ d UpperCamelCase :Optional[int] = (3 * i + 5) % 16 else: UpperCamelCase :List[str] = c ^ (b | not_aa(__magic_name__ )) UpperCamelCase :int = (7 * i) % 16 UpperCamelCase :Dict = (f + a + added_consts[i] + block_words[g]) % 2**32 UpperCamelCase :Tuple = d UpperCamelCase :str = c UpperCamelCase :Tuple = b UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , left_rotate_aa(__magic_name__ , shift_amounts[i] ) ) # Add hashed chunk to running total UpperCamelCase :List[str] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :str = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :int = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : list ) -> int: """simple docstring""" _enforce_args(__magic_name__ , __magic_name__ ) if n == 0: return 0 UpperCamelCase :List[Any] = float("""-inf""" ) for i in range(1 , n + 1 ): UpperCamelCase :Optional[Any] = max( __magic_name__ , prices[i - 1] + naive_cut_rod_recursive(n - i , __magic_name__ ) ) return max_revue def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : list ) -> Union[str, Any]: """simple docstring""" _enforce_args(__magic_name__ , __magic_name__ ) UpperCamelCase :Tuple = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(__magic_name__ , __magic_name__ , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : list , __magic_name__ : list ) -> Union[str, Any]: """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: UpperCamelCase :Optional[int] = float("""-inf""" ) for i in range(1 , n + 1 ): UpperCamelCase :List[str] = max( __magic_name__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , __magic_name__ , __magic_name__ ) , ) UpperCamelCase :List[str] = max_revenue return max_rev[n] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : list ) -> str: """simple docstring""" _enforce_args(__magic_name__ , __magic_name__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. UpperCamelCase :Tuple = [float("""-inf""" ) for _ in range(n + 1 )] UpperCamelCase :Any = 0 for i in range(1 , n + 1 ): UpperCamelCase :Tuple = max_rev[i] for j in range(1 , i + 1 ): UpperCamelCase :Union[str, Any] = max(__magic_name__ , prices[j - 1] + max_rev[i - j] ) UpperCamelCase :Dict = max_revenue_i return max_rev[n] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : list ) -> Optional[int]: """simple docstring""" if n < 0: UpperCamelCase :Tuple = f"""n must be greater than or equal to 0. Got n = {n}""" raise ValueError(__magic_name__ ) if n > len(__magic_name__ ): UpperCamelCase :Optional[int] = ( """Each integral piece of rod must have a corresponding price. """ f"""Got n = {n} but length of prices = {len(__magic_name__ )}""" ) raise ValueError(__magic_name__ ) def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: """simple docstring""" UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23] UpperCamelCase :Optional[Any] = len(__magic_name__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. UpperCamelCase :Dict = 36 UpperCamelCase :Optional[int] = top_down_cut_rod(__magic_name__ , __magic_name__ ) UpperCamelCase :Any = bottom_up_cut_rod(__magic_name__ , __magic_name__ ) UpperCamelCase :List[Any] = naive_cut_rod_recursive(__magic_name__ , __magic_name__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
38
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[Any] , __lowerCamelCase : Callable , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[dict] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : List[Any] , ): super().__init__( features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = Generator( cache_dir=__lowerCamelCase , features=__lowerCamelCase , generator=__lowerCamelCase , gen_kwargs=__lowerCamelCase , **__lowerCamelCase , ) def _A ( self : List[str] ): # Build iterable dataset if self.streaming: UpperCamelCase :Any = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: UpperCamelCase :Tuple = None UpperCamelCase :Dict = None UpperCamelCase :Dict = None UpperCamelCase :List[str] = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) UpperCamelCase :Tuple = self.builder.as_dataset( split="""train""" , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
38
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase_ : Union[str, Any] = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = ['''CLIPFeatureExtractor'''] UpperCAmelCase_ : Dict = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : str = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase_ : Union[str, Any] = 16 UpperCAmelCase_ : int = 32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 , __magic_name__ : str = "bert-base-cased" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = AutoTokenizer.from_pretrained(__magic_name__ ) UpperCamelCase :Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__magic_name__ : Tuple ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase :List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__magic_name__ , max_length=__magic_name__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase :List[Any] = datasets.map( __magic_name__ , batched=__magic_name__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__magic_name__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase :Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__magic_name__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__magic_name__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__magic_name__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase :List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) UpperCamelCase :List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase :Union[str, Any] = config["""lr"""] UpperCamelCase :List[str] = int(config["""num_epochs"""] ) UpperCamelCase :str = int(config["""seed"""] ) UpperCamelCase :Dict = int(config["""batch_size"""] ) UpperCamelCase :Union[str, Any] = args.model_name_or_path set_seed(__magic_name__ ) UpperCamelCase , UpperCamelCase :Dict = get_dataloaders(__magic_name__ , __magic_name__ , __magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase :List[str] = AutoModelForSequenceClassification.from_pretrained(__magic_name__ , return_dict=__magic_name__ ) # Instantiate optimizer UpperCamelCase :Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase :Optional[Any] = optimizer_cls(params=model.parameters() , lr=__magic_name__ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase :Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase :Any = 1 UpperCamelCase :Dict = (len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase :List[Any] = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=0 , num_training_steps=__magic_name__ , ) else: UpperCamelCase :Any = DummyScheduler(__magic_name__ , total_num_steps=__magic_name__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase :int = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase :Tuple = 0 # Now we train the model UpperCamelCase :Any = evaluate.load("""glue""" , """mrpc""" ) UpperCamelCase :Tuple = 0 UpperCamelCase :List[Any] = {} for epoch in range(__magic_name__ , __magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): UpperCamelCase :List[str] = model(**__magic_name__ ) UpperCamelCase :Dict = outputs.loss UpperCamelCase :Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__magic_name__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCamelCase :str = 0 for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__magic_name__ ) UpperCamelCase :List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase , UpperCamelCase :Optional[int] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__magic_name__ ) - 1: UpperCamelCase :Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) UpperCamelCase :List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __magic_name__ ) UpperCamelCase :Dict = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCamelCase :str = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :List[str] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__magic_name__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__magic_name__ , ) parser.add_argument( """--output_dir""" , type=__magic_name__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__magic_name__ , default=__magic_name__ , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__magic_name__ , default=3 , help="""Number of train epochs.""" , ) UpperCamelCase :str = parser.parse_args() UpperCamelCase :Any = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
38
1
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str]=3 , __lowerCamelCase : List[Any]=32 , __lowerCamelCase : int=3 , __lowerCamelCase : Any=10 , __lowerCamelCase : Optional[int]=[10, 20, 30, 40] , __lowerCamelCase : Tuple=[1, 1, 2, 1] , __lowerCamelCase : Tuple=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Union[str, Any]="relu" , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : Any=None , ): UpperCamelCase :Dict = parent UpperCamelCase :Optional[Any] = batch_size UpperCamelCase :Optional[int] = image_size UpperCamelCase :Dict = num_channels UpperCamelCase :Tuple = embeddings_size UpperCamelCase :Optional[int] = hidden_sizes UpperCamelCase :Any = depths UpperCamelCase :List[str] = is_training UpperCamelCase :int = use_labels UpperCamelCase :Any = hidden_act UpperCamelCase :Optional[int] = num_labels UpperCamelCase :Optional[int] = scope UpperCamelCase :List[Any] = len(__lowerCamelCase ) def _A ( self : int ): UpperCamelCase :int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :int = self.get_config() return config, pixel_values def _A ( self : Optional[int] ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _A ( self : str , __lowerCamelCase : int , __lowerCamelCase : Tuple ): UpperCamelCase :int = FlaxRegNetModel(config=__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _A ( self : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : str ): UpperCamelCase :str = self.num_labels UpperCamelCase :Tuple = FlaxRegNetForImageClassification(config=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Any ): UpperCamelCase :str = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase :Tuple = config_and_inputs UpperCamelCase :int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : int = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () snake_case__ : List[str] = False snake_case__ : Optional[Any] = False snake_case__ : Optional[int] = False def _A ( self : Any ): UpperCamelCase :Any = FlaxRegNetModelTester(self ) UpperCamelCase :Tuple = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def _A ( self : str ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _A ( self : List[Any] ): return def _A ( self : int ): UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def _A ( self : Any ): pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def _A ( self : Union[str, Any] ): pass def _A ( self : str ): UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(__lowerCamelCase ) UpperCamelCase :Dict = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Any = [*signature.parameters.keys()] UpperCamelCase :Dict = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _A ( self : List[str] ): def check_hidden_states_output(__lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple ): UpperCamelCase :Union[str, Any] = model_class(__lowerCamelCase ) UpperCamelCase :str = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) UpperCamelCase :str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase :str = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) , expected_num_stages + 1 ) UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase :int = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase :Tuple = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = model_class(__lowerCamelCase ) @jax.jit def model_jitted(__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Optional[int] ): return model(pixel_values=__lowerCamelCase , **__lowerCamelCase ) with self.subTest("""JIT Enabled""" ): UpperCamelCase :Dict = model_jitted(**__lowerCamelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase :Optional[Any] = 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 ) def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" UpperCamelCase :Any = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def _A ( self : Optional[Any] ): return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040""" ) if is_vision_available() else None @slow def _A ( self : Any ): UpperCamelCase :Any = FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040""" ) UpperCamelCase :Optional[int] = self.default_image_processor UpperCamelCase :Dict = prepare_img() UpperCamelCase :Union[str, Any] = image_processor(images=__lowerCamelCase , return_tensors="""np""" ) UpperCamelCase :List[Any] = model(**__lowerCamelCase ) # verify the logits UpperCamelCase :int = (1, 1_000) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) )
38
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[Any] = TransfoXLTokenizer snake_case__ : List[Any] = False snake_case__ : Tuple = False def _A ( self : str ): super().setUp() UpperCamelCase :Dict = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _A ( self : List[str] , **__lowerCamelCase : Any ): UpperCamelCase :Any = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : int ): UpperCamelCase :List[Any] = """<unk> UNwanted , running""" UpperCamelCase :int = """<unk> unwanted, running""" return input_text, output_text def _A ( self : Tuple ): UpperCamelCase :List[str] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__lowerCamelCase ) UpperCamelCase :Any = tokenizer.tokenize("""<unk> UNwanted , running""" ) self.assertListEqual(__lowerCamelCase , ["""<unk>""", """unwanted""", """,""", """running"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [0, 4, 8, 7] ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _A ( self : Tuple ): UpperCamelCase :Any = TransfoXLTokenizer(lower_case=__lowerCamelCase ) UpperCamelCase :Optional[int] = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" UpperCamelCase :Optional[int] = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(__lowerCamelCase ) , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = len(__lowerCamelCase ) tokenizer.add_tokens(["""new1""", """new2"""] ) tokenizer.move_added_token("""new1""" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , """new1""" )
38
1
print((lambda quine: quine % quine)('''print((lambda quine: quine %% quine)(%r))'''))
38
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase_ : int = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[int] ) -> Dict: """simple docstring""" for attribute in key.split(""".""" ): UpperCamelCase :Dict = getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: UpperCamelCase :Optional[int] = getattr(__magic_name__ , __magic_name__ ).shape else: UpperCamelCase :Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCamelCase :str = value elif weight_type == "weight_g": UpperCamelCase :int = value elif weight_type == "weight_v": UpperCamelCase :int = value elif weight_type == "bias": UpperCamelCase :List[Any] = value else: UpperCamelCase :Any = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Dict = fairseq_model.state_dict() UpperCamelCase :int = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase :str = False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == """group""" , ) UpperCamelCase :Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase :Optional[int] = True if "*" in mapped_key: UpperCamelCase :List[Any] = name.split(__magic_name__ )[0].split(""".""" )[-2] UpperCamelCase :int = mapped_key.replace("""*""" , __magic_name__ ) if "weight_g" in name: UpperCamelCase :List[Any] = """weight_g""" elif "weight_v" in name: UpperCamelCase :List[Any] = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase :Any = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase :List[str] = """weight""" else: UpperCamelCase :Optional[int] = None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int , __magic_name__ : List[str] ) -> Dict: """simple docstring""" UpperCamelCase :Dict = full_name.split("""conv_layers.""" )[-1] UpperCamelCase :int = name.split(""".""" ) UpperCamelCase :str = int(items[0] ) UpperCamelCase :str = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCamelCase :Dict = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCamelCase :Union[str, Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : List[Any] , __magic_name__ : str=None ) -> int: """simple docstring""" UpperCamelCase :List[Any] = torch.load(__magic_name__ ) UpperCamelCase :List[Any] = WavLMConfigOrig(checkpoint["""cfg"""] ) UpperCamelCase :int = WavLMOrig(__magic_name__ ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: UpperCamelCase :List[Any] = WavLMConfig.from_pretrained(__magic_name__ ) else: UpperCamelCase :Any = WavLMConfig() UpperCamelCase :Dict = WavLMModel(__magic_name__ ) recursively_load_weights(__magic_name__ , __magic_name__ ) hf_wavlm.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') UpperCAmelCase_ : Optional[int] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
38
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Union[str, Any] = """naver-clova-ix/donut-base-finetuned-docvqa""" snake_case__ : int = ( """This is a tool that answers a question about an document (pdf). It takes an input named `document` which """ """should be the document containing the information, as well as a `question` that is the question about the """ """document. It returns a text that contains the answer to the question.""" ) snake_case__ : Any = """document_qa""" snake_case__ : List[str] = AutoProcessor snake_case__ : Optional[Any] = VisionEncoderDecoderModel snake_case__ : Optional[Any] = ["""image""", """text"""] snake_case__ : Tuple = ["""text"""] def __init__( self : Optional[int] , *__lowerCamelCase : Tuple , **__lowerCamelCase : Optional[int] ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : "Image" , __lowerCamelCase : str ): UpperCamelCase :int = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" UpperCamelCase :List[Any] = task_prompt.replace("""{user_input}""" , __lowerCamelCase ) UpperCamelCase :Tuple = self.pre_processor.tokenizer( __lowerCamelCase , add_special_tokens=__lowerCamelCase , return_tensors="""pt""" ).input_ids UpperCamelCase :List[str] = self.pre_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def _A ( self : Union[str, Any] , __lowerCamelCase : List[Any] ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=__lowerCamelCase , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=__lowerCamelCase , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=__lowerCamelCase , ).sequences def _A ( self : Union[str, Any] , __lowerCamelCase : str ): UpperCamelCase :Optional[int] = self.pre_processor.batch_decode(__lowerCamelCase )[0] UpperCamelCase :Any = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) UpperCamelCase :List[Any] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) UpperCamelCase :Optional[int] = re.sub(R"""<.*?>""" , """""" , __lowerCamelCase , count=1 ).strip() # remove first task start token UpperCamelCase :str = self.pre_processor.tokenajson(__lowerCamelCase ) return sequence["answer"]
38
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCAmelCase_ : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""bs4"""] ) super().__init__(**__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = [] UpperCamelCase :List[str] = [] UpperCamelCase :Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag UpperCamelCase :Optional[Any] = parent.find_all(child.name , recursive=__lowerCamelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCamelCase ) else next(i for i, s in enumerate(__lowerCamelCase , 1 ) if s is child ) ) UpperCamelCase :Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Any = BeautifulSoup(__lowerCamelCase , """html.parser""" ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Tuple = [] UpperCamelCase :Tuple = [] for element in html_code.descendants: if type(__lowerCamelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue UpperCamelCase :Any = html.unescape(__lowerCamelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = self.xpath_soup(__lowerCamelCase ) stringaxtag_seq.append(__lowerCamelCase ) stringaxsubs_seq.append(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Tuple = """""" for tagname, subs in zip(__lowerCamelCase , __lowerCamelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Any , __lowerCamelCase : Dict ): UpperCamelCase :Any = False # Check that strings has a valid type if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = True elif isinstance(__lowerCamelCase , (list, tuple) ): if len(__lowerCamelCase ) == 0 or isinstance(html_strings[0] , __lowerCamelCase ): UpperCamelCase :Any = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ F"""but is of type {type(__lowerCamelCase )}.""" ) UpperCamelCase :str = bool(isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(html_strings[0] , __lowerCamelCase )) ) if not is_batched: UpperCamelCase :Any = [html_strings] # Get nodes + xpaths UpperCamelCase :Union[str, Any] = [] UpperCamelCase :str = [] for html_string in html_strings: UpperCamelCase , UpperCamelCase , UpperCamelCase :int = self.get_three_from_single(__lowerCamelCase ) nodes.append(__lowerCamelCase ) UpperCamelCase :int = [] for node, tag_list, sub_list in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): UpperCamelCase :str = self.construct_xpath(__lowerCamelCase , __lowerCamelCase ) xpath_strings.append(__lowerCamelCase ) xpaths.append(__lowerCamelCase ) # return as Dict UpperCamelCase :Optional[int] = {"""nodes""": nodes, """xpaths""": xpaths} UpperCamelCase :Any = BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) return encoded_inputs
38
1
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCAmelCase_ : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""bs4"""] ) super().__init__(**__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = [] UpperCamelCase :List[str] = [] UpperCamelCase :Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag UpperCamelCase :Optional[Any] = parent.find_all(child.name , recursive=__lowerCamelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCamelCase ) else next(i for i, s in enumerate(__lowerCamelCase , 1 ) if s is child ) ) UpperCamelCase :Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Any = BeautifulSoup(__lowerCamelCase , """html.parser""" ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Tuple = [] UpperCamelCase :Tuple = [] for element in html_code.descendants: if type(__lowerCamelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue UpperCamelCase :Any = html.unescape(__lowerCamelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = self.xpath_soup(__lowerCamelCase ) stringaxtag_seq.append(__lowerCamelCase ) stringaxsubs_seq.append(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Tuple = """""" for tagname, subs in zip(__lowerCamelCase , __lowerCamelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Any , __lowerCamelCase : Dict ): UpperCamelCase :Any = False # Check that strings has a valid type if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = True elif isinstance(__lowerCamelCase , (list, tuple) ): if len(__lowerCamelCase ) == 0 or isinstance(html_strings[0] , __lowerCamelCase ): UpperCamelCase :Any = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ F"""but is of type {type(__lowerCamelCase )}.""" ) UpperCamelCase :str = bool(isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(html_strings[0] , __lowerCamelCase )) ) if not is_batched: UpperCamelCase :Any = [html_strings] # Get nodes + xpaths UpperCamelCase :Union[str, Any] = [] UpperCamelCase :str = [] for html_string in html_strings: UpperCamelCase , UpperCamelCase , UpperCamelCase :int = self.get_three_from_single(__lowerCamelCase ) nodes.append(__lowerCamelCase ) UpperCamelCase :int = [] for node, tag_list, sub_list in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): UpperCamelCase :str = self.construct_xpath(__lowerCamelCase , __lowerCamelCase ) xpath_strings.append(__lowerCamelCase ) xpaths.append(__lowerCamelCase ) # return as Dict UpperCamelCase :Optional[int] = {"""nodes""": nodes, """xpaths""": xpaths} UpperCamelCase :Any = BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) return encoded_inputs
38
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : list[int] ) -> bool: """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : list[int] , __magic_name__ : int ) -> bool: """simple docstring""" if curr_ind == len(__magic_name__ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__magic_name__ ) ): if valid_connection(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): # Insert current vertex into path as next transition UpperCamelCase :str = next_ver # Validate created path if util_hamilton_cycle(__magic_name__ , __magic_name__ , curr_ind + 1 ): return True # Backtrack UpperCamelCase :Union[str, Any] = -1 return False def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int = 0 ) -> list[int]: """simple docstring""" UpperCamelCase :Union[str, Any] = [-1] * (len(__magic_name__ ) + 1) # initialize start and end of path with starting index UpperCamelCase :Any = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__magic_name__ , __magic_name__ , 1 ) else []
38
1
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ : Optional[Any] = { '''configuration_autoformer''': [ '''AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AutoformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AutoformerForPrediction''', '''AutoformerModel''', '''AutoformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys UpperCAmelCase_ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : str=7 , __lowerCamelCase : Tuple=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Any=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : str=False , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : Any=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : List[Any]=12 , __lowerCamelCase : int=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Optional[int]="last" , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[str]=None , ): UpperCamelCase :int = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :str = seq_length UpperCamelCase :Optional[int] = is_training UpperCamelCase :Optional[int] = use_input_lengths UpperCamelCase :Union[str, Any] = use_token_type_ids UpperCamelCase :List[str] = use_labels UpperCamelCase :Dict = gelu_activation UpperCamelCase :Optional[int] = sinusoidal_embeddings UpperCamelCase :List[Any] = causal UpperCamelCase :Optional[int] = asm UpperCamelCase :List[str] = n_langs UpperCamelCase :int = vocab_size UpperCamelCase :List[Any] = n_special UpperCamelCase :List[Any] = hidden_size UpperCamelCase :List[str] = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :Tuple = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :List[str] = type_vocab_size UpperCamelCase :Union[str, Any] = type_sequence_label_size UpperCamelCase :int = initializer_range UpperCamelCase :List[str] = num_labels UpperCamelCase :Optional[int] = num_choices UpperCamelCase :Optional[Any] = summary_type UpperCamelCase :Tuple = use_proj UpperCamelCase :Optional[Any] = scope def _A ( self : List[str] ): UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Any = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :List[Any] = None if self.use_input_lengths: UpperCamelCase :Dict = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase :str = None if self.use_token_type_ids: UpperCamelCase :int = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase :Optional[int] = None UpperCamelCase :int = None UpperCamelCase :List[Any] = None if self.use_labels: UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :List[str] = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase :List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _A ( self : List[Any] ): return 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 , ) def _A ( self : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : int , ): UpperCamelCase :Tuple = FlaubertModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :int = model(__lowerCamelCase , lengths=__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :List[Any] = model(__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , ): UpperCamelCase :Any = FlaubertWithLMHeadModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Dict = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Any = FlaubertForQuestionAnsweringSimple(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) 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 _A ( self : str , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : str , ): UpperCamelCase :str = FlaubertForQuestionAnswering(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :Optional[int] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , p_mask=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , ) ((UpperCamelCase) , ) :int = result_with_labels.to_tuple() UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) ((UpperCamelCase) , ) :List[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , ): UpperCamelCase :Optional[int] = FlaubertForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Tuple = model(__lowerCamelCase ) UpperCamelCase :List[str] = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A ( self : Any , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Dict = self.num_labels UpperCamelCase :Tuple = FlaubertForTokenClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Union[str, Any] = self.num_choices UpperCamelCase :List[Any] = FlaubertForMultipleChoice(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A ( self : str ): UpperCamelCase :List[str] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :List[Any] = config_and_inputs UpperCamelCase :Union[str, Any] = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[int] = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _A ( self : int , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ): 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 _A ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ): UpperCamelCase :Tuple = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": UpperCamelCase :Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) UpperCamelCase :List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def _A ( self : str ): UpperCamelCase :List[Any] = FlaubertModelTester(self ) UpperCamelCase :Any = ConfigTester(self , config_class=__lowerCamelCase , emb_dim=37 ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__lowerCamelCase ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__lowerCamelCase ) def _A ( self : int ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__lowerCamelCase ) @slow def _A ( self : Any ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Optional[int] = FlaubertModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @slow @require_torch_gpu def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = model_class(config=__lowerCamelCase ) UpperCamelCase :str = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :str = torch.jit.trace( __lowerCamelCase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__lowerCamelCase , os.path.join(__lowerCamelCase , """traced_model.pt""" ) ) UpperCamelCase :int = torch.jit.load(os.path.join(__lowerCamelCase , """traced_model.pt""" ) , map_location=__lowerCamelCase ) loaded(inputs_dict["""input_ids"""].to(__lowerCamelCase ) , inputs_dict["""attention_mask"""].to(__lowerCamelCase ) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) UpperCamelCase :Optional[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): UpperCamelCase :Tuple = model(__lowerCamelCase )[0] UpperCamelCase :Union[str, Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :int = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
38
1
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging UpperCAmelCase_ : Tuple = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = R"""\w+[.]\d+""" UpperCamelCase :int = re.findall(__magic_name__ , __magic_name__ ) for pat in pats: UpperCamelCase :List[str] = key.replace(__magic_name__ , """_""".join(pat.split(""".""" ) ) ) return key def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[int] ) -> Tuple: """simple docstring""" UpperCamelCase :Optional[Any] = pt_tuple_key[:-1] + ("""scale""",) if ( any("""norm""" in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): UpperCamelCase :List[str] = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: UpperCamelCase :Optional[Any] = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: UpperCamelCase :Optional[Any] = pt_tuple_key[:-1] + ("""embedding""",) return renamed_pt_tuple_key, pt_tensor # conv layer UpperCamelCase :Dict = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: UpperCamelCase :Any = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer UpperCamelCase :Dict = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight": UpperCamelCase :Optional[Any] = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight UpperCamelCase :str = pt_tuple_key[:-1] + ("""weight""",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias UpperCamelCase :Optional[int] = pt_tuple_key[:-1] + ("""bias""",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Tuple=42 ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :Any = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params UpperCamelCase :Tuple = flax_model.init_weights(PRNGKey(__magic_name__ ) ) UpperCamelCase :Any = flatten_dict(__magic_name__ ) UpperCamelCase :Optional[int] = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): UpperCamelCase :Union[str, Any] = rename_key(__magic_name__ ) UpperCamelCase :Optional[Any] = tuple(renamed_pt_key.split(""".""" ) ) # Correctly rename weight parameters UpperCamelCase , UpperCamelCase :Tuple = rename_key_and_reshape_tensor(__magic_name__ , __magic_name__ , __magic_name__ ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """ f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) # also add unexpected weight so that warning is thrown UpperCamelCase :List[Any] = jnp.asarray(__magic_name__ ) return unflatten_dict(__magic_name__ )
38
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """openai/whisper-base""" snake_case__ : Optional[int] = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) snake_case__ : Any = """transcriber""" snake_case__ : Optional[int] = WhisperProcessor snake_case__ : str = WhisperForConditionalGeneration snake_case__ : Optional[Any] = ["""audio"""] snake_case__ : Any = ["""text"""] def _A ( self : str , __lowerCamelCase : Dict ): return self.pre_processor(__lowerCamelCase , return_tensors="""pt""" ).input_features def _A ( self : Dict , __lowerCamelCase : List[Any] ): return self.model.generate(inputs=__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : Optional[Any] ): return self.pre_processor.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase )[0]
38
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase_ : Optional[int] = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[int] = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase_ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=_a ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) snake_case__ : ClassVar[Features] = Features({"""audio""": Audio()} ) snake_case__ : ClassVar[Features] = Features({"""transcription""": Value("""string""" )} ) snake_case__ : str = "audio" snake_case__ : str = "transcription" def _A ( self : List[str] , __lowerCamelCase : Dict ): if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) UpperCamelCase :int = copy.deepcopy(self ) UpperCamelCase :Any = self.input_schema.copy() UpperCamelCase :List[str] = features[self.audio_column] UpperCamelCase :List[Any] = input_schema return task_template @property def _A ( self : Optional[int] ): return {self.audio_column: "audio", self.transcription_column: "transcription"}
38
1
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase_ : Union[str, Any] = 16 UpperCAmelCase_ : int = 32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 , __magic_name__ : str = "bert-base-cased" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = AutoTokenizer.from_pretrained(__magic_name__ ) UpperCamelCase :Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__magic_name__ : Tuple ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase :List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__magic_name__ , max_length=__magic_name__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase :List[Any] = datasets.map( __magic_name__ , batched=__magic_name__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__magic_name__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase :Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__magic_name__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__magic_name__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__magic_name__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase :List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) UpperCamelCase :List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase :Union[str, Any] = config["""lr"""] UpperCamelCase :List[str] = int(config["""num_epochs"""] ) UpperCamelCase :str = int(config["""seed"""] ) UpperCamelCase :Dict = int(config["""batch_size"""] ) UpperCamelCase :Union[str, Any] = args.model_name_or_path set_seed(__magic_name__ ) UpperCamelCase , UpperCamelCase :Dict = get_dataloaders(__magic_name__ , __magic_name__ , __magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase :List[str] = AutoModelForSequenceClassification.from_pretrained(__magic_name__ , return_dict=__magic_name__ ) # Instantiate optimizer UpperCamelCase :Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase :Optional[Any] = optimizer_cls(params=model.parameters() , lr=__magic_name__ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase :Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase :Any = 1 UpperCamelCase :Dict = (len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase :List[Any] = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=0 , num_training_steps=__magic_name__ , ) else: UpperCamelCase :Any = DummyScheduler(__magic_name__ , total_num_steps=__magic_name__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase :int = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase :Tuple = 0 # Now we train the model UpperCamelCase :Any = evaluate.load("""glue""" , """mrpc""" ) UpperCamelCase :Tuple = 0 UpperCamelCase :List[Any] = {} for epoch in range(__magic_name__ , __magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): UpperCamelCase :List[str] = model(**__magic_name__ ) UpperCamelCase :Dict = outputs.loss UpperCamelCase :Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__magic_name__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCamelCase :str = 0 for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__magic_name__ ) UpperCamelCase :List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase , UpperCamelCase :Optional[int] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__magic_name__ ) - 1: UpperCamelCase :Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) UpperCamelCase :List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __magic_name__ ) UpperCamelCase :Dict = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCamelCase :str = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :List[str] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__magic_name__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__magic_name__ , ) parser.add_argument( """--output_dir""" , type=__magic_name__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__magic_name__ , default=__magic_name__ , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__magic_name__ , default=3 , help="""Number of train epochs.""" , ) UpperCamelCase :str = parser.parse_args() UpperCamelCase :Any = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
38
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
38
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
38
import re import string import numpy as np import datasets UpperCAmelCase_ : Dict = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' UpperCAmelCase_ : Any = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' UpperCAmelCase_ : Tuple = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def _A ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : int=False , __lowerCamelCase : Optional[int]=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase :str = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in predictions] ) UpperCamelCase :Tuple = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in references] ) else: UpperCamelCase :Any = np.asarray(__lowerCamelCase ) UpperCamelCase :str = np.asarray(__lowerCamelCase ) if ignore_case: UpperCamelCase :Tuple = np.char.lower(__lowerCamelCase ) UpperCamelCase :Any = np.char.lower(__lowerCamelCase ) if ignore_punctuation: UpperCamelCase :Optional[int] = string.punctuation.maketrans("""""" , """""" , string.punctuation ) UpperCamelCase :Optional[Any] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :List[str] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) if ignore_numbers: UpperCamelCase :Tuple = string.digits.maketrans("""""" , """""" , string.digits ) UpperCamelCase :Dict = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :Tuple = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :int = predictions == references return {"exact_match": np.mean(__lowerCamelCase ) * 100}
38
1
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[Any] = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) snake_case__ : Any = ( { """feature-extraction""": TFMobileBertModel, """fill-mask""": TFMobileBertForMaskedLM, """question-answering""": TFMobileBertForQuestionAnswering, """text-classification""": TFMobileBertForSequenceClassification, """token-classification""": TFMobileBertForTokenClassification, """zero-shot""": TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) snake_case__ : Union[str, Any] = False snake_case__ : Dict = False def _A ( self : List[Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : int , __lowerCamelCase : int=False ): UpperCamelCase :Dict = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class in get_values(__lowerCamelCase ): UpperCamelCase :List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str=13 , __lowerCamelCase : List[Any]=7 , __lowerCamelCase : str=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Dict=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : Union[str, Any]=32 , __lowerCamelCase : Optional[int]=32 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : List[Any]=4 , __lowerCamelCase : Tuple=37 , __lowerCamelCase : Any="gelu" , __lowerCamelCase : Any=0.1 , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : Tuple=512 , __lowerCamelCase : Dict=16 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : Any=0.02 , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : List[str]=None , ): UpperCamelCase :Optional[int] = parent UpperCamelCase :str = batch_size UpperCamelCase :Optional[int] = seq_length UpperCamelCase :Optional[Any] = is_training UpperCamelCase :List[str] = use_input_mask UpperCamelCase :Union[str, Any] = use_token_type_ids UpperCamelCase :Tuple = use_labels UpperCamelCase :Union[str, Any] = vocab_size UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :Any = num_hidden_layers UpperCamelCase :List[str] = num_attention_heads UpperCamelCase :List[str] = intermediate_size UpperCamelCase :int = hidden_act UpperCamelCase :Any = hidden_dropout_prob UpperCamelCase :int = attention_probs_dropout_prob UpperCamelCase :str = max_position_embeddings UpperCamelCase :str = type_vocab_size UpperCamelCase :Union[str, Any] = type_sequence_label_size UpperCamelCase :Tuple = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :Union[str, Any] = num_choices UpperCamelCase :List[Any] = scope UpperCamelCase :Any = embedding_size def _A ( self : Dict ): UpperCamelCase :Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :List[Any] = None if self.use_input_mask: UpperCamelCase :Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :Tuple = None if self.use_token_type_ids: UpperCamelCase :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase :Optional[int] = None UpperCamelCase :Dict = None UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _A ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : Dict ): UpperCamelCase :Dict = TFMobileBertModel(config=__lowerCamelCase ) UpperCamelCase :Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :str = model(__lowerCamelCase ) UpperCamelCase :Any = [input_ids, input_mask] UpperCamelCase :Dict = model(__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase ) 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 _A ( self : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ): UpperCamelCase :Optional[Any] = TFMobileBertForMaskedLM(config=__lowerCamelCase ) UpperCamelCase :int = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : int , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : int ): UpperCamelCase :str = TFMobileBertForNextSentencePrediction(config=__lowerCamelCase ) UpperCamelCase :Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def _A ( self : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ): UpperCamelCase :Optional[int] = TFMobileBertForPreTraining(config=__lowerCamelCase ) UpperCamelCase :Any = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :Any = model(__lowerCamelCase ) self.parent.assertEqual( result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def _A ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ): UpperCamelCase :int = self.num_labels UpperCamelCase :Union[str, Any] = TFMobileBertForSequenceClassification(config=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : int ): UpperCamelCase :str = self.num_choices UpperCamelCase :List[str] = TFMobileBertForMultipleChoice(config=__lowerCamelCase ) UpperCamelCase :Dict = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :Tuple = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :Optional[Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :int = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } UpperCamelCase :List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A ( self : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Dict ): UpperCamelCase :str = self.num_labels UpperCamelCase :int = TFMobileBertForTokenClassification(config=__lowerCamelCase ) UpperCamelCase :Dict = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :Tuple = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Any ): UpperCamelCase :Union[str, Any] = TFMobileBertForQuestionAnswering(config=__lowerCamelCase ) UpperCamelCase :Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase :Tuple = model(__lowerCamelCase ) 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 _A ( self : str ): UpperCamelCase :Tuple = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Dict = config_and_inputs UpperCamelCase :Optional[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict def _A ( self : Tuple ): UpperCamelCase :int = TFMobileBertModelTest.TFMobileBertModelTester(self ) UpperCamelCase :Dict = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=37 ) def _A ( self : int ): self.config_tester.run_common_tests() def _A ( self : List[Any] ): UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*__lowerCamelCase ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__lowerCamelCase ) def _A ( self : str ): UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__lowerCamelCase ) def _A ( self : Dict ): UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*__lowerCamelCase ) def _A ( self : Any ): UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__lowerCamelCase ) def _A ( self : Any ): UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*__lowerCamelCase ) @slow def _A ( self : int ): # for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["google/mobilebert-uncased"]: UpperCamelCase :Optional[int] = TFMobileBertModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _A ( self : Tuple ): UpperCamelCase :List[Any] = TFMobileBertForPreTraining.from_pretrained("""google/mobilebert-uncased""" ) UpperCamelCase :str = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase :Dict = model(__lowerCamelCase )[0] UpperCamelCase :str = [1, 6, 30_522] self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :int = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 )
38
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : str = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """layoutlmv3""" def __init__( self : List[Any] , __lowerCamelCase : Optional[Any]=50_265 , __lowerCamelCase : Dict=768 , __lowerCamelCase : Any=12 , __lowerCamelCase : int=12 , __lowerCamelCase : str=3_072 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : Optional[Any]=512 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Union[str, Any]=0.02 , __lowerCamelCase : Union[str, Any]=1E-5 , __lowerCamelCase : Any=1 , __lowerCamelCase : Optional[int]=0 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Dict=1_024 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=128 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : str=32 , __lowerCamelCase : List[Any]=128 , __lowerCamelCase : str=64 , __lowerCamelCase : List[str]=256 , __lowerCamelCase : Dict=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Tuple=224 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Dict=16 , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : Optional[Any] , ): super().__init__( 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 , initializer_range=__lowerCamelCase , layer_norm_eps=__lowerCamelCase , pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :int = max_ad_position_embeddings UpperCamelCase :Tuple = coordinate_size UpperCamelCase :List[Any] = shape_size UpperCamelCase :Union[str, Any] = has_relative_attention_bias UpperCamelCase :Any = rel_pos_bins UpperCamelCase :Optional[Any] = max_rel_pos UpperCamelCase :str = has_spatial_attention_bias UpperCamelCase :Tuple = rel_ad_pos_bins UpperCamelCase :Optional[int] = max_rel_ad_pos UpperCamelCase :Tuple = text_embed UpperCamelCase :str = visual_embed UpperCamelCase :Optional[Any] = input_size UpperCamelCase :str = num_channels UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[Any] = classifier_dropout class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = version.parse("""1.12""" ) @property def _A ( self : Optional[int] ): # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def _A ( self : str ): return 1E-5 @property def _A ( self : Dict ): return 12 def _A ( self : Dict , __lowerCamelCase : "ProcessorMixin" , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional["TensorType"] = None , __lowerCamelCase : int = 3 , __lowerCamelCase : int = 40 , __lowerCamelCase : int = 40 , ): setattr(processor.image_processor , """apply_ocr""" , __lowerCamelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase :Optional[Any] = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase :Optional[int] = processor.tokenizer.num_special_tokens_to_add(__lowerCamelCase ) UpperCamelCase :int = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase :Any = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase :Optional[Any] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase :List[str] = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = dict( processor( __lowerCamelCase , text=__lowerCamelCase , boxes=__lowerCamelCase , return_tensors=__lowerCamelCase , ) ) return inputs
38
1
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 _SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : List[str]=True , __lowerCamelCase : Dict=False , __lowerCamelCase : Any=10 , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : Optional[Any]=32 * 8 , __lowerCamelCase : Tuple=32 * 8 , __lowerCamelCase : Union[str, Any]=4 , __lowerCamelCase : Tuple=64 , ): UpperCamelCase :int = parent UpperCamelCase :Optional[Any] = batch_size UpperCamelCase :Tuple = is_training UpperCamelCase :Tuple = use_auxiliary_loss UpperCamelCase :Dict = num_queries UpperCamelCase :Any = num_channels UpperCamelCase :List[Any] = min_size UpperCamelCase :Any = max_size UpperCamelCase :List[str] = num_labels UpperCamelCase :Dict = hidden_dim UpperCamelCase :Optional[Any] = hidden_dim def _A ( self : Any ): UpperCamelCase :Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __lowerCamelCase ) UpperCamelCase :Optional[int] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__lowerCamelCase ) UpperCamelCase :Optional[Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__lowerCamelCase ) > 0.5 ).float() UpperCamelCase :Any = (torch.rand((self.batch_size, self.num_labels) , device=__lowerCamelCase ) > 0.5).long() UpperCamelCase :List[Any] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _A ( self : Optional[int] ): UpperCamelCase :int = MaskaFormerConfig( hidden_size=self.hidden_dim , ) UpperCamelCase :Tuple = self.num_queries UpperCamelCase :Optional[Any] = self.num_labels UpperCamelCase :Any = [1, 1, 1, 1] UpperCamelCase :List[str] = self.num_channels UpperCamelCase :int = 64 UpperCamelCase :Union[str, Any] = 128 UpperCamelCase :Optional[Any] = self.hidden_dim UpperCamelCase :List[Any] = self.hidden_dim UpperCamelCase :List[str] = self.hidden_dim return config def _A ( self : List[Any] ): UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[str] = self.prepare_config_and_inputs() UpperCamelCase :List[Any] = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def _A ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : Optional[int] ): UpperCamelCase :Optional[Any] = output.encoder_hidden_states UpperCamelCase :Optional[Any] = output.pixel_decoder_hidden_states UpperCamelCase :Dict = 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 _A ( self : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any]=False ): with torch.no_grad(): UpperCamelCase :Optional[Any] = MaskaFormerModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :List[str] = model(pixel_values=__lowerCamelCase , pixel_mask=__lowerCamelCase ) UpperCamelCase :Tuple = 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 _A ( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : int ): UpperCamelCase :Optional[int] = MaskaFormerForUniversalSegmentation(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() def comm_check_on_output(__lowerCamelCase : Optional[Any] ): # 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(): UpperCamelCase :Optional[int] = model(pixel_values=__lowerCamelCase , pixel_mask=__lowerCamelCase ) UpperCamelCase :Any = model(__lowerCamelCase ) comm_check_on_output(__lowerCamelCase ) UpperCamelCase :Tuple = 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 _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Dict = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () snake_case__ : List[Any] = {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {} snake_case__ : List[str] = False snake_case__ : Any = False snake_case__ : Optional[int] = False snake_case__ : Tuple = False def _A ( self : List[str] ): UpperCamelCase :str = MaskaFormerModelTester(self ) UpperCamelCase :Union[str, Any] = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() def _A ( self : str ): UpperCamelCase , UpperCamelCase :List[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 _A ( self : Union[str, Any] ): UpperCamelCase :List[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 _A ( self : List[Any] ): pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" ) def _A ( self : str ): pass @unittest.skip(reason="""Mask2Former is not a generative model""" ) def _A ( self : str ): pass @unittest.skip(reason="""Mask2Former does not use token embeddings""" ) def _A ( 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 _A ( self : Optional[Any] ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _A ( self : Dict ): pass def _A ( self : str ): UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(__lowerCamelCase ) UpperCamelCase :str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Dict = [*signature.parameters.keys()] UpperCamelCase :Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) @slow def _A ( self : int ): for model_name in ["facebook/mask2former-swin-small-coco-instance"]: UpperCamelCase :int = MaskaFormerModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def _A ( self : List[str] ): UpperCamelCase :Dict = (self.model_tester.min_size,) * 2 UpperCamelCase :Tuple = { """pixel_values""": torch.randn((2, 3, *size) , device=__lowerCamelCase ), """mask_labels""": torch.randn((2, 10, *size) , device=__lowerCamelCase ), """class_labels""": torch.zeros(2 , 10 , device=__lowerCamelCase ).long(), } UpperCamelCase :str = self.model_tester.get_config() UpperCamelCase :str = MaskaFormerForUniversalSegmentation(__lowerCamelCase ).to(__lowerCamelCase ) UpperCamelCase :Optional[Any] = model(**__lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def _A ( self : Dict ): UpperCamelCase , UpperCamelCase :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 _A ( self : Dict ): UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Optional[int] = model_class(__lowerCamelCase ).to(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = model(**__lowerCamelCase , output_attentions=__lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def _A ( self : List[str] ): if not self.model_tester.is_training: return UpperCamelCase :Dict = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() UpperCamelCase :Optional[Any] = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() UpperCamelCase :int = model(__lowerCamelCase , mask_labels=__lowerCamelCase , class_labels=__lowerCamelCase ).loss loss.backward() def _A ( self : List[str] ): UpperCamelCase :Optional[int] = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() UpperCamelCase :List[Any] = True UpperCamelCase :str = True UpperCamelCase :int = model_class(__lowerCamelCase ).to(__lowerCamelCase ) model.train() UpperCamelCase :Union[str, Any] = model(__lowerCamelCase , mask_labels=__lowerCamelCase , class_labels=__lowerCamelCase ) UpperCamelCase :Optional[Any] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCamelCase :Any = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() UpperCamelCase :Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCamelCase :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 ) UpperCAmelCase_ : Optional[Any] = 1E-4 def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" UpperCamelCase :Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def _A ( self : Tuple ): return "facebook/mask2former-swin-small-coco-instance" @cached_property def _A ( self : Dict ): return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _A ( self : Tuple ): UpperCamelCase :List[Any] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__lowerCamelCase ) UpperCamelCase :Optional[int] = self.default_image_processor UpperCamelCase :Optional[Any] = prepare_img() UpperCamelCase :Optional[Any] = image_processor(__lowerCamelCase , return_tensors="""pt""" ).to(__lowerCamelCase ) UpperCamelCase :str = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__lowerCamelCase , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__lowerCamelCase ) UpperCamelCase :List[str] = 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 ) ) UpperCamelCase :Tuple = 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 ) ) UpperCamelCase :Any = 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 _A ( self : Any ): UpperCamelCase :Dict = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowerCamelCase ).eval() UpperCamelCase :str = self.default_image_processor UpperCamelCase :Dict = prepare_img() UpperCamelCase :str = image_processor(__lowerCamelCase , return_tensors="""pt""" ).to(__lowerCamelCase ) UpperCamelCase :str = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__lowerCamelCase , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase :List[Any] = model(**__lowerCamelCase ) # masks_queries_logits UpperCamelCase :int = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) UpperCamelCase :Any = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] UpperCamelCase :Optional[int] = torch.tensor(__lowerCamelCase ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __lowerCamelCase , atol=__lowerCamelCase ) ) # class_queries_logits UpperCamelCase :List[Any] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) UpperCamelCase :Union[str, Any] = 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 _A ( self : Tuple ): UpperCamelCase :List[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowerCamelCase ).eval() UpperCamelCase :int = self.default_image_processor UpperCamelCase :List[str] = image_processor( [np.zeros((3, 800, 1_333) ), np.zeros((3, 800, 1_333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="""pt""" , ) UpperCamelCase :Optional[Any] = inputs["""pixel_values"""].to(__lowerCamelCase ) UpperCamelCase :Optional[Any] = [el.to(__lowerCamelCase ) for el in inputs["""mask_labels"""]] UpperCamelCase :Any = [el.to(__lowerCamelCase ) for el in inputs["""class_labels"""]] with torch.no_grad(): UpperCamelCase :List[str] = model(**__lowerCamelCase ) self.assertTrue(outputs.loss is not None )
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Any = StableDiffusionXLImgaImgPipeline snake_case__ : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} snake_case__ : Tuple = PipelineTesterMixin.required_optional_params - {"""latents"""} snake_case__ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case__ : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS snake_case__ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=__lowerCamelCase , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) UpperCamelCase :Tuple = EulerDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCamelCase :Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=32 , ) UpperCamelCase :Any = CLIPTextModel(__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :List[Any] = CLIPTextModelWithProjection(__lowerCamelCase ) UpperCamelCase :int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _A ( self : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any]=0 ): UpperCamelCase :Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) UpperCamelCase :List[str] = image / 2 + 0.5 if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :Any = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :List[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def _A ( self : str ): UpperCamelCase :List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase :Optional[Any] = self.get_dummy_components() UpperCamelCase :List[Any] = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :Any = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = sd_pipe(**__lowerCamelCase ).images UpperCamelCase :Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :List[Any] = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : Dict ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _A ( self : Optional[Any] ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _A ( self : Union[str, Any] ): pass def _A ( self : Optional[int] ): UpperCamelCase :Union[str, Any] = self.get_dummy_components() UpperCamelCase :Dict = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) UpperCamelCase :List[Any] = sd_pipe.to(__lowerCamelCase ) UpperCamelCase :List[str] = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) # forward without prompt embeds UpperCamelCase :List[Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :int = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = negative_prompt UpperCamelCase :Union[str, Any] = 3 * [inputs["""prompt"""]] UpperCamelCase :Dict = sd_pipe(**__lowerCamelCase ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = 3 * ["""this is a negative prompt"""] UpperCamelCase :Union[str, Any] = 3 * [inputs.pop("""prompt""" )] ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = sd_pipe.encode_prompt(__lowerCamelCase , negative_prompt=__lowerCamelCase ) UpperCamelCase :Dict = sd_pipe( **__lowerCamelCase , prompt_embeds=__lowerCamelCase , negative_prompt_embeds=__lowerCamelCase , pooled_prompt_embeds=__lowerCamelCase , negative_pooled_prompt_embeds=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Tuple ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict="cpu" , __lowerCamelCase : List[Any]=torch.floataa , __lowerCamelCase : Tuple=0 ): UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = np.random.RandomState(__lowerCamelCase ).standard_normal((1, 4, 64, 64) ) UpperCamelCase :Dict = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase , dtype=__lowerCamelCase ) UpperCamelCase :str = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _A ( self : Optional[Any] ): UpperCamelCase :Any = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = self.get_inputs(__lowerCamelCase ) UpperCamelCase :Optional[int] = pipe(**__lowerCamelCase ).images UpperCamelCase :Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCamelCase :Union[str, Any] = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : str ) -> float: """simple docstring""" def get_matched_characters(__magic_name__ : str , __magic_name__ : str ) -> str: UpperCamelCase :List[Any] = [] UpperCamelCase :List[Any] = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): UpperCamelCase :Union[str, Any] = int(max(0 , i - limit ) ) UpperCamelCase :Optional[int] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(__magic_name__ ) UpperCamelCase :str = f"""{_stra[0:_stra.index(__magic_name__ )]} {_stra[_stra.index(__magic_name__ ) + 1:]}""" return "".join(__magic_name__ ) # matching characters UpperCamelCase :Dict = get_matched_characters(__magic_name__ , __magic_name__ ) UpperCamelCase :List[str] = get_matched_characters(__magic_name__ , __magic_name__ ) UpperCamelCase :Tuple = len(__magic_name__ ) # transposition UpperCamelCase :Tuple = ( len([(ca, ca) for ca, ca in zip(__magic_name__ , __magic_name__ ) if ca != ca] ) // 2 ) if not match_count: UpperCamelCase :List[str] = 0.0 else: UpperCamelCase :Tuple = ( 1 / 3 * ( match_count / len(__magic_name__ ) + match_count / len(__magic_name__ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters UpperCamelCase :str = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('''hello''', '''world'''))
38
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : int = { '''CarlCochet/trajectory-transformer-halfcheetah-medium-v2''': ( '''https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json''' ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """trajectory_transformer""" snake_case__ : Optional[Any] = ["""past_key_values"""] snake_case__ : Tuple = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Union[str, Any] , __lowerCamelCase : Any=100 , __lowerCamelCase : str=5 , __lowerCamelCase : str=1 , __lowerCamelCase : Optional[int]=1 , __lowerCamelCase : int=249 , __lowerCamelCase : str=6 , __lowerCamelCase : Dict=17 , __lowerCamelCase : Optional[Any]=25 , __lowerCamelCase : List[str]=4 , __lowerCamelCase : str=4 , __lowerCamelCase : Tuple=128 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : int=0.0006 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Any=1E-12 , __lowerCamelCase : int=1 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Tuple=1 , __lowerCamelCase : int=50_256 , __lowerCamelCase : Union[str, Any]=50_256 , **__lowerCamelCase : Dict , ): UpperCamelCase :Dict = vocab_size UpperCamelCase :int = action_weight UpperCamelCase :Tuple = reward_weight UpperCamelCase :str = value_weight UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :Tuple = block_size UpperCamelCase :Optional[int] = action_dim UpperCamelCase :int = observation_dim UpperCamelCase :List[str] = transition_dim UpperCamelCase :List[Any] = learning_rate UpperCamelCase :Optional[Any] = n_layer UpperCamelCase :Any = n_head UpperCamelCase :List[str] = n_embd UpperCamelCase :Any = embd_pdrop UpperCamelCase :str = attn_pdrop UpperCamelCase :Union[str, Any] = resid_pdrop UpperCamelCase :Optional[Any] = initializer_range UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Optional[int] = kaiming_initializer_range UpperCamelCase :Tuple = use_cache super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str ) -> bool: """simple docstring""" UpperCamelCase :Union[str, Any] = [int(__magic_name__ ) for i in ip_va_address.split(""".""" ) if i.isdigit()] return len(__magic_name__ ) == 4 and all(0 <= int(__magic_name__ ) <= 254 for octet in octets ) if __name__ == "__main__": UpperCAmelCase_ : int = input().strip() UpperCAmelCase_ : Any = '''valid''' if is_ip_va_address_valid(ip) else '''invalid''' print(F'''{ip} is a {valid_or_invalid} IP v4 address.''')
38
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 3 ) -> qiskit.result.counts.Counts: """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): raise TypeError("""number of qubits must be a integer.""" ) if number_of_qubits <= 0: raise ValueError("""number of qubits must be > 0.""" ) if math.floor(__magic_name__ ) != number_of_qubits: raise ValueError("""number of qubits must be exact integer.""" ) if number_of_qubits > 10: raise ValueError("""number of qubits too large to simulate(>10).""" ) UpperCamelCase :int = QuantumRegister(__magic_name__ , """qr""" ) UpperCamelCase :str = ClassicalRegister(__magic_name__ , """cr""" ) UpperCamelCase :str = QuantumCircuit(__magic_name__ , __magic_name__ ) UpperCamelCase :List[Any] = number_of_qubits for i in range(__magic_name__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(__magic_name__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , __magic_name__ , __magic_name__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(__magic_name__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(__magic_name__ , __magic_name__ ) # simulate with 10000 shots UpperCamelCase :str = Aer.get_backend("""qasm_simulator""" ) UpperCamelCase :Dict = execute(__magic_name__ , __magic_name__ , shots=1_0000 ) return job.result().get_counts(__magic_name__ ) if __name__ == "__main__": print( F'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
38
1
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 10 ) -> str: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ) or n < 0: raise ValueError("""Invalid input""" ) UpperCamelCase :List[Any] = 10**n UpperCamelCase :str = 2_8433 * (pow(2 , 783_0457 , __magic_name__ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'''{solution(10) = }''')
38
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer UpperCAmelCase_ : Optional[Any] = ['''bert-base-uncased''', '''bert-base-cased'''] UpperCAmelCase_ : List[str] = '''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class _SCREAMING_SNAKE_CASE ( tf.keras.Model ): def __init__( self : List[str] , __lowerCamelCase : Union[str, Any] ): super().__init__() UpperCamelCase :Any = tokenizer UpperCamelCase :List[str] = AutoConfig.from_pretrained(__lowerCamelCase ) UpperCamelCase :List[str] = TFAutoModel.from_config(__lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : str ): UpperCamelCase :str = self.tokenizer(__lowerCamelCase ) UpperCamelCase :Any = self.bert(**__lowerCamelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Dict ): super().setUp() UpperCamelCase :int = [ BertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase :Any = [TFBertTokenizer.from_pretrained(__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(__lowerCamelCase , use_fast_bert_tokenizer=__lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase :Any = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] UpperCamelCase :Union[str, Any] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _A ( self : Optional[int] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tokenizer(__lowerCamelCase , return_tensors="""tf""" , padding="""longest""" ) UpperCamelCase :str = tf_tokenizer(__lowerCamelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _A ( self : Dict ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :str = tf_tokenizer(self.paired_sentences ) UpperCamelCase :Any = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _A ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[Any] = tf.function(__lowerCamelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase :Any = tf.constant(__lowerCamelCase ) UpperCamelCase :List[str] = compiled_tokenizer(__lowerCamelCase ) UpperCamelCase :Optional[Any] = tf_tokenizer(__lowerCamelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _A ( self : Tuple ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase :List[str] = ModelToSave(tokenizer=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase :Union[str, Any] = model(__lowerCamelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase :List[str] = Path(__lowerCamelCase ) / """saved.model""" model.save(__lowerCamelCase ) UpperCamelCase :List[Any] = tf.keras.models.load_model(__lowerCamelCase ) UpperCamelCase :Dict = loaded_model(__lowerCamelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
38
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : int = { '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''', } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Union[str, Any] = """blip_2_vision_model""" def __init__( self : Any , __lowerCamelCase : Any=1_408 , __lowerCamelCase : Any=6_144 , __lowerCamelCase : Any=39 , __lowerCamelCase : List[str]=16 , __lowerCamelCase : List[Any]=224 , __lowerCamelCase : List[str]=14 , __lowerCamelCase : Any="gelu" , __lowerCamelCase : List[str]=0.00001 , __lowerCamelCase : Dict=0.0 , __lowerCamelCase : List[str]=1E-10 , __lowerCamelCase : int=True , **__lowerCamelCase : str , ): super().__init__(**__lowerCamelCase ) UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :List[str] = intermediate_size UpperCamelCase :Optional[Any] = num_hidden_layers UpperCamelCase :Union[str, Any] = num_attention_heads UpperCamelCase :List[str] = patch_size UpperCamelCase :str = image_size UpperCamelCase :Optional[int] = initializer_range UpperCamelCase :Optional[int] = attention_dropout UpperCamelCase :Union[str, Any] = layer_norm_eps UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :List[str] = qkv_bias @classmethod def _A ( cls : Tuple , __lowerCamelCase : Union[str, os.PathLike] , **__lowerCamelCase : List[str] ): cls._set_token_in_kwargs(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :List[Any] = cls.get_config_dict(__lowerCamelCase , **__lowerCamelCase ) # get the vision config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": UpperCamelCase :Union[str, Any] = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = """blip_2_qformer""" def __init__( self : Optional[int] , __lowerCamelCase : Optional[Any]=30_522 , __lowerCamelCase : Any=768 , __lowerCamelCase : Union[str, Any]=12 , __lowerCamelCase : Optional[Any]=12 , __lowerCamelCase : List[str]=3_072 , __lowerCamelCase : Union[str, Any]="gelu" , __lowerCamelCase : str=0.1 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : int=512 , __lowerCamelCase : Tuple=0.02 , __lowerCamelCase : Union[str, Any]=1E-12 , __lowerCamelCase : Any=0 , __lowerCamelCase : Tuple="absolute" , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : Optional[Any]=1_408 , **__lowerCamelCase : str , ): super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase ) UpperCamelCase :Tuple = vocab_size UpperCamelCase :str = hidden_size UpperCamelCase :Dict = num_hidden_layers UpperCamelCase :Tuple = num_attention_heads UpperCamelCase :Optional[Any] = hidden_act UpperCamelCase :Any = intermediate_size UpperCamelCase :Tuple = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :Tuple = layer_norm_eps UpperCamelCase :Tuple = position_embedding_type UpperCamelCase :Optional[Any] = cross_attention_frequency UpperCamelCase :Optional[Any] = encoder_hidden_size @classmethod def _A ( cls : Optional[Any] , __lowerCamelCase : Union[str, os.PathLike] , **__lowerCamelCase : int ): cls._set_token_in_kwargs(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :str = cls.get_config_dict(__lowerCamelCase , **__lowerCamelCase ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": UpperCamelCase :str = config_dict["""qformer_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__lowerCamelCase , **__lowerCamelCase ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = """blip-2""" snake_case__ : Optional[Any] = True def __init__( self : int , __lowerCamelCase : Dict=None , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[str]=None , __lowerCamelCase : Dict=32 , **__lowerCamelCase : Dict ): super().__init__(**__lowerCamelCase ) if vision_config is None: UpperCamelCase :List[str] = {} logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" ) if qformer_config is None: UpperCamelCase :List[Any] = {} logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" ) if text_config is None: UpperCamelCase :int = {} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) UpperCamelCase :Tuple = BlipaVisionConfig(**__lowerCamelCase ) UpperCamelCase :str = BlipaQFormerConfig(**__lowerCamelCase ) UpperCamelCase :Any = text_config["""model_type"""] if """model_type""" in text_config else """opt""" UpperCamelCase :Union[str, Any] = CONFIG_MAPPING[text_model_type](**__lowerCamelCase ) UpperCamelCase :List[str] = self.text_config.tie_word_embeddings UpperCamelCase :Union[str, Any] = self.text_config.is_encoder_decoder UpperCamelCase :Tuple = num_query_tokens UpperCamelCase :Any = self.vision_config.hidden_size UpperCamelCase :int = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES UpperCamelCase :Union[str, Any] = 1.0 UpperCamelCase :Union[str, Any] = 0.02 @classmethod def _A ( cls : Tuple , __lowerCamelCase : BlipaVisionConfig , __lowerCamelCase : BlipaQFormerConfig , __lowerCamelCase : PretrainedConfig , **__lowerCamelCase : List[Any] , ): return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__lowerCamelCase , ) def _A ( self : Optional[int] ): UpperCamelCase :Tuple = copy.deepcopy(self.__dict__ ) UpperCamelCase :Dict = self.vision_config.to_dict() UpperCamelCase :Optional[int] = self.qformer_config.to_dict() UpperCamelCase :Any = self.text_config.to_dict() UpperCamelCase :Union[str, Any] = self.__class__.model_type return output
38
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase_ : Any = '''Create a default config file for Accelerate with only a few flags set.''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int]="no" , __magic_name__ : str = default_json_config_file , __magic_name__ : bool = False ) -> str: """simple docstring""" UpperCamelCase :Any = Path(__magic_name__ ) path.parent.mkdir(parents=__magic_name__ , exist_ok=__magic_name__ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False UpperCamelCase :Dict = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) UpperCamelCase :Optional[Any] = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): UpperCamelCase :Union[str, Any] = torch.cuda.device_count() UpperCamelCase :List[Any] = num_gpus UpperCamelCase :Dict = False if num_gpus > 1: UpperCamelCase :Any = """MULTI_GPU""" else: UpperCamelCase :Any = """NO""" elif is_xpu_available() and use_xpu: UpperCamelCase :Optional[Any] = torch.xpu.device_count() UpperCamelCase :Optional[int] = num_xpus UpperCamelCase :int = False if num_xpus > 1: UpperCamelCase :Union[str, Any] = """MULTI_XPU""" else: UpperCamelCase :Union[str, Any] = """NO""" elif is_npu_available(): UpperCamelCase :List[Any] = torch.npu.device_count() UpperCamelCase :Optional[Any] = num_npus UpperCamelCase :Tuple = False if num_npus > 1: UpperCamelCase :Optional[Any] = """MULTI_NPU""" else: UpperCamelCase :List[Any] = """NO""" else: UpperCamelCase :Any = 0 UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[str] = """NO""" UpperCamelCase :int = ClusterConfig(**__magic_name__ ) config.to_json_file(__magic_name__ ) return path def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = parser.add_parser("""default""" , parents=__magic_name__ , help=__magic_name__ , formatter_class=__magic_name__ ) parser.add_argument( """--config_file""" , default=__magic_name__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=__magic_name__ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=__magic_name__ ) return parser def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
38
1
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class _SCREAMING_SNAKE_CASE : snake_case__ : Optional[int] = None def _A ( self : int ): UpperCamelCase :List[str] = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :List[str] = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __lowerCamelCase ) def _A ( self : List[str] ): UpperCamelCase :Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Optional[Any] = os.path.join(__lowerCamelCase , """feat_extract.json""" ) feat_extract_first.to_json_file(__lowerCamelCase ) UpperCamelCase :int = self.feature_extraction_class.from_json_file(__lowerCamelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _A ( self : Optional[int] ): UpperCamelCase :List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :int = feat_extract_first.save_pretrained(__lowerCamelCase )[0] check_json_file_has_correct_format(__lowerCamelCase ) UpperCamelCase :str = self.feature_extraction_class.from_pretrained(__lowerCamelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _A ( self : Dict ): UpperCamelCase :List[Any] = self.feature_extraction_class() self.assertIsNotNone(__lowerCamelCase )
38
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : str = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
38
1
# Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict ) -> Any: """simple docstring""" return 1 / (1 + np.exp(-z )) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Dict ) -> str: """simple docstring""" return (-y * np.log(__magic_name__ ) - (1 - y) * np.log(1 - h )).mean() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : List[Any] ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :Tuple = np.dot(__magic_name__ , __magic_name__ ) return np.sum(y * scores - np.log(1 + np.exp(__magic_name__ ) ) ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : List[str] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any]=7_0000 ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Tuple = np.zeros(x.shape[1] ) for iterations in range(__magic_name__ ): UpperCamelCase :str = np.dot(__magic_name__ , __magic_name__ ) UpperCamelCase :str = sigmoid_function(__magic_name__ ) UpperCamelCase :int = np.dot(x.T , h - y ) / y.size UpperCamelCase :int = theta - alpha * gradient # updating the weights UpperCamelCase :List[str] = np.dot(__magic_name__ , __magic_name__ ) UpperCamelCase :str = sigmoid_function(__magic_name__ ) UpperCamelCase :List[Any] = cost_function(__magic_name__ , __magic_name__ ) if iterations % 100 == 0: print(f"""loss: {j} \t""" ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": UpperCAmelCase_ : int = datasets.load_iris() UpperCAmelCase_ : Dict = iris.data[:, :2] UpperCAmelCase_ : Dict = (iris.target != 0) * 1 UpperCAmelCase_ : Optional[int] = 0.1 UpperCAmelCase_ : List[Any] = logistic_reg(alpha, x, y, max_iterations=7_00_00) print('''theta: ''', theta) # printing the theta i.e our weights vector def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] ) -> List[str]: """simple docstring""" return sigmoid_function( np.dot(__magic_name__ , __magic_name__ ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''') plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''') ((UpperCAmelCase_) , (UpperCAmelCase_)) : Union[str, Any] = (x[:, 0].min(), x[:, 0].max()) ((UpperCAmelCase_) , (UpperCAmelCase_)) : List[str] = (x[:, 1].min(), x[:, 1].max()) ((UpperCAmelCase_) , (UpperCAmelCase_)) : List[str] = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) UpperCAmelCase_ : List[Any] = np.c_[xxa.ravel(), xxa.ravel()] UpperCAmelCase_ : Tuple = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''') plt.legend() plt.show()
38
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, 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 _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = ShapEImgaImgPipeline snake_case__ : Optional[Any] = ["""image"""] snake_case__ : Union[str, Any] = ["""image"""] snake_case__ : Optional[Any] = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] snake_case__ : List[str] = False @property def _A ( self : Any ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Optional[Any] ): return self.time_input_dim * 4 @property def _A ( self : Union[str, Any] ): return 8 @property def _A ( self : int ): torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCamelCase :Optional[int] = CLIPVisionModel(__lowerCamelCase ) return model @property def _A ( self : str ): UpperCamelCase :Optional[int] = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def _A ( self : Tuple ): torch.manual_seed(0 ) UpperCamelCase :Dict = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase :int = PriorTransformer(**__lowerCamelCase ) return model @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) UpperCamelCase :str = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase :List[str] = ShapERenderer(**__lowerCamelCase ) return model def _A ( self : str ): UpperCamelCase :int = self.dummy_prior UpperCamelCase :Any = self.dummy_image_encoder UpperCamelCase :Dict = self.dummy_image_processor UpperCamelCase :List[Any] = self.dummy_renderer UpperCamelCase :int = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__lowerCamelCase , clip_sample=__lowerCamelCase , clip_sample_range=1.0 , ) UpperCamelCase :Optional[Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def _A ( self : int , __lowerCamelCase : int , __lowerCamelCase : Any=0 ): UpperCamelCase :Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("""mps""" ): UpperCamelCase :List[Any] = torch.manual_seed(__lowerCamelCase ) else: UpperCamelCase :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) UpperCamelCase :Optional[Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _A ( self : List[str] ): UpperCamelCase :Dict = """cpu""" UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :int = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) UpperCamelCase :Dict = output.images[0] UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase :Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _A ( self : List[Any] ): # 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 : List[Any] ): UpperCamelCase :str = torch_device == """cpu""" UpperCamelCase :int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , ) def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.get_dummy_components() UpperCamelCase :Optional[int] = self.pipeline_class(**__lowerCamelCase ) UpperCamelCase :List[Any] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Any = 1 UpperCamelCase :int = 2 UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase :str = batch_size * [inputs[key]] UpperCamelCase :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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Any ): UpperCamelCase :Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCamelCase :Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCamelCase :Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCamelCase :List[str] = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCamelCase :Optional[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCamelCase :Optional[int] = pipe( __lowerCamelCase , generator=__lowerCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
38
1
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[str] , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any]=13 , __lowerCamelCase : str=7 , __lowerCamelCase : Tuple=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Any=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : str=False , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : Any=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : List[Any]=12 , __lowerCamelCase : int=2 , __lowerCamelCase : List[str]=0.02 , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Optional[int]="last" , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[str]=None , ): UpperCamelCase :int = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :str = seq_length UpperCamelCase :Optional[int] = is_training UpperCamelCase :Optional[int] = use_input_lengths UpperCamelCase :Union[str, Any] = use_token_type_ids UpperCamelCase :List[str] = use_labels UpperCamelCase :Dict = gelu_activation UpperCamelCase :Optional[int] = sinusoidal_embeddings UpperCamelCase :List[Any] = causal UpperCamelCase :Optional[int] = asm UpperCamelCase :List[str] = n_langs UpperCamelCase :int = vocab_size UpperCamelCase :List[Any] = n_special UpperCamelCase :List[Any] = hidden_size UpperCamelCase :List[str] = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :Tuple = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Tuple = max_position_embeddings UpperCamelCase :List[str] = type_vocab_size UpperCamelCase :Union[str, Any] = type_sequence_label_size UpperCamelCase :int = initializer_range UpperCamelCase :List[str] = num_labels UpperCamelCase :Optional[int] = num_choices UpperCamelCase :Optional[Any] = summary_type UpperCamelCase :Tuple = use_proj UpperCamelCase :Optional[Any] = scope def _A ( self : List[str] ): UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Any = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :List[Any] = None if self.use_input_lengths: UpperCamelCase :Dict = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase :str = None if self.use_token_type_ids: UpperCamelCase :int = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase :Optional[int] = None UpperCamelCase :int = None UpperCamelCase :List[Any] = None if self.use_labels: UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :List[str] = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase :List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _A ( self : List[Any] ): return 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 , ) def _A ( self : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : int , ): UpperCamelCase :Tuple = FlaubertModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :int = model(__lowerCamelCase , lengths=__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :List[Any] = model(__lowerCamelCase , langs=__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , ): UpperCamelCase :Any = FlaubertWithLMHeadModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Dict = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Any = FlaubertForQuestionAnsweringSimple(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) 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 _A ( self : str , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : str , ): UpperCamelCase :str = FlaubertForQuestionAnswering(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Any = model(__lowerCamelCase ) UpperCamelCase :Optional[int] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , p_mask=__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase , cls_index=__lowerCamelCase , is_impossible=__lowerCamelCase , ) ((UpperCamelCase) , ) :int = result_with_labels.to_tuple() UpperCamelCase :int = model(__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) ((UpperCamelCase) , ) :List[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _A ( self : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , ): UpperCamelCase :Optional[int] = FlaubertForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Tuple = model(__lowerCamelCase ) UpperCamelCase :List[str] = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A ( self : Any , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Dict = self.num_labels UpperCamelCase :Tuple = FlaubertForTokenClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): UpperCamelCase :Union[str, Any] = self.num_choices UpperCamelCase :List[Any] = FlaubertForMultipleChoice(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() UpperCamelCase :Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase :Union[str, Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A ( self : str ): UpperCamelCase :List[str] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :List[Any] = config_and_inputs UpperCamelCase :Union[str, Any] = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): snake_case__ : Optional[int] = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _A ( self : int , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ): 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 _A ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ): UpperCamelCase :Tuple = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": UpperCamelCase :Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) UpperCamelCase :List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def _A ( self : str ): UpperCamelCase :List[Any] = FlaubertModelTester(self ) UpperCamelCase :Any = ConfigTester(self , config_class=__lowerCamelCase , emb_dim=37 ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : List[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__lowerCamelCase ) def _A ( self : Optional[int] ): UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__lowerCamelCase ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__lowerCamelCase ) def _A ( self : int ): UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__lowerCamelCase ) @slow def _A ( self : Any ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Optional[int] = FlaubertModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @slow @require_torch_gpu def _A ( self : Tuple ): UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = model_class(config=__lowerCamelCase ) UpperCamelCase :str = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :str = torch.jit.trace( __lowerCamelCase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__lowerCamelCase , os.path.join(__lowerCamelCase , """traced_model.pt""" ) ) UpperCamelCase :int = torch.jit.load(os.path.join(__lowerCamelCase , """traced_model.pt""" ) , map_location=__lowerCamelCase ) loaded(inputs_dict["""input_ids"""].to(__lowerCamelCase ) , inputs_dict["""attention_mask"""].to(__lowerCamelCase ) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) UpperCamelCase :Optional[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): UpperCamelCase :Tuple = model(__lowerCamelCase )[0] UpperCamelCase :Union[str, Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __lowerCamelCase ) UpperCamelCase :int = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
38
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record UpperCAmelCase_ : int = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' UpperCAmelCase_ : Optional[Any] = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' UpperCAmelCase_ : int = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any="binary" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = simple_accuracy(__magic_name__ , __magic_name__ ) UpperCamelCase :Dict = float(fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average=__magic_name__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = {} for id_pred, label in zip(__magic_name__ , __magic_name__ ): UpperCamelCase :str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCamelCase :Union[str, Any] = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase :Dict = [(pred, label)] UpperCamelCase , UpperCamelCase :Optional[int] = [], [] for question, preds_labels in question_map.items(): UpperCamelCase , UpperCamelCase :Optional[Any] = zip(*__magic_name__ ) UpperCamelCase :Optional[int] = fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average="""macro""" ) fas.append(__magic_name__ ) UpperCamelCase :int = int(sum(pred == label for pred, label in preds_labels ) == len(__magic_name__ ) ) ems.append(__magic_name__ ) UpperCamelCase :Optional[int] = float(sum(__magic_name__ ) / len(__magic_name__ ) ) UpperCamelCase :str = sum(__magic_name__ ) / len(__magic_name__ ) UpperCamelCase :Tuple = float(fa_score(y_true=__magic_name__ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : str ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _A ( self : Optional[Any] ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _A ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : str ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCamelCase :Optional[Any] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCamelCase :Tuple = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
38
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase_ : Any = '''Create a default config file for Accelerate with only a few flags set.''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int]="no" , __magic_name__ : str = default_json_config_file , __magic_name__ : bool = False ) -> str: """simple docstring""" UpperCamelCase :Any = Path(__magic_name__ ) path.parent.mkdir(parents=__magic_name__ , exist_ok=__magic_name__ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False UpperCamelCase :Dict = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) UpperCamelCase :Optional[Any] = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): UpperCamelCase :Union[str, Any] = torch.cuda.device_count() UpperCamelCase :List[Any] = num_gpus UpperCamelCase :Dict = False if num_gpus > 1: UpperCamelCase :Any = """MULTI_GPU""" else: UpperCamelCase :Any = """NO""" elif is_xpu_available() and use_xpu: UpperCamelCase :Optional[Any] = torch.xpu.device_count() UpperCamelCase :Optional[int] = num_xpus UpperCamelCase :int = False if num_xpus > 1: UpperCamelCase :Union[str, Any] = """MULTI_XPU""" else: UpperCamelCase :Union[str, Any] = """NO""" elif is_npu_available(): UpperCamelCase :List[Any] = torch.npu.device_count() UpperCamelCase :Optional[Any] = num_npus UpperCamelCase :Tuple = False if num_npus > 1: UpperCamelCase :Optional[Any] = """MULTI_NPU""" else: UpperCamelCase :List[Any] = """NO""" else: UpperCamelCase :Any = 0 UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[str] = """NO""" UpperCamelCase :int = ClusterConfig(**__magic_name__ ) config.to_json_file(__magic_name__ ) return path def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = parser.add_parser("""default""" , parents=__magic_name__ , help=__magic_name__ , formatter_class=__magic_name__ ) parser.add_argument( """--config_file""" , default=__magic_name__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=__magic_name__ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=__magic_name__ ) return parser def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
38
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : List[str] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any=13 , __lowerCamelCase : Dict=3 , __lowerCamelCase : int=224 , __lowerCamelCase : Any=30 , __lowerCamelCase : Tuple=400 , __lowerCamelCase : int=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , ): UpperCamelCase :List[Any] = size if size is not None else {"""height""": 18, """width""": 18} UpperCamelCase :str = parent UpperCamelCase :Optional[int] = batch_size UpperCamelCase :Dict = num_channels UpperCamelCase :str = image_size UpperCamelCase :Dict = min_resolution UpperCamelCase :str = max_resolution UpperCamelCase :Union[str, Any] = do_resize UpperCamelCase :Optional[Any] = size UpperCamelCase :Any = do_normalize UpperCamelCase :Optional[Any] = image_mean UpperCamelCase :Tuple = image_std def _A ( self : int ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : List[Any] = ViTImageProcessor if is_vision_available() else None def _A ( self : str ): UpperCamelCase :Tuple = EfficientFormerImageProcessorTester(self ) @property def _A ( self : List[str] ): return self.image_proc_tester.prepare_image_processor_dict() def _A ( self : int ): UpperCamelCase :List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCamelCase , """size""" ) ) def _A ( self : Optional[int] ): pass def _A ( self : str ): # Initialize image_processor UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase :List[str] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :List[Any] = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : Union[str, Any] ): # Initialize image_processor UpperCamelCase :Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase :List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase :Dict = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :Tuple = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def _A ( self : List[Any] ): # Initialize image_processor UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase :Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase :List[Any] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched UpperCamelCase :str = image_processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
38
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = ["""image_processor""", """tokenizer"""] snake_case__ : str = """BlipImageProcessor""" snake_case__ : int = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : str ): UpperCamelCase :List[Any] = False super().__init__(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Tuple = self.image_processor def __call__( self : Tuple , __lowerCamelCase : ImageInput = None , __lowerCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __lowerCamelCase : bool = True , __lowerCamelCase : Union[bool, str, PaddingStrategy] = False , __lowerCamelCase : Union[bool, str, TruncationStrategy] = None , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : int = 0 , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Union[str, TensorType]] = None , **__lowerCamelCase : Tuple , ): if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: UpperCamelCase :List[str] = self.tokenizer UpperCamelCase :int = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) return text_encoding # add pixel_values UpperCamelCase :Any = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) if text is not None: UpperCamelCase :Dict = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) else: UpperCamelCase :Optional[int] = None if text_encoding is not None: encoding_image_processor.update(__lowerCamelCase ) return encoding_image_processor def _A ( self : Dict , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Optional[int] ): return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : int , *__lowerCamelCase : str , **__lowerCamelCase : int ): return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property def _A ( self : Union[str, Any] ): UpperCamelCase :List[str] = self.tokenizer.model_input_names UpperCamelCase :Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
38
from collections.abc import Generator from math import sin def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" if len(__magic_name__ ) != 32: raise ValueError("""Input must be of length 32""" ) UpperCamelCase :int = B"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bytes: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :Any = format(__magic_name__ , """08x""" )[-8:] UpperCamelCase :Union[str, Any] = B"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :str = B"""""" for char in message: bit_string += format(__magic_name__ , """08b""" ).encode("""utf-8""" ) UpperCamelCase :Any = format(len(__magic_name__ ) , """064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__magic_name__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> Generator[list[int], None, None]: """simple docstring""" if len(__magic_name__ ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 , len(__magic_name__ ) , 512 ): UpperCamelCase :Tuple = bit_string[pos : pos + 512] UpperCamelCase :Optional[int] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) UpperCamelCase :List[str] = format(__magic_name__ , """032b""" ) UpperCamelCase :Any = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(__magic_name__ , 2 ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" return (a + b) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : bytes ) -> bytes: """simple docstring""" UpperCamelCase :Tuple = preprocess(__magic_name__ ) UpperCamelCase :List[str] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states UpperCamelCase :Union[str, Any] = 0X67_45_23_01 UpperCamelCase :Union[str, Any] = 0XEF_CD_AB_89 UpperCamelCase :List[str] = 0X98_BA_DC_FE UpperCamelCase :int = 0X10_32_54_76 UpperCamelCase :int = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__magic_name__ ): UpperCamelCase :Optional[Any] = aa UpperCamelCase :Any = ba UpperCamelCase :Tuple = ca UpperCamelCase :List[str] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f UpperCamelCase :int = d ^ (b & (c ^ d)) UpperCamelCase :Optional[int] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f UpperCamelCase :str = c ^ (d & (b ^ c)) UpperCamelCase :Union[str, Any] = (5 * i + 1) % 16 elif i <= 47: UpperCamelCase :str = b ^ c ^ d UpperCamelCase :Optional[int] = (3 * i + 5) % 16 else: UpperCamelCase :List[str] = c ^ (b | not_aa(__magic_name__ )) UpperCamelCase :int = (7 * i) % 16 UpperCamelCase :Dict = (f + a + added_consts[i] + block_words[g]) % 2**32 UpperCamelCase :Tuple = d UpperCamelCase :str = c UpperCamelCase :Tuple = b UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , left_rotate_aa(__magic_name__ , shift_amounts[i] ) ) # Add hashed chunk to running total UpperCamelCase :List[str] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :str = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :int = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = sum_aa(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[Any] = reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
38
1
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Tuple , __magic_name__ : List[Any] ) -> str: """simple docstring""" UpperCamelCase :int = set() UpperCamelCase :Optional[Any] = [] def parse_line(__magic_name__ : Any ): for line in fp: if isinstance(__magic_name__ , __magic_name__ ): UpperCamelCase :Tuple = line.decode("""UTF-8""" ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(""" """ ): # process a single warning and move it to `selected_warnings`. if len(__magic_name__ ) > 0: UpperCamelCase :List[Any] = """\n""".join(__magic_name__ ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(__magic_name__ ) buffer.clear() continue else: UpperCamelCase :Any = line.strip() buffer.append(__magic_name__ ) if from_gh: for filename in os.listdir(__magic_name__ ): UpperCamelCase :Tuple = os.path.join(__magic_name__ , __magic_name__ ) if not os.path.isdir(__magic_name__ ): # read the file if filename != "warnings.txt": continue with open(__magic_name__ ) as fp: parse_line(__magic_name__ ) else: try: with zipfile.ZipFile(__magic_name__ ) as z: for filename in z.namelist(): if not os.path.isdir(__magic_name__ ): # read the file if filename != "warnings.txt": continue with z.open(__magic_name__ ) as fp: parse_line(__magic_name__ ) except Exception: logger.warning( f"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : List[str] ) -> Dict: """simple docstring""" UpperCamelCase :Optional[int] = set() UpperCamelCase :Optional[int] = [os.path.join(__magic_name__ , __magic_name__ ) for p in os.listdir(__magic_name__ ) if (p.endswith(""".zip""" ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(__magic_name__ , __magic_name__ ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] ) -> Tuple: """simple docstring""" return values.split(""",""" ) UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') parser.add_argument( '''--output_dir''', type=str, required=True, help='''Where to store the downloaded artifacts and other result files.''', ) parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''') # optional parameters parser.add_argument( '''--targets''', default='''DeprecationWarning,UserWarning,FutureWarning''', type=list_str, help='''Comma-separated list of target warning(s) which we want to extract.''', ) parser.add_argument( '''--from_gh''', action='''store_true''', help='''If running from a GitHub action workflow and collecting warnings from its artifacts.''', ) UpperCAmelCase_ : Optional[int] = parser.parse_args() UpperCAmelCase_ : List[str] = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links UpperCAmelCase_ : List[str] = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print('''=''' * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts UpperCAmelCase_ : Any = extract_warnings(args.output_dir, args.targets) UpperCAmelCase_ : str = sorted(selected_warnings) with open(os.path.join(args.output_dir, '''selected_warnings.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
38
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : List[Any] , __lowerCamelCase : Callable , __lowerCamelCase : Optional[Features] = None , __lowerCamelCase : str = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[dict] = None , __lowerCamelCase : Optional[int] = None , **__lowerCamelCase : List[Any] , ): super().__init__( features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Union[str, Any] = Generator( cache_dir=__lowerCamelCase , features=__lowerCamelCase , generator=__lowerCamelCase , gen_kwargs=__lowerCamelCase , **__lowerCamelCase , ) def _A ( self : List[str] ): # Build iterable dataset if self.streaming: UpperCamelCase :Any = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: UpperCamelCase :Tuple = None UpperCamelCase :Dict = None UpperCamelCase :Dict = None UpperCamelCase :List[str] = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) UpperCamelCase :Tuple = self.builder.as_dataset( split="""train""" , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
38
1
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Tuple = PhobertTokenizer snake_case__ : List[str] = False def _A ( self : Optional[int] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase :int = ["""T@@""", """i""", """I""", """R@@""", """r""", """e@@"""] UpperCamelCase :List[str] = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) UpperCamelCase :Tuple = ["""#version: 0.2""", """l à</w>"""] UpperCamelCase :Dict = {"""unk_token""": """<unk>"""} UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: for token in vocab_tokens: fp.write(F"""{token} {vocab_tokens[token]}\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__lowerCamelCase ) ) def _A ( self : List[Any] , **__lowerCamelCase : Optional[int] ): kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : Dict ): UpperCamelCase :List[str] = """Tôi là VinAI Research""" UpperCamelCase :Union[str, Any] = """T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>""" return input_text, output_text def _A ( self : Optional[int] ): UpperCamelCase :Any = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase :int = """Tôi là VinAI Research""" UpperCamelCase :List[str] = """T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h""".split() UpperCamelCase :List[str] = tokenizer.tokenize(__lowerCamelCase ) print(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[Any] = tokens + [tokenizer.unk_token] UpperCamelCase :List[Any] = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase )
38
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase_ : Union[str, Any] = 16 UpperCAmelCase_ : int = 32 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 , __magic_name__ : str = "bert-base-cased" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = AutoTokenizer.from_pretrained(__magic_name__ ) UpperCamelCase :Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__magic_name__ : Tuple ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase :List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__magic_name__ , max_length=__magic_name__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase :List[Any] = datasets.map( __magic_name__ , batched=__magic_name__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__magic_name__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase :Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__magic_name__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__magic_name__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__magic_name__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase :List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) UpperCamelCase :List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase :Union[str, Any] = config["""lr"""] UpperCamelCase :List[str] = int(config["""num_epochs"""] ) UpperCamelCase :str = int(config["""seed"""] ) UpperCamelCase :Dict = int(config["""batch_size"""] ) UpperCamelCase :Union[str, Any] = args.model_name_or_path set_seed(__magic_name__ ) UpperCamelCase , UpperCamelCase :Dict = get_dataloaders(__magic_name__ , __magic_name__ , __magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase :List[str] = AutoModelForSequenceClassification.from_pretrained(__magic_name__ , return_dict=__magic_name__ ) # Instantiate optimizer UpperCamelCase :Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase :Optional[Any] = optimizer_cls(params=model.parameters() , lr=__magic_name__ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase :Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase :Any = 1 UpperCamelCase :Dict = (len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase :List[Any] = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=0 , num_training_steps=__magic_name__ , ) else: UpperCamelCase :Any = DummyScheduler(__magic_name__ , total_num_steps=__magic_name__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase :int = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase :Tuple = 0 # Now we train the model UpperCamelCase :Any = evaluate.load("""glue""" , """mrpc""" ) UpperCamelCase :Tuple = 0 UpperCamelCase :List[Any] = {} for epoch in range(__magic_name__ , __magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): UpperCamelCase :List[str] = model(**__magic_name__ ) UpperCamelCase :Dict = outputs.loss UpperCamelCase :Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__magic_name__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCamelCase :str = 0 for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase :Optional[int] = model(**__magic_name__ ) UpperCamelCase :List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase , UpperCamelCase :Optional[int] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__magic_name__ ) - 1: UpperCamelCase :Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) UpperCamelCase :List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __magic_name__ ) UpperCamelCase :Dict = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCamelCase :str = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: """simple docstring""" UpperCamelCase :List[str] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__magic_name__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__magic_name__ , ) parser.add_argument( """--output_dir""" , type=__magic_name__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__magic_name__ , default=__magic_name__ , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__magic_name__ , default=3 , help="""Number of train epochs.""" , ) UpperCamelCase :str = parser.parse_args() UpperCamelCase :Any = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
38
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Any = """openai/whisper-base""" snake_case__ : Optional[int] = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) snake_case__ : Any = """transcriber""" snake_case__ : Optional[int] = WhisperProcessor snake_case__ : str = WhisperForConditionalGeneration snake_case__ : Optional[Any] = ["""audio"""] snake_case__ : Any = ["""text"""] def _A ( self : str , __lowerCamelCase : Dict ): return self.pre_processor(__lowerCamelCase , return_tensors="""pt""" ).input_features def _A ( self : Dict , __lowerCamelCase : List[Any] ): return self.model.generate(inputs=__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : Optional[Any] ): return self.pre_processor.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase )[0]
38
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): snake_case__ : Optional[Any] = TransfoXLTokenizer snake_case__ : List[Any] = False snake_case__ : Tuple = False def _A ( self : str ): super().setUp() UpperCamelCase :Dict = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] UpperCamelCase :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _A ( self : List[str] , **__lowerCamelCase : Any ): UpperCamelCase :Any = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : Any , __lowerCamelCase : int ): UpperCamelCase :List[Any] = """<unk> UNwanted , running""" UpperCamelCase :int = """<unk> unwanted, running""" return input_text, output_text def _A ( self : Tuple ): UpperCamelCase :List[str] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__lowerCamelCase ) UpperCamelCase :Any = tokenizer.tokenize("""<unk> UNwanted , running""" ) self.assertListEqual(__lowerCamelCase , ["""<unk>""", """unwanted""", """,""", """running"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [0, 4, 8, 7] ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) def _A ( self : Union[str, Any] ): UpperCamelCase :int = TransfoXLTokenizer(lower_case=__lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _A ( self : Tuple ): UpperCamelCase :Any = TransfoXLTokenizer(lower_case=__lowerCamelCase ) UpperCamelCase :Optional[int] = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" UpperCamelCase :Optional[int] = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(__lowerCamelCase ) , __lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :List[str] = len(__lowerCamelCase ) tokenizer.add_tokens(["""new1""", """new2"""] ) tokenizer.move_added_token("""new1""" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , """new1""" )
38
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase_ : Tuple = { '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', '''BridgeTowerVisionConfig''', ], '''processing_bridgetower''': ['''BridgeTowerProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = [ '''BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BridgeTowerForContrastiveLearning''', '''BridgeTowerForImageAndTextRetrieval''', '''BridgeTowerForMaskedLM''', '''BridgeTowerModel''', '''BridgeTowerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys UpperCAmelCase_ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
38
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase_ : int = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[int] ) -> Dict: """simple docstring""" for attribute in key.split(""".""" ): UpperCamelCase :Dict = getattr(__magic_name__ , __magic_name__ ) if weight_type is not None: UpperCamelCase :Optional[int] = getattr(__magic_name__ , __magic_name__ ).shape else: UpperCamelCase :Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCamelCase :str = value elif weight_type == "weight_g": UpperCamelCase :int = value elif weight_type == "weight_v": UpperCamelCase :int = value elif weight_type == "bias": UpperCamelCase :List[Any] = value else: UpperCamelCase :Any = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Dict = fairseq_model.state_dict() UpperCamelCase :int = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase :str = False if "conv_layers" in name: load_conv_layer( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == """group""" , ) UpperCamelCase :Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase :Optional[int] = True if "*" in mapped_key: UpperCamelCase :List[Any] = name.split(__magic_name__ )[0].split(""".""" )[-2] UpperCamelCase :int = mapped_key.replace("""*""" , __magic_name__ ) if "weight_g" in name: UpperCamelCase :List[Any] = """weight_g""" elif "weight_v" in name: UpperCamelCase :List[Any] = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase :Any = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase :List[str] = """weight""" else: UpperCamelCase :Optional[int] = None set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) continue if not is_used: unused_weights.append(__magic_name__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int , __magic_name__ : List[str] ) -> Dict: """simple docstring""" UpperCamelCase :Dict = full_name.split("""conv_layers.""" )[-1] UpperCamelCase :int = name.split(""".""" ) UpperCamelCase :str = int(items[0] ) UpperCamelCase :str = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCamelCase :Dict = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCamelCase :Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCamelCase :Union[str, Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__magic_name__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : List[Any] , __magic_name__ : str=None ) -> int: """simple docstring""" UpperCamelCase :List[Any] = torch.load(__magic_name__ ) UpperCamelCase :List[Any] = WavLMConfigOrig(checkpoint["""cfg"""] ) UpperCamelCase :int = WavLMOrig(__magic_name__ ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: UpperCamelCase :List[Any] = WavLMConfig.from_pretrained(__magic_name__ ) else: UpperCamelCase :Any = WavLMConfig() UpperCamelCase :Dict = WavLMModel(__magic_name__ ) recursively_load_weights(__magic_name__ , __magic_name__ ) hf_wavlm.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') UpperCAmelCase_ : Optional[int] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
38
1
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : Any = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Tuple ) -> Any: """simple docstring""" UpperCamelCase :Optional[int] = torch.load(__magic_name__ , map_location="""cpu""" ) if "model" in sd.keys(): UpperCamelCase :Any = torch.load(__magic_name__ , map_location="""cpu""" )["""model"""] # pop unnecessary weights UpperCamelCase :str = [ """decoder.version""", """decoder.output_projection.weight""", ] for key in keys_to_delete: if key in sd: sd.pop(__magic_name__ ) UpperCamelCase :Dict = { """decoder.project_in_dim.weight""": """decoder.project_in.weight""", """decoder.project_out_dim.weight""": """decoder.project_out.weight""", """decoder.layer_norm.weight""": """decoder.final_layer_norm.weight""", """decoder.layer_norm.bias""": """decoder.final_layer_norm.bias""", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: UpperCamelCase :Optional[Any] = sd.pop(__magic_name__ ) UpperCamelCase :Optional[int] = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: UpperCamelCase :List[str] = sd[key] # We split QKV in separate Q,K,V UpperCamelCase :List[str] = key.replace(""".qkv_proj.""" , """.q_proj.""" ) UpperCamelCase :Optional[int] = key.replace(""".qkv_proj.""" , """.k_proj.""" ) UpperCamelCase :Any = key.replace(""".qkv_proj.""" , """.v_proj.""" ) UpperCamelCase :str = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = torch.split(__magic_name__ , depth // 3 , dim=0 ) UpperCamelCase :List[Any] = q UpperCamelCase :Tuple = k UpperCamelCase :Optional[Any] = v del sd[key] return sd @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Any , __magic_name__ : Union[str, Any]=None ) -> Any: """simple docstring""" UpperCamelCase :Optional[Any] = load_checkpoint(__magic_name__ ) if config is not None: UpperCamelCase :Optional[Any] = OPTConfig.from_pretrained(__magic_name__ ) else: UpperCamelCase :List[Any] = OPTConfig() UpperCamelCase :Union[str, Any] = OPTModel(__magic_name__ ).half().eval() model.load_state_dict(__magic_name__ ) # Check results Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) model.save_pretrained(__magic_name__ ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--fairseq_path''', type=str, help=( '''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:''' ''' https://huggingface.co/models?other=opt_metasq''' ), ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''') UpperCAmelCase_ : Dict = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
38
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCAmelCase_ : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""bs4"""] ) super().__init__(**__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = [] UpperCamelCase :List[str] = [] UpperCamelCase :Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag UpperCamelCase :Optional[Any] = parent.find_all(child.name , recursive=__lowerCamelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCamelCase ) else next(i for i, s in enumerate(__lowerCamelCase , 1 ) if s is child ) ) UpperCamelCase :Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Any = BeautifulSoup(__lowerCamelCase , """html.parser""" ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Tuple = [] UpperCamelCase :Tuple = [] for element in html_code.descendants: if type(__lowerCamelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue UpperCamelCase :Any = html.unescape(__lowerCamelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = self.xpath_soup(__lowerCamelCase ) stringaxtag_seq.append(__lowerCamelCase ) stringaxsubs_seq.append(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Tuple = """""" for tagname, subs in zip(__lowerCamelCase , __lowerCamelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Any , __lowerCamelCase : Dict ): UpperCamelCase :Any = False # Check that strings has a valid type if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = True elif isinstance(__lowerCamelCase , (list, tuple) ): if len(__lowerCamelCase ) == 0 or isinstance(html_strings[0] , __lowerCamelCase ): UpperCamelCase :Any = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ F"""but is of type {type(__lowerCamelCase )}.""" ) UpperCamelCase :str = bool(isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(html_strings[0] , __lowerCamelCase )) ) if not is_batched: UpperCamelCase :Any = [html_strings] # Get nodes + xpaths UpperCamelCase :Union[str, Any] = [] UpperCamelCase :str = [] for html_string in html_strings: UpperCamelCase , UpperCamelCase , UpperCamelCase :int = self.get_three_from_single(__lowerCamelCase ) nodes.append(__lowerCamelCase ) UpperCamelCase :int = [] for node, tag_list, sub_list in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): UpperCamelCase :str = self.construct_xpath(__lowerCamelCase , __lowerCamelCase ) xpath_strings.append(__lowerCamelCase ) xpaths.append(__lowerCamelCase ) # return as Dict UpperCamelCase :Optional[int] = {"""nodes""": nodes, """xpaths""": xpaths} UpperCamelCase :Any = BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) return encoded_inputs
38
1
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel UpperCAmelCase_ : Any = '''0.12''' # assumed parallelism: 8 @require_flax @is_staging_test class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @classmethod def _A ( cls : str ): UpperCamelCase :Optional[int] = TOKEN HfFolder.save_token(__lowerCamelCase ) @classmethod def _A ( cls : Tuple ): try: delete_repo(token=cls._token , repo_id="""test-model-flax""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-model-flax-org""" ) except HTTPError: pass def _A ( self : List[Any] ): UpperCamelCase :Dict = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCamelCase :List[str] = FlaxBertModel(__lowerCamelCase ) model.push_to_hub("""test-model-flax""" , use_auth_token=self._token ) UpperCamelCase :List[str] = FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""" ) UpperCamelCase :str = flatten_dict(unfreeze(model.params ) ) UpperCamelCase :List[Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase :Dict = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCamelCase , 1E-3 , msg=F"""{key} not identical""" ) # Reset repo delete_repo(token=self._token , repo_id="""test-model-flax""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__lowerCamelCase , repo_id="""test-model-flax""" , push_to_hub=__lowerCamelCase , use_auth_token=self._token ) UpperCamelCase :str = FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""" ) UpperCamelCase :int = flatten_dict(unfreeze(model.params ) ) UpperCamelCase :Tuple = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase :Dict = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCamelCase , 1E-3 , msg=F"""{key} not identical""" ) def _A ( self : int ): UpperCamelCase :Optional[int] = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCamelCase :Any = FlaxBertModel(__lowerCamelCase ) model.push_to_hub("""valid_org/test-model-flax-org""" , use_auth_token=self._token ) UpperCamelCase :Optional[Any] = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) UpperCamelCase :List[str] = flatten_dict(unfreeze(model.params ) ) UpperCamelCase :Union[str, Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase :List[str] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCamelCase , 1E-3 , msg=F"""{key} not identical""" ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-model-flax-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( __lowerCamelCase , repo_id="""valid_org/test-model-flax-org""" , push_to_hub=__lowerCamelCase , use_auth_token=self._token ) UpperCamelCase :int = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) UpperCamelCase :str = flatten_dict(unfreeze(model.params ) ) UpperCamelCase :Union[str, Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase :Union[str, Any] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCamelCase , 1E-3 , msg=F"""{key} not identical""" ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Tuple , __magic_name__ : Any ) -> Tuple: """simple docstring""" UpperCamelCase :Optional[int] = True UpperCamelCase :str = flatten_dict(modela.params ) UpperCamelCase :Optional[int] = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4: UpperCamelCase :Any = False return models_are_equal @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : Dict ): UpperCamelCase :Optional[Any] = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) UpperCamelCase :Union[str, Any] = FlaxBertModel(__lowerCamelCase ) UpperCamelCase :Dict = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__lowerCamelCase , __lowerCamelCase ) ) with self.assertRaises(__lowerCamelCase ): UpperCamelCase :str = FlaxBertModel.from_pretrained(__lowerCamelCase ) UpperCamelCase :Any = FlaxBertModel.from_pretrained(__lowerCamelCase , subfolder=__lowerCamelCase ) self.assertTrue(check_models_equal(__lowerCamelCase , __lowerCamelCase ) ) def _A ( self : Dict ): UpperCamelCase :int = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) UpperCamelCase :List[Any] = FlaxBertModel(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__lowerCamelCase , __lowerCamelCase ) , max_shard_size="""10KB""" ) with self.assertRaises(__lowerCamelCase ): UpperCamelCase :List[str] = FlaxBertModel.from_pretrained(__lowerCamelCase ) UpperCamelCase :str = FlaxBertModel.from_pretrained(__lowerCamelCase , subfolder=__lowerCamelCase ) self.assertTrue(check_models_equal(__lowerCamelCase , __lowerCamelCase ) ) def _A ( self : Optional[Any] ): UpperCamelCase :Union[str, Any] = """bert""" UpperCamelCase :Optional[Any] = """hf-internal-testing/tiny-random-bert-subfolder""" with self.assertRaises(__lowerCamelCase ): UpperCamelCase :Tuple = FlaxBertModel.from_pretrained(__lowerCamelCase ) UpperCamelCase :Tuple = FlaxBertModel.from_pretrained(__lowerCamelCase , subfolder=__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def _A ( self : Optional[Any] ): UpperCamelCase :List[str] = """bert""" UpperCamelCase :str = """hf-internal-testing/tiny-random-bert-sharded-subfolder""" with self.assertRaises(__lowerCamelCase ): UpperCamelCase :Dict = FlaxBertModel.from_pretrained(__lowerCamelCase ) UpperCamelCase :str = FlaxBertModel.from_pretrained(__lowerCamelCase , subfolder=__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase )
38
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : list[int] ) -> bool: """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : list[int] , __magic_name__ : int ) -> bool: """simple docstring""" if curr_ind == len(__magic_name__ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__magic_name__ ) ): if valid_connection(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): # Insert current vertex into path as next transition UpperCamelCase :str = next_ver # Validate created path if util_hamilton_cycle(__magic_name__ , __magic_name__ , curr_ind + 1 ): return True # Backtrack UpperCamelCase :Union[str, Any] = -1 return False def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[list[int]] , __magic_name__ : int = 0 ) -> list[int]: """simple docstring""" UpperCamelCase :Union[str, Any] = [-1] * (len(__magic_name__ ) + 1) # initialize start and end of path with starting index UpperCamelCase :Any = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__magic_name__ , __magic_name__ , 1 ) else []
38
1