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
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = BigBirdConfig.from_json_file(__SCREAMING_SNAKE_CASE ) print(F'''Building PyTorch model from configuration: {config}''' ) if is_trivia_qa: lowercase_ : Tuple = BigBirdForQuestionAnswering(__SCREAMING_SNAKE_CASE ) else: lowercase_ : Optional[Any] = BigBirdForPreTraining(__SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , is_trivia_qa=__SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": _lowercase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) _lowercase : Union[str, Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
93
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : List[Any] = { "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[Any] = [ "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimesformerModel", "TimesformerForVideoClassification", "TimesformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys _lowercase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
1
'''simple docstring''' from __future__ import annotations def snake_case_ ( __SCREAMING_SNAKE_CASE : int | str ): """simple docstring""" lowercase_ : Optional[int] = str(__SCREAMING_SNAKE_CASE ) return n == n[::-1] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 1000000 ): """simple docstring""" lowercase_ : Union[str, Any] = 0 for i in range(1 , __SCREAMING_SNAKE_CASE ): if is_palindrome(__SCREAMING_SNAKE_CASE ) and is_palindrome(bin(__SCREAMING_SNAKE_CASE ).split('''b''' )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
93
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
1
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black _lowercase : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. _lowercase : Union[str, Any] = " \"\"\"\n Output class for the scheduler's step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"\"\"\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n" class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) lowercase_ : str = self.diffusers_dir shutil.copy( os.path.join(__SCREAMING_SNAKE_CASE , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def _snake_case ( self ): """simple docstring""" lowercase_ : Any = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : str = comment + F'''\nclass {class_name}(nn.Module):\n''' + class_code if overwrite_result is not None: lowercase_ : Union[str, Any] = comment + F'''\nclass {class_name}(nn.Module):\n''' + overwrite_result lowercase_ : int = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 ) lowercase_ : Union[str, Any] = black.format_str(__SCREAMING_SNAKE_CASE , mode=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(__SCREAMING_SNAKE_CASE , '''w''' , newline='''\n''' ) as f: f.write(__SCREAMING_SNAKE_CASE ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__SCREAMING_SNAKE_CASE ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: self.assertTrue(f.read() , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , __SCREAMING_SNAKE_CASE , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , __SCREAMING_SNAKE_CASE ) , ) # Copy consistency with a really long name lowercase_ : List[str] = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( F'''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}''' , F'''{long_class_name}SchedulerOutput''' , re.sub('''Bert''' , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , __SCREAMING_SNAKE_CASE , overwrite_result=re.sub('''DDPM''' , '''Test''' , __SCREAMING_SNAKE_CASE ) , )
93
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 50000000 ): """simple docstring""" lowercase_ : Any = set() lowercase_ : List[Any] = int((limit - 24) ** (1 / 2) ) lowercase_ : str = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __SCREAMING_SNAKE_CASE ) ) ) for primea in primes: lowercase_ : Dict = primea * primea for primea in primes: lowercase_ : Dict = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowercase_ : Optional[int] = primea * primea * primea * primea lowercase_ : Any = square + cube + tetr if total >= limit: break ret.add(__SCREAMING_SNAKE_CASE ) return len(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(f"""{solution() = }""")
93
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCAmelCase__ ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = KandinskyInpaintPipeline lowerCAmelCase_ = ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image'''] lowerCAmelCase_ = [ '''prompt''', '''negative_prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''', ] lowerCAmelCase_ = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''negative_prompt''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] lowerCAmelCase_ = False @property def _snake_case ( self ): """simple docstring""" return 32 @property def _snake_case ( self ): """simple docstring""" return 32 @property def _snake_case ( self ): """simple docstring""" return self.time_input_dim @property def _snake_case ( self ): """simple docstring""" return self.time_input_dim * 4 @property def _snake_case ( self ): """simple docstring""" return 1_00 @property def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base''' ) return tokenizer @property def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : Optional[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=10_05 , ) lowercase_ : int = MultilingualCLIP(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = text_encoder.eval() return text_encoder @property def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : Any = { '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } lowercase_ : int = UNetaDConditionModel(**__SCREAMING_SNAKE_CASE ) return model @property def _snake_case ( self ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : Tuple = VQModel(**self.dummy_movq_kwargs ) return model def _snake_case ( self ): """simple docstring""" lowercase_ : int = self.dummy_text_encoder lowercase_ : int = self.dummy_tokenizer lowercase_ : Tuple = self.dummy_unet lowercase_ : List[Any] = self.dummy_movq lowercase_ : Dict = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='''linear''' , beta_start=0.00_085 , beta_end=0.012 , clip_sample=__SCREAMING_SNAKE_CASE , set_alpha_to_one=__SCREAMING_SNAKE_CASE , steps_offset=1 , prediction_type='''epsilon''' , thresholding=__SCREAMING_SNAKE_CASE , ) lowercase_ : List[Any] = { '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): """simple docstring""" lowercase_ : List[str] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__SCREAMING_SNAKE_CASE ) # create init_image lowercase_ : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowercase_ : List[Any] = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert('''RGB''' ).resize((2_56, 2_56) ) # create mask lowercase_ : Tuple = np.ones((64, 64) , dtype=np.floataa ) lowercase_ : Optional[int] = 0 if str(__SCREAMING_SNAKE_CASE ).startswith('''mps''' ): lowercase_ : str = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: lowercase_ : str = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = { '''prompt''': '''horse''', '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = '''cpu''' lowercase_ : Dict = self.get_dummy_components() lowercase_ : List[str] = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = pipe(**self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[Any] = output.images lowercase_ : str = pipe( **self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) , return_dict=__SCREAMING_SNAKE_CASE , )[0] lowercase_ : Optional[Any] = image[0, -3:, -3:, -1] lowercase_ : Tuple = image_from_tuple[0, -3:, -3:, -1] print(F'''image.shape {image.shape}''' ) assert image.shape == (1, 64, 64, 3) lowercase_ : Optional[int] = np.array( [0.8_326_919, 0.73_790_467, 0.20_918_581, 0.9_309_612, 0.5_511_791, 0.43_713_328, 0.5_513_321, 0.49_922_934, 0.59_497_786] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' def _snake_case ( self ): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy''' ) lowercase_ : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) lowercase_ : str = np.ones((7_68, 7_68) , dtype=np.floataa ) lowercase_ : List[Any] = 0 lowercase_ : int = '''a hat''' lowercase_ : int = KandinskyPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = KandinskyInpaintPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-inpaint''' , torch_dtype=torch.floataa ) lowercase_ : Dict = pipeline.to(__SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) lowercase_ , lowercase_ : Dict = pipe_prior( __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() lowercase_ : Dict = pipeline( __SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , image_embeds=__SCREAMING_SNAKE_CASE , negative_image_embeds=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=1_00 , height=7_68 , width=7_68 , output_type='''np''' , ) lowercase_ : Tuple = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
93
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
1
'''simple docstring''' import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline _lowercase : List[Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : tuple , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int]=False , ): """simple docstring""" output_path.parent.mkdir(parents=__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , f=output_path.as_posix() , input_names=__SCREAMING_SNAKE_CASE , output_names=__SCREAMING_SNAKE_CASE , dynamic_axes=__SCREAMING_SNAKE_CASE , do_constant_folding=__SCREAMING_SNAKE_CASE , use_external_data_format=__SCREAMING_SNAKE_CASE , enable_onnx_checker=__SCREAMING_SNAKE_CASE , opset_version=__SCREAMING_SNAKE_CASE , ) else: export( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , f=output_path.as_posix() , input_names=__SCREAMING_SNAKE_CASE , output_names=__SCREAMING_SNAKE_CASE , dynamic_axes=__SCREAMING_SNAKE_CASE , do_constant_folding=__SCREAMING_SNAKE_CASE , opset_version=__SCREAMING_SNAKE_CASE , ) @torch.no_grad() def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ): """simple docstring""" lowercase_ : List[Any] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): lowercase_ : Tuple = '''cuda''' elif fpaa and not torch.cuda.is_available(): raise ValueError('''`float16` model export is only supported on GPUs with CUDA''' ) else: lowercase_ : Any = '''cpu''' lowercase_ : List[Any] = StableDiffusionPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , torch_dtype=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : int = Path(__SCREAMING_SNAKE_CASE ) # TEXT ENCODER lowercase_ : Any = pipeline.text_encoder.config.max_position_embeddings lowercase_ : Union[str, Any] = pipeline.text_encoder.config.hidden_size lowercase_ : Any = pipeline.tokenizer( '''A sample prompt''' , padding='''max_length''' , max_length=pipeline.tokenizer.model_max_length , truncation=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' , ) onnx_export( pipeline.text_encoder , model_args=(text_input.input_ids.to(device=__SCREAMING_SNAKE_CASE , dtype=torch.intaa )) , output_path=output_path / '''text_encoder''' / '''model.onnx''' , ordered_input_names=['''input_ids'''] , output_names=['''last_hidden_state''', '''pooler_output'''] , dynamic_axes={ '''input_ids''': {0: '''batch''', 1: '''sequence'''}, } , opset=__SCREAMING_SNAKE_CASE , ) del pipeline.text_encoder # UNET lowercase_ : str = pipeline.unet.config.in_channels lowercase_ : str = pipeline.unet.config.sample_size lowercase_ : List[Any] = output_path / '''unet''' / '''model.onnx''' onnx_export( pipeline.unet , model_args=( torch.randn(2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ), torch.randn(2 ).to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ), torch.randn(2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ), False, ) , output_path=__SCREAMING_SNAKE_CASE , ordered_input_names=['''sample''', '''timestep''', '''encoder_hidden_states''', '''return_dict'''] , output_names=['''out_sample'''] , dynamic_axes={ '''sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, '''timestep''': {0: '''batch'''}, '''encoder_hidden_states''': {0: '''batch''', 1: '''sequence'''}, } , opset=__SCREAMING_SNAKE_CASE , use_external_data_format=__SCREAMING_SNAKE_CASE , ) lowercase_ : str = str(unet_path.absolute().as_posix() ) lowercase_ : Optional[Any] = os.path.dirname(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = onnx.load(__SCREAMING_SNAKE_CASE ) # clean up existing tensor files shutil.rmtree(__SCREAMING_SNAKE_CASE ) os.mkdir(__SCREAMING_SNAKE_CASE ) # collate external tensor files into one onnx.save_model( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , save_as_external_data=__SCREAMING_SNAKE_CASE , all_tensors_to_one_file=__SCREAMING_SNAKE_CASE , location='''weights.pb''' , convert_attribute=__SCREAMING_SNAKE_CASE , ) del pipeline.unet # VAE ENCODER lowercase_ : Optional[int] = pipeline.vae lowercase_ : Optional[Any] = vae_encoder.config.in_channels lowercase_ : int = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder lowercase_ : Union[str, Any] = lambda __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : vae_encoder.encode(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )[0].sample() onnx_export( __SCREAMING_SNAKE_CASE , model_args=( torch.randn(1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ), False, ) , output_path=output_path / '''vae_encoder''' / '''model.onnx''' , ordered_input_names=['''sample''', '''return_dict'''] , output_names=['''latent_sample'''] , dynamic_axes={ '''sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, } , opset=__SCREAMING_SNAKE_CASE , ) # VAE DECODER lowercase_ : List[Any] = pipeline.vae lowercase_ : Any = vae_decoder.config.latent_channels lowercase_ : str = vae_decoder.config.out_channels # forward only through the decoder part lowercase_ : Dict = vae_encoder.decode onnx_export( __SCREAMING_SNAKE_CASE , model_args=( torch.randn(1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ), False, ) , output_path=output_path / '''vae_decoder''' / '''model.onnx''' , ordered_input_names=['''latent_sample''', '''return_dict'''] , output_names=['''sample'''] , dynamic_axes={ '''latent_sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, } , opset=__SCREAMING_SNAKE_CASE , ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: lowercase_ : Dict = pipeline.safety_checker lowercase_ : List[Any] = safety_checker.config.vision_config.num_channels lowercase_ : Tuple = safety_checker.config.vision_config.image_size lowercase_ : Tuple = safety_checker.forward_onnx onnx_export( pipeline.safety_checker , model_args=( torch.randn( 1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ).to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ), torch.randn(1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ), ) , output_path=output_path / '''safety_checker''' / '''model.onnx''' , ordered_input_names=['''clip_input''', '''images'''] , output_names=['''out_images''', '''has_nsfw_concepts'''] , dynamic_axes={ '''clip_input''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, '''images''': {0: '''batch''', 1: '''height''', 2: '''width''', 3: '''channels'''}, } , opset=__SCREAMING_SNAKE_CASE , ) del pipeline.safety_checker lowercase_ : List[str] = OnnxRuntimeModel.from_pretrained(output_path / '''safety_checker''' ) lowercase_ : Optional[int] = pipeline.feature_extractor else: lowercase_ : int = None lowercase_ : str = None lowercase_ : Optional[int] = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / '''vae_encoder''' ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / '''vae_decoder''' ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / '''text_encoder''' ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / '''unet''' ) , scheduler=pipeline.scheduler , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , requires_safety_checker=safety_checker is not None , ) onnx_pipeline.save_pretrained(__SCREAMING_SNAKE_CASE ) print('''ONNX pipeline saved to''' , __SCREAMING_SNAKE_CASE ) del pipeline del onnx_pipeline lowercase_ : Tuple = OnnxStableDiffusionPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , provider='''CPUExecutionProvider''' ) print('''ONNX pipeline is loadable''' ) if __name__ == "__main__": _lowercase : Optional[int] = argparse.ArgumentParser() parser.add_argument( "--model_path", type=str, required=True, help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).", ) parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.") parser.add_argument( "--opset", default=1_4, type=int, help="The version of the ONNX operator set to use.", ) parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode") _lowercase : Union[str, Any] = parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
93
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : @staticmethod def _snake_case ( *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): lowerCAmelCase_ = MODEL_FOR_OBJECT_DETECTION_MAPPING def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = object_detector('''./tests/fixtures/tests_samples/COCO/000000039769.png''' , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { '''score''': ANY(__SCREAMING_SNAKE_CASE ), '''label''': ANY(__SCREAMING_SNAKE_CASE ), '''box''': {'''xmin''': ANY(__SCREAMING_SNAKE_CASE ), '''ymin''': ANY(__SCREAMING_SNAKE_CASE ), '''xmax''': ANY(__SCREAMING_SNAKE_CASE ), '''ymax''': ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets lowercase_ : Tuple = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) lowercase_ : str = [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] lowercase_ : Optional[int] = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { '''score''': ANY(__SCREAMING_SNAKE_CASE ), '''label''': ANY(__SCREAMING_SNAKE_CASE ), '''box''': {'''xmin''': ANY(__SCREAMING_SNAKE_CASE ), '''ymin''': ANY(__SCREAMING_SNAKE_CASE ), '''xmax''': ANY(__SCREAMING_SNAKE_CASE ), '''ymax''': ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip('''Object detection not implemented in TF''' ) def _snake_case ( self ): """simple docstring""" pass @require_torch def _snake_case ( self ): """simple docstring""" lowercase_ : int = '''hf-internal-testing/tiny-detr-mobilenetsv3''' lowercase_ : Any = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_59, '''ymin''': 1_20, '''xmax''': 4_80, '''ymax''': 3_59}}, {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_59, '''ymin''': 1_20, '''xmax''': 4_80, '''ymax''': 3_59}}, ] , ) lowercase_ : Optional[Any] = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_59, '''ymin''': 1_20, '''xmax''': 4_80, '''ymax''': 3_59}}, {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_59, '''ymin''': 1_20, '''xmax''': 4_80, '''ymax''': 3_59}}, ], [ {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_59, '''ymin''': 1_20, '''xmax''': 4_80, '''ymax''': 3_59}}, {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_59, '''ymin''': 1_20, '''xmax''': 4_80, '''ymax''': 3_59}}, ], ] , ) @require_torch @slow def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = '''facebook/detr-resnet-50''' lowercase_ : Tuple = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 1_75, '''ymax''': 1_17}}, {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 3_33, '''ymin''': 72, '''xmax''': 3_68, '''ymax''': 1_87}}, {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_39, '''ymax''': 4_73}}, {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 3_14, '''ymax''': 4_70}}, {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 3_45, '''ymin''': 23, '''xmax''': 6_40, '''ymax''': 3_68}}, ] , ) lowercase_ : List[str] = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 1_75, '''ymax''': 1_17}}, {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 3_33, '''ymin''': 72, '''xmax''': 3_68, '''ymax''': 1_87}}, {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_39, '''ymax''': 4_73}}, {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 3_14, '''ymax''': 4_70}}, {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 3_45, '''ymin''': 23, '''xmax''': 6_40, '''ymax''': 3_68}}, ], [ {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 1_75, '''ymax''': 1_17}}, {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 3_33, '''ymin''': 72, '''xmax''': 3_68, '''ymax''': 1_87}}, {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_39, '''ymax''': 4_73}}, {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 3_14, '''ymax''': 4_70}}, {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 3_45, '''ymin''': 23, '''xmax''': 6_40, '''ymax''': 3_68}}, ], ] , ) @require_torch @slow def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = '''facebook/detr-resnet-50''' lowercase_ : List[str] = pipeline('''object-detection''' , model=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 1_75, '''ymax''': 1_17}}, {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 3_33, '''ymin''': 72, '''xmax''': 3_68, '''ymax''': 1_87}}, {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_39, '''ymax''': 4_73}}, {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 3_14, '''ymax''': 4_70}}, {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 3_45, '''ymin''': 23, '''xmax''': 6_40, '''ymax''': 3_68}}, ] , ) lowercase_ : List[Any] = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 1_75, '''ymax''': 1_17}}, {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 3_33, '''ymin''': 72, '''xmax''': 3_68, '''ymax''': 1_87}}, {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_39, '''ymax''': 4_73}}, {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 3_14, '''ymax''': 4_70}}, {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 3_45, '''ymin''': 23, '''xmax''': 6_40, '''ymax''': 3_68}}, ], [ {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 1_75, '''ymax''': 1_17}}, {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 3_33, '''ymin''': 72, '''xmax''': 3_68, '''ymax''': 1_87}}, {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_39, '''ymax''': 4_73}}, {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 3_14, '''ymax''': 4_70}}, {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 3_45, '''ymin''': 23, '''xmax''': 6_40, '''ymax''': 3_68}}, ], ] , ) @require_torch @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = 0.9_985 lowercase_ : Optional[int] = '''facebook/detr-resnet-50''' lowercase_ : Dict = pipeline('''object-detection''' , model=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 3_14, '''ymax''': 4_70}}, {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 3_45, '''ymin''': 23, '''xmax''': 6_40, '''ymax''': 3_68}}, ] , ) @require_torch @require_pytesseract @slow def _snake_case ( self ): """simple docstring""" lowercase_ : int = '''Narsil/layoutlmv3-finetuned-funsd''' lowercase_ : Union[str, Any] = 0.9_993 lowercase_ : str = pipeline('''object-detection''' , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = object_detector( '''https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png''' ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.9_993, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 2_94, '''ymin''': 2_54, '''xmax''': 3_43, '''ymax''': 2_64}}, {'''score''': 0.9_993, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 2_94, '''ymin''': 2_54, '''xmax''': 3_43, '''ymax''': 2_64}}, ] , )
93
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = 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(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = tempfile.mkdtemp() # fmt: off lowercase_ : Optional[int] = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on lowercase_ : Optional[int] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) lowercase_ : int = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] lowercase_ : Optional[int] = {'''unk_token''': '''<unk>'''} lowercase_ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase_ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48_145_466, 0.4_578_275, 0.40_821_073], '''image_std''': [0.26_862_954, 0.26_130_258, 0.27_577_711], } lowercase_ : Any = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] lowercase_ : List[str] = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self ): """simple docstring""" lowercase_ : int = self.get_tokenizer() lowercase_ : Tuple = self.get_rust_tokenizer() lowercase_ : Union[str, Any] = self.get_image_processor() lowercase_ : Tuple = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) lowercase_ : int = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) lowercase_ : int = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) lowercase_ : Any = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowercase_ : int = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) lowercase_ : List[str] = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) lowercase_ : Tuple = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = self.get_image_processor() lowercase_ : List[Any] = self.get_tokenizer() lowercase_ : Optional[int] = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.prepare_image_inputs() lowercase_ : List[Any] = image_processor(__SCREAMING_SNAKE_CASE , return_tensors='''np''' ) lowercase_ : Optional[Any] = processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = self.get_image_processor() lowercase_ : Union[str, Any] = self.get_tokenizer() lowercase_ : Tuple = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = '''lower newer''' lowercase_ : List[Any] = processor(text=__SCREAMING_SNAKE_CASE ) lowercase_ : int = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = self.get_image_processor() lowercase_ : Union[str, Any] = self.get_tokenizer() lowercase_ : Dict = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) lowercase_ : str = '''lower newer''' lowercase_ : Optional[int] = self.prepare_image_inputs() lowercase_ : Dict = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.get_image_processor() lowercase_ : Tuple = self.get_tokenizer() lowercase_ : str = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) lowercase_ : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowercase_ : Any = processor.batch_decode(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = self.get_image_processor() lowercase_ : int = self.get_tokenizer() lowercase_ : Dict = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = '''lower newer''' lowercase_ : Any = self.prepare_image_inputs() lowercase_ : Any = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
1
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets _lowercase : List[Any] = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n" _lowercase : List[Any] = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n" _lowercase : List[str] = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"pearson\": Pearson Correlation\n \"spearmanr\": Spearman Correlation\n \"matthews_correlation\": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'stsb')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n {'pearson': 1.0, 'spearmanr': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'cola')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" return float((preds == labels).mean() ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Any = simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = float(fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=__SCREAMING_SNAKE_CASE ) ) return { "accuracy": acc, "f1": fa, } def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : Optional[int] = float(pearsonr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )[0] ) lowercase_ : Tuple = float(spearmanr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def _snake_case ( self ): """simple docstring""" if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} elif self.config_name == "stsb": return pearson_and_spearman(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
93
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = update_image_and_anno( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , filter_scale=__SCREAMING_SNAKE_CASE , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : int = F'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(__SCREAMING_SNAKE_CASE ) with open(F'''{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__SCREAMING_SNAKE_CASE ) labels.append(__SCREAMING_SNAKE_CASE ) return img_paths, labels def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : tuple[int, int] , __SCREAMING_SNAKE_CASE : tuple[float, float] , __SCREAMING_SNAKE_CASE : float = 0.0 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ 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 snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
1
'''simple docstring''' import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller _lowercase : str = 3 def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" print('''Generating primitive root of p''' ) while True: lowercase_ : Tuple = random.randrange(3 , __SCREAMING_SNAKE_CASE ) if pow(__SCREAMING_SNAKE_CASE , 2 , __SCREAMING_SNAKE_CASE ) == 1: continue if pow(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) == 1: continue return g def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" print('''Generating prime p...''' ) lowercase_ : Union[str, Any] = rabin_miller.generate_large_prime(__SCREAMING_SNAKE_CASE ) # select large prime number. lowercase_ : Any = primitive_root(__SCREAMING_SNAKE_CASE ) # one primitive root on modulo p. lowercase_ : Any = random.randrange(3 , __SCREAMING_SNAKE_CASE ) # private_key -> have to be greater than 2 for safety. lowercase_ : List[Any] = cryptomath.find_mod_inverse(pow(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = (key_size, e_a, e_a, p) lowercase_ : Optional[Any] = (key_size, d) return public_key, private_key def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if os.path.exists(F'''{name}_pubkey.txt''' ) or os.path.exists(F'''{name}_privkey.txt''' ): print('''\nWARNING:''' ) print( F'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n''' '''Use a different name or delete these files and re-run this program.''' ) sys.exit() lowercase_ , lowercase_ : Optional[Any] = generate_key(__SCREAMING_SNAKE_CASE ) print(F'''\nWriting public key to file {name}_pubkey.txt...''' ) with open(F'''{name}_pubkey.txt''' , '''w''' ) as fo: fo.write(F'''{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}''' ) print(F'''Writing private key to file {name}_privkey.txt...''' ) with open(F'''{name}_privkey.txt''' , '''w''' ) as fo: fo.write(F'''{private_key[0]},{private_key[1]}''' ) def snake_case_ ( ): """simple docstring""" print('''Making key files...''' ) make_key_files('''elgamal''' , 2048 ) print('''Key files generation successful''' ) if __name__ == "__main__": main()
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
'''simple docstring''' import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration _lowercase : Dict = 5_0_0_0_0 _lowercase : Union[str, Any] = 5_0_0_0 _lowercase , _lowercase : List[str] = os.path.split(__file__) _lowercase : Any = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json")) @get_duration def snake_case_ ( __SCREAMING_SNAKE_CASE : datasets.Dataset , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" for i in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = dataset[i] @get_duration def snake_case_ ( __SCREAMING_SNAKE_CASE : datasets.Dataset , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" for i in range(0 , len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ): lowercase_ : int = dataset[i : i + batch_size] @get_duration def snake_case_ ( __SCREAMING_SNAKE_CASE : datasets.Dataset , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with dataset.formatted_as(type=__SCREAMING_SNAKE_CASE ): for i in range(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = dataset[i] @get_duration def snake_case_ ( __SCREAMING_SNAKE_CASE : datasets.Dataset , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with dataset.formatted_as(type=__SCREAMING_SNAKE_CASE ): for i in range(0 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : List[str] = dataset[i : i + batch_size] def snake_case_ ( ): """simple docstring""" lowercase_ : Any = {'''num examples''': SPEED_TEST_N_EXAMPLES} lowercase_ : Optional[int] = [ (read, {'''length''': SMALL_TEST}), (read, {'''length''': SPEED_TEST_N_EXAMPLES}), (read_batch, {'''length''': SPEED_TEST_N_EXAMPLES, '''batch_size''': 10}), (read_batch, {'''length''': SPEED_TEST_N_EXAMPLES, '''batch_size''': 100}), (read_batch, {'''length''': SPEED_TEST_N_EXAMPLES, '''batch_size''': 1000}), (read_formatted, {'''type''': '''numpy''', '''length''': SMALL_TEST}), (read_formatted, {'''type''': '''pandas''', '''length''': SMALL_TEST}), (read_formatted, {'''type''': '''torch''', '''length''': SMALL_TEST}), (read_formatted, {'''type''': '''tensorflow''', '''length''': SMALL_TEST}), (read_formatted_batch, {'''type''': '''numpy''', '''length''': SMALL_TEST, '''batch_size''': 10}), (read_formatted_batch, {'''type''': '''numpy''', '''length''': SMALL_TEST, '''batch_size''': 1000}), ] lowercase_ : List[str] = [ (read, {'''length''': SMALL_TEST}), (read, {'''length''': SPEED_TEST_N_EXAMPLES}), (read_batch, {'''length''': SPEED_TEST_N_EXAMPLES, '''batch_size''': 10}), (read_batch, {'''length''': SPEED_TEST_N_EXAMPLES, '''batch_size''': 100}), (read_batch, {'''length''': SPEED_TEST_N_EXAMPLES, '''batch_size''': 1000}), (read_formatted, {'''type''': '''numpy''', '''length''': SMALL_TEST}), (read_formatted_batch, {'''type''': '''numpy''', '''length''': SMALL_TEST, '''batch_size''': 10}), (read_formatted_batch, {'''type''': '''numpy''', '''length''': SMALL_TEST, '''batch_size''': 1000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print('''generating dataset''' ) lowercase_ : Dict = datasets.Features( {'''list''': datasets.Sequence(datasets.Value('''float32''' ) ), '''numbers''': datasets.Value('''float32''' )} ) lowercase_ : Dict = generate_example_dataset( os.path.join(__SCREAMING_SNAKE_CASE , '''dataset.arrow''' ) , __SCREAMING_SNAKE_CASE , num_examples=__SCREAMING_SNAKE_CASE , seq_shapes={'''list''': (100,)} , ) print('''first set of iterations''' ) for func, kwargs in functions: print(func.__name__ , str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = func(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) print('''shuffling dataset''' ) lowercase_ : int = dataset.shuffle() print('''Second set of iterations (after shuffling''' ) for func, kwargs in functions_shuffled: print('''shuffled ''' , func.__name__ , str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = func( __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as f: f.write(json.dumps(__SCREAMING_SNAKE_CASE ).encode('''utf-8''' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
93
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
1
'''simple docstring''' import random class lowerCAmelCase__ : @staticmethod def _snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = [ord(__SCREAMING_SNAKE_CASE ) for i in text] lowercase_ : Optional[Any] = [] lowercase_ : Union[str, Any] = [] for i in plain: lowercase_ : List[str] = random.randint(1 , 3_00 ) lowercase_ : Optional[int] = (i + k) * k cipher.append(__SCREAMING_SNAKE_CASE ) key.append(__SCREAMING_SNAKE_CASE ) return cipher, key @staticmethod def _snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): lowercase_ : Union[str, Any] = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(__SCREAMING_SNAKE_CASE ) ) return "".join(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": _lowercase , _lowercase : Optional[int] = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
93
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
1
'''simple docstring''' from jiwer import compute_measures import datasets _lowercase : List[Any] = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n" _lowercase : Optional[int] = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n" _lowercase : str = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> wer = datasets.load_metric(\"wer\")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def _snake_case ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', ] , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=False ): """simple docstring""" if concatenate_texts: return compute_measures(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )["wer"] else: lowercase_ : Any = 0 lowercase_ : Any = 0 for prediction, reference in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : List[Any] = compute_measures(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [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 _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
'''simple docstring''' from __future__ import annotations _lowercase : Tuple = 8.988E9 # units = N * m^s * C^-2 def snake_case_ ( __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float ): """simple docstring""" lowercase_ : int = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if distance < 0: raise ValueError('''Distance cannot be negative''' ) if force == 0: lowercase_ : List[Any] = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: lowercase_ : Union[str, Any] = abs(__SCREAMING_SNAKE_CASE ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: lowercase_ : Dict = abs(__SCREAMING_SNAKE_CASE ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: lowercase_ : Tuple = (COULOMBS_CONSTANT * charge_product / abs(__SCREAMING_SNAKE_CASE )) ** 0.5 return {"distance": distance} raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
93
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" lowercase_ : int = scheduler lowercase_ : Optional[int] = optimizers if isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ) else [optimizers] lowercase_ : Optional[Any] = split_batches lowercase_ : Union[str, Any] = step_with_optimizer lowercase_ : List[Any] = GradientState() def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step lowercase_ : Union[str, Any] = AcceleratorState().num_processes for _ in range(__SCREAMING_SNAKE_CASE ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , '''total_steps''' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) else: self.scheduler.step(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.scheduler.get_last_lr() def _snake_case ( self ): """simple docstring""" return self.scheduler.state_dict() def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" self.scheduler.load_state_dict(__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.scheduler.get_lr() def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.scheduler.print_lr(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
93
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = 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(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(__SCREAMING_SNAKE_CASE ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
93
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
1
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer _lowercase : Optional[int] = ["gpt2"] _lowercase : Union[str, Any] = "gpt2" if is_tf_available(): class lowerCAmelCase__ ( tf.Module ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__() lowercase_ : int = tokenizer lowercase_ : List[str] = AutoConfig.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = TFGPTaLMHeadModel.from_config(__SCREAMING_SNAKE_CASE ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.tokenizer(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = tokenized['''input_ids'''].to_tensor() lowercase_ : int = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) lowercase_ : Any = self.model(input_ids=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE )['''logits'''] return outputs @require_tf @require_keras_nlp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" super().setUp() lowercase_ : List[str] = [GPTaTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) for checkpoint in (TOKENIZER_CHECKPOINTS)] lowercase_ : Dict = [TFGPTaTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) lowercase_ : Optional[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ċ, ꝼ''', ] lowercase_ : Optional[int] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _snake_case ( self ): """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: lowercase_ : str = tokenizer([test_inputs] , return_tensors='''tf''' ) lowercase_ : Tuple = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors lowercase_ : int = python_outputs[key].numpy() lowercase_ : List[str] = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(__SCREAMING_SNAKE_CASE , tf.intaa ) == tf_outputs_values ) ) @slow def _snake_case ( self ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: lowercase_ : str = tf.function(__SCREAMING_SNAKE_CASE ) for test_inputs in self.test_sentences: lowercase_ : str = tf.constant(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = compiled_tokenizer(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = tf_tokenizer(__SCREAMING_SNAKE_CASE ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _snake_case ( self ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: lowercase_ : Dict = ModelToSave(tokenizer=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = tf.convert_to_tensor([self.test_sentences[0]] ) lowercase_ : Union[str, Any] = model.serving(__SCREAMING_SNAKE_CASE ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ) / '''saved.model''' tf.saved_model.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , signatures={'''serving_default''': model.serving} ) lowercase_ : List[str] = tf.saved_model.load(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = loaded_model.signatures['''serving_default'''](__SCREAMING_SNAKE_CASE )['''output_0'''] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def _snake_case ( self ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: lowercase_ : Dict = tf.convert_to_tensor([self.test_sentences[0]] ) lowercase_ : Optional[int] = tf_tokenizer(__SCREAMING_SNAKE_CASE ) # Build model with some sample inputs lowercase_ : Tuple = tf_tokenizer.get_config() lowercase_ : int = TFGPTaTokenizer.from_config(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = model_from_config(__SCREAMING_SNAKE_CASE ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def _snake_case ( self ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run lowercase_ : Union[str, Any] = 12_31_23 for max_length in [3, 5, 10_24]: lowercase_ : Dict = tf.convert_to_tensor([self.test_sentences[0]] ) lowercase_ : Dict = tf_tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = out['''input_ids'''].numpy().shape[1] assert out_length == max_length
93
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() _lowercase : int = logging.get_logger(__name__) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Tuple=False ): """simple docstring""" lowercase_ : Tuple = [] # fmt: off # stem: rename_keys.append(('''cls_token''', '''vit.embeddings.cls_token''') ) rename_keys.append(('''pos_embed''', '''vit.embeddings.position_embeddings''') ) rename_keys.append(('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias''') ) # backbone rename_keys.append(('''patch_embed.backbone.stem.conv.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.bias''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias''') ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowercase_ : Union[str, Any] = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) # fmt: on return rename_keys def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Any=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: lowercase_ : int = '''''' else: lowercase_ : Any = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowercase_ : Optional[Any] = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) lowercase_ : int = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict lowercase_ : List[str] = in_proj_weight[ : config.hidden_size, : ] lowercase_ : List[str] = in_proj_bias[: config.hidden_size] lowercase_ : List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowercase_ : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowercase_ : List[str] = in_proj_weight[ -config.hidden_size :, : ] lowercase_ : Tuple = in_proj_bias[-config.hidden_size :] def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : Optional[int] = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : Union[str, Any] = dct.pop(__SCREAMING_SNAKE_CASE ) lowercase_ : str = val def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase_ : Optional[Any] = Image.open(requests.get(__SCREAMING_SNAKE_CASE , stream=__SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def snake_case_ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int=False ): """simple docstring""" lowercase_ : Optional[int] = BitConfig( global_padding='''same''' , layer_type='''bottleneck''' , depths=(3, 4, 9) , out_features=['''stage3'''] , embedding_dynamic_padding=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = ViTHybridConfig(backbone_config=__SCREAMING_SNAKE_CASE , image_size=384 , num_labels=1000 ) lowercase_ : Optional[int] = False # load original model from timm lowercase_ : Tuple = timm.create_model(__SCREAMING_SNAKE_CASE , pretrained=__SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowercase_ : str = timm_model.state_dict() if base_model: remove_classification_head_(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = create_rename_keys(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) read_in_q_k_v(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = '''huggingface/label-files''' lowercase_ : Union[str, Any] = '''imagenet-1k-id2label.json''' lowercase_ : Union[str, Any] = json.load(open(hf_hub_download(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , repo_type='''dataset''' ) , '''r''' ) ) lowercase_ : Dict = {int(__SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} lowercase_ : Dict = idalabel lowercase_ : Any = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": lowercase_ : Optional[int] = ViTHybridModel(__SCREAMING_SNAKE_CASE ).eval() else: lowercase_ : int = ViTHybridForImageClassification(__SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(__SCREAMING_SNAKE_CASE ) # create image processor lowercase_ : Any = create_transform(**resolve_data_config({} , model=__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = transform.transforms lowercase_ : int = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } lowercase_ : int = ViTHybridImageProcessor( do_resize=__SCREAMING_SNAKE_CASE , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=__SCREAMING_SNAKE_CASE , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=__SCREAMING_SNAKE_CASE , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowercase_ : List[str] = prepare_img() lowercase_ : Any = transform(__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) lowercase_ : Optional[int] = processor(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # verify logits with torch.no_grad(): lowercase_ : Union[str, Any] = model(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = outputs.logits print('''Predicted class:''' , logits.argmax(-1 ).item() ) if base_model: lowercase_ : Dict = timm_model.forward_features(__SCREAMING_SNAKE_CASE ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__SCREAMING_SNAKE_CASE , outputs.pooler_output , atol=1E-3 ) else: lowercase_ : Union[str, Any] = timm_model(__SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__SCREAMING_SNAKE_CASE , outputs.logits , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) if push_to_hub: print(F'''Pushing model and processor to the hub {vit_name}''' ) model.push_to_hub(F'''ybelkada/{vit_name}''' ) processor.push_to_hub(F'''ybelkada/{vit_name}''' ) if __name__ == "__main__": _lowercase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) _lowercase : Tuple = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
1
'''simple docstring''' from __future__ import annotations from cmath import sqrt def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if a == 0: raise ValueError('''Coefficient \'a\' must not be zero.''' ) lowercase_ : List[Any] = b * b - 4 * a * c lowercase_ : Dict = (-b + sqrt(__SCREAMING_SNAKE_CASE )) / (2 * a) lowercase_ : Tuple = (-b - sqrt(__SCREAMING_SNAKE_CASE )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = quadratic_roots(a=5 , b=6 , c=1 ) print(F'''The solutions are: {solutiona} and {solutiona}''' ) if __name__ == "__main__": main()
93
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class lowerCAmelCase__ : lowerCAmelCase_ = MBartConfig lowerCAmelCase_ = {} lowerCAmelCase_ = '''gelu''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=13 , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=99 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=37 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=20 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0 , ): """simple docstring""" lowercase_ : List[str] = parent lowercase_ : Optional[int] = batch_size lowercase_ : Optional[int] = seq_length lowercase_ : List[str] = is_training lowercase_ : Dict = use_labels lowercase_ : Optional[Any] = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Dict = num_hidden_layers lowercase_ : int = num_attention_heads lowercase_ : Union[str, Any] = intermediate_size lowercase_ : int = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : int = max_position_embeddings lowercase_ : Union[str, Any] = eos_token_id lowercase_ : str = pad_token_id lowercase_ : Tuple = bos_token_id def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowercase_ : Any = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowercase_ : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) lowercase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase_ : Any = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) lowercase_ : str = prepare_mbart_inputs_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return config, inputs_dict def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = TFMBartModel(config=__SCREAMING_SNAKE_CASE ).get_decoder() lowercase_ : Dict = inputs_dict['''input_ids'''] lowercase_ : Tuple = input_ids[:1, :] lowercase_ : str = inputs_dict['''attention_mask'''][:1, :] lowercase_ : Optional[int] = inputs_dict['''head_mask'''] lowercase_ : Union[str, Any] = 1 # first forward pass lowercase_ : str = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , head_mask=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = outputs.to_tuple() lowercase_ : Tuple = past_key_values[1] def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : List[str]=None , ): """simple docstring""" if attention_mask is None: lowercase_ : Optional[int] = tf.cast(tf.math.not_equal(__SCREAMING_SNAKE_CASE , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowercase_ : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: lowercase_ : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowercase_ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowercase_ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () lowerCAmelCase_ = (TFMBartForConditionalGeneration,) if is_tf_available() else () lowerCAmelCase_ = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) lowerCAmelCase_ = True lowerCAmelCase_ = False lowerCAmelCase_ = False def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = TFMBartModelTester(self ) lowercase_ : Union[str, Any] = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__SCREAMING_SNAKE_CASE ) @require_sentencepiece @require_tokenizers @require_tf class lowerCAmelCase__ ( unittest.TestCase ): lowerCAmelCase_ = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] lowerCAmelCase_ = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] lowerCAmelCase_ = '''facebook/mbart-large-en-ro''' @cached_property def _snake_case ( self ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _snake_case ( self ): """simple docstring""" lowercase_ : Any = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = self.translate_src_text(**__SCREAMING_SNAKE_CASE ) self.assertListEqual(self.expected_text , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = self.tokenizer(self.src_text , **__SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) lowercase_ : str = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) lowercase_ : List[str] = self.tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) return generated_words @slow def _snake_case ( self ): """simple docstring""" self._assert_generated_batch_equal_expected()
93
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __SCREAMING_SNAKE_CASE : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : int = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = tabu_search( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": _lowercase : Any = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : dict ): """simple docstring""" lowercase_ : set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack lowercase_ : set[int] = set() return any( node not in visited and depth_first_search(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for node in graph ) def snake_case_ ( __SCREAMING_SNAKE_CASE : dict , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : set , __SCREAMING_SNAKE_CASE : set ): """simple docstring""" visited.add(__SCREAMING_SNAKE_CASE ) rec_stk.add(__SCREAMING_SNAKE_CASE ) for node in graph[vertex]: if node not in visited: if depth_first_search(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(__SCREAMING_SNAKE_CASE ) return False if __name__ == "__main__": from doctest import testmod testmod()
93
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
1
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Dict=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' lowercase_ : int = nn.Parameter(__SCREAMING_SNAKE_CASE ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' lowercase_ : Any = nn.Parameter(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : Optional[int] = np.asarray(weights[0] ) lowercase_ : Optional[Any] = np.asarray(weights[1] ) lowercase_ : Optional[int] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(1 , 2 ).contiguous().view(-1 , __SCREAMING_SNAKE_CASE ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(1 , 2 ).contiguous().view(-1 , __SCREAMING_SNAKE_CASE ) , ) set_param( torch_layer.output.dense , torch.tensor(__SCREAMING_SNAKE_CASE ).view(-1 , __SCREAMING_SNAKE_CASE ).contiguous().transpose(0 , 1 ) , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Union[str, Any] = np.asarray(weights[0] ) lowercase_ : Any = np.asarray(weights[1] ) lowercase_ : Optional[int] = np.asarray(weights[2] ) lowercase_ : int = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(1 , 2 ).contiguous().view(-1 , __SCREAMING_SNAKE_CASE ) , ) set_param( torch_layer.self_attention.key , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(1 , 2 ).contiguous().view(-1 , __SCREAMING_SNAKE_CASE ) , ) set_param( torch_layer.self_attention.value , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(1 , 2 ).contiguous().view(-1 , __SCREAMING_SNAKE_CASE ) , ) set_param( torch_layer.output.dense , torch.tensor(__SCREAMING_SNAKE_CASE ).view(-1 , __SCREAMING_SNAKE_CASE ).contiguous().transpose(0 , 1 ) , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" lowercase_ : Union[str, Any] = weights[0][0][0] lowercase_ : Optional[Any] = np.asarray(layer_norm_a[0] ) lowercase_ : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(__SCREAMING_SNAKE_CASE ) , torch.tensor(__SCREAMING_SNAKE_CASE ) , ) # lsh weights + output lowercase_ : Dict = weights[0][1] if len(__SCREAMING_SNAKE_CASE ) < 4: set_layer_weights_in_torch_lsh(__SCREAMING_SNAKE_CASE , torch_block.attention , __SCREAMING_SNAKE_CASE ) else: set_layer_weights_in_torch_local(__SCREAMING_SNAKE_CASE , torch_block.attention , __SCREAMING_SNAKE_CASE ) # intermediate weighs lowercase_ : Dict = weights[2][0][1][2] # Chunked Feed Forward if len(__SCREAMING_SNAKE_CASE ) == 4: lowercase_ : Any = intermediate_weights[2] # layernorm 2 lowercase_ : List[Any] = np.asarray(intermediate_weights[0][0] ) lowercase_ : Any = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(__SCREAMING_SNAKE_CASE ) , torch.tensor(__SCREAMING_SNAKE_CASE ) , ) # intermediate dense lowercase_ : List[str] = np.asarray(intermediate_weights[1][0] ) lowercase_ : List[str] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(0 , 1 ).contiguous() , torch.tensor(__SCREAMING_SNAKE_CASE ) , ) # intermediate out lowercase_ : int = np.asarray(intermediate_weights[4][0] ) lowercase_ : Union[str, Any] = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(0 , 1 ).contiguous() , torch.tensor(__SCREAMING_SNAKE_CASE ) , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : Tuple = torch_model.reformer # word embeds lowercase_ : Optional[Any] = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(__SCREAMING_SNAKE_CASE ) , ) if isinstance(weights[3] , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): lowercase_ : Tuple = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' lowercase_ : Any = nn.Parameter(torch.tensor(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Tuple = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( __SCREAMING_SNAKE_CASE ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): lowercase_ : Dict = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # output layer norm lowercase_ : List[str] = np.asarray(weights[7][0] ) lowercase_ : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(__SCREAMING_SNAKE_CASE ) , torch.tensor(__SCREAMING_SNAKE_CASE ) , ) # output embeddings lowercase_ : Optional[int] = np.asarray(weights[9][0] ) lowercase_ : Any = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(__SCREAMING_SNAKE_CASE ).transpose(0 , 1 ).contiguous() , torch.tensor(__SCREAMING_SNAKE_CASE ) , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = ReformerConfig.from_json_file(__SCREAMING_SNAKE_CASE ) print(F'''Building PyTorch model from configuration: {config}''' ) lowercase_ : Optional[Any] = ReformerModelWithLMHead(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , '''rb''' ) as f: lowercase_ : List[str] = pickle.load(__SCREAMING_SNAKE_CASE )['''weights'''] set_model_weights_in_torch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": _lowercase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--trax_model_pkl_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained Reformer model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _lowercase : str = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 lowerCAmelCase_ = None lowerCAmelCase_ = None _lowercase : Optional[int] = namedtuple("CoinsDistribResult", "moves excess") def snake_case_ ( __SCREAMING_SNAKE_CASE : TreeNode | None ): """simple docstring""" if root is None: return 0 # Validation def count_nodes(__SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(__SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(__SCREAMING_SNAKE_CASE ) != count_coins(__SCREAMING_SNAKE_CASE ): raise ValueError('''The nodes number should be same as the number of coins''' ) # Main calculation def get_distrib(__SCREAMING_SNAKE_CASE : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) lowercase_ , lowercase_ : Tuple = get_distrib(node.left ) lowercase_ , lowercase_ : Dict = get_distrib(node.right ) lowercase_ : Dict = 1 - left_distrib_excess lowercase_ : Optional[int] = 1 - right_distrib_excess lowercase_ : Tuple = ( left_distrib_moves + right_distrib_moves + abs(__SCREAMING_SNAKE_CASE ) + abs(__SCREAMING_SNAKE_CASE ) ) lowercase_ : int = node.data - coins_to_left - coins_to_right return CoinsDistribResult(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return get_distrib(__SCREAMING_SNAKE_CASE )[0] if __name__ == "__main__": import doctest doctest.testmod()
93
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : float ): """simple docstring""" return 10 - x * x def snake_case_ ( __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float ): """simple docstring""" if equation(__SCREAMING_SNAKE_CASE ) * equation(__SCREAMING_SNAKE_CASE ) >= 0: raise ValueError('''Wrong space!''' ) lowercase_ : Any = a while (b - a) >= 0.01: # Find middle point lowercase_ : Dict = (a + b) / 2 # Check if middle point is root if equation(__SCREAMING_SNAKE_CASE ) == 0.0: break # Decide the side to repeat the steps if equation(__SCREAMING_SNAKE_CASE ) * equation(__SCREAMING_SNAKE_CASE ) < 0: lowercase_ : Optional[Any] = c else: lowercase_ : List[Any] = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
93
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 1000 ): """simple docstring""" return sum(e for e in range(3 , __SCREAMING_SNAKE_CASE ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f"""{solution() = }""")
93
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 1000 ): """simple docstring""" lowercase_ : Optional[int] = 2**power lowercase_ : Any = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = list(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = 0 for i in list_num: sum_of_num += int(__SCREAMING_SNAKE_CASE ) return sum_of_num if __name__ == "__main__": _lowercase : Any = int(input("Enter the power of 2: ").strip()) print("2 ^ ", power, " = ", 2**power) _lowercase : Optional[int] = solution(power) print("Sum of the digits is: ", result)
93
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase : Optional[Any] = {"configuration_opt": ["OPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OPTConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : int = [ "OPT_PRETRAINED_MODEL_ARCHIVE_LIST", "OPTForCausalLM", "OPTModel", "OPTPreTrainedModel", "OPTForSequenceClassification", "OPTForQuestionAnswering", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : int = ["TFOPTForCausalLM", "TFOPTModel", "TFOPTPreTrainedModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "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 _lowercase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = XLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) lowercase_ : Union[str, Any] = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] ) # The dog is cute and lives in the garden house lowercase_ : Optional[Any] = torch.Size((1, 12, 7_68) ) # batch_size, sequence_length, embedding_vector_dim lowercase_ : Union[str, Any] = torch.tensor( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): lowercase_ : Optional[Any] = model(__SCREAMING_SNAKE_CASE )['''last_hidden_state'''].detach() self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = XLMRobertaModel.from_pretrained('''xlm-roberta-large''' ) lowercase_ : Any = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] ) # The dog is cute and lives in the garden house lowercase_ : List[Any] = torch.Size((1, 12, 10_24) ) # batch_size, sequence_length, embedding_vector_dim lowercase_ : str = torch.tensor( [[-0.0_699, -0.0_318, 0.0_705, -0.1_241, 0.0_999, -0.0_520, 0.1_004, -0.1_838, -0.4_704, 0.1_437, 0.0_821, 0.0_126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): lowercase_ : Optional[Any] = model(__SCREAMING_SNAKE_CASE )['''last_hidden_state'''].detach() self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __SCREAMING_SNAKE_CASE , atol=1E-3 ) )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ): """simple docstring""" lowercase_ : str = StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) lowercase_ : int = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler('''sample_euler''' ) lowercase_ : int = '''A painting of a squirrel eating a burger''' lowercase_ : Optional[int] = torch.manual_seed(0 ) lowercase_ : Optional[Any] = sd_pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) lowercase_ : str = output.images lowercase_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowercase_ : str = np.array([0.0_447, 0.0_492, 0.0_468, 0.0_408, 0.0_383, 0.0_408, 0.0_354, 0.0_380, 0.0_339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self ): """simple docstring""" lowercase_ : Any = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) lowercase_ : Optional[int] = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler('''sample_euler''' ) lowercase_ : Optional[int] = '''A painting of a squirrel eating a burger''' lowercase_ : List[Any] = torch.manual_seed(0 ) lowercase_ : Optional[int] = sd_pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) lowercase_ : Any = output.images lowercase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowercase_ : str = np.array([0.1_237, 0.1_320, 0.1_438, 0.1_359, 0.1_390, 0.1_132, 0.1_277, 0.1_175, 0.1_112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self ): """simple docstring""" lowercase_ : str = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) lowercase_ : Optional[Any] = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler('''sample_dpmpp_2m''' ) lowercase_ : List[Any] = '''A painting of a squirrel eating a burger''' lowercase_ : int = torch.manual_seed(0 ) lowercase_ : Dict = sd_pipe( [prompt] , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=15 , output_type='''np''' , use_karras_sigmas=__SCREAMING_SNAKE_CASE , ) lowercase_ : Union[str, Any] = output.images lowercase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) lowercase_ : Optional[int] = np.array( [0.11_381_689, 0.12_112_921, 0.1_389_457, 0.12_549_606, 0.1_244_964, 0.10_831_517, 0.11_562_866, 0.10_867_816, 0.10_499_048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor from ..utils import is_datasets_available from .base import PipelineTool if is_datasets_available(): from datasets import load_dataset class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''microsoft/speecht5_tts''' lowerCAmelCase_ = ( '''This is a tool that reads an English text out loud. It takes an input named `text` which should contain the ''' '''text to read (in English) and returns a waveform object containing the sound.''' ) lowerCAmelCase_ = '''text_reader''' lowerCAmelCase_ = SpeechTaProcessor lowerCAmelCase_ = SpeechTaForTextToSpeech lowerCAmelCase_ = SpeechTaHifiGan lowerCAmelCase_ = ['''text'''] lowerCAmelCase_ = ['''audio'''] def _snake_case ( self ): """simple docstring""" if self.post_processor is None: lowercase_ : str = '''microsoft/speecht5_hifigan''' super().setup() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : Tuple = self.pre_processor(text=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' , truncation=__SCREAMING_SNAKE_CASE ) if speaker_embeddings is None: if not is_datasets_available(): raise ImportError('''Datasets needs to be installed if not passing speaker embeddings.''' ) lowercase_ : Optional[Any] = load_dataset('''Matthijs/cmu-arctic-xvectors''' , split='''validation''' ) lowercase_ : List[str] = torch.tensor(embeddings_dataset[73_05]['''xvector'''] ).unsqueeze(0 ) return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" with torch.no_grad(): return self.model.generate_speech(**__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" with torch.no_grad(): return self.post_processor(__SCREAMING_SNAKE_CASE ).cpu().detach()
93
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = update_image_and_anno( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , filter_scale=__SCREAMING_SNAKE_CASE , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : int = F'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(__SCREAMING_SNAKE_CASE ) with open(F'''{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__SCREAMING_SNAKE_CASE ) labels.append(__SCREAMING_SNAKE_CASE ) return img_paths, labels def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : tuple[int, int] , __SCREAMING_SNAKE_CASE : tuple[float, float] , __SCREAMING_SNAKE_CASE : float = 0.0 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ 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 snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
1
'''simple docstring''' import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py _lowercase : Dict = "src/transformers" _lowercase : List[Any] = "docs/source/en" _lowercase : Optional[Any] = "." def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowercase_ : Tuple = f.readlines() # Find the start prompt. lowercase_ : List[str] = 0 while not lines[start_index].startswith(__SCREAMING_SNAKE_CASE ): start_index += 1 start_index += 1 lowercase_ : List[str] = start_index while not lines[end_index].startswith(__SCREAMING_SNAKE_CASE ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | _lowercase : List[Any] = "Model|Encoder|Decoder|ForConditionalGeneration" # Regexes that match TF/Flax/PT model names. _lowercase : Dict = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") _lowercase : Optional[Any] = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _lowercase : str = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # This is to make sure the transformers module imported is the one in the repo. _lowercase : Any = direct_transformers_import(TRANSFORMERS_PATH) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : Optional[Any] = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __SCREAMING_SNAKE_CASE ) return [m.group(0 ) for m in matches] def snake_case_ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : Union[str, Any] = 2 if text == '''✅''' or text == '''❌''' else len(__SCREAMING_SNAKE_CASE ) lowercase_ : str = (width - text_length) // 2 lowercase_ : str = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def snake_case_ ( ): """simple docstring""" lowercase_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowercase_ : Dict = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowercase_ : Dict = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowercase_ : Union[str, Any] = collections.defaultdict(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = collections.defaultdict(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = collections.defaultdict(__SCREAMING_SNAKE_CASE ) lowercase_ : str = collections.defaultdict(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = collections.defaultdict(__SCREAMING_SNAKE_CASE ) # Let's lookup through all transformers object (once). for attr_name in dir(__SCREAMING_SNAKE_CASE ): lowercase_ : Any = None if attr_name.endswith('''Tokenizer''' ): lowercase_ : Any = slow_tokenizers lowercase_ : List[str] = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): lowercase_ : Dict = fast_tokenizers lowercase_ : Optional[int] = attr_name[:-13] elif _re_tf_models.match(__SCREAMING_SNAKE_CASE ) is not None: lowercase_ : Any = tf_models lowercase_ : Any = _re_tf_models.match(__SCREAMING_SNAKE_CASE ).groups()[0] elif _re_flax_models.match(__SCREAMING_SNAKE_CASE ) is not None: lowercase_ : Union[str, Any] = flax_models lowercase_ : Dict = _re_flax_models.match(__SCREAMING_SNAKE_CASE ).groups()[0] elif _re_pt_models.match(__SCREAMING_SNAKE_CASE ) is not None: lowercase_ : str = pt_models lowercase_ : Any = _re_pt_models.match(__SCREAMING_SNAKE_CASE ).groups()[0] if lookup_dict is not None: while len(__SCREAMING_SNAKE_CASE ) > 0: if attr_name in model_name_to_prefix.values(): lowercase_ : int = True break # Try again after removing the last word in the name lowercase_ : Optional[int] = ''''''.join(camel_case_split(__SCREAMING_SNAKE_CASE )[:-1] ) # Let's build that table! lowercase_ : List[Any] = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowercase_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowercase_ : Any = [len(__SCREAMING_SNAKE_CASE ) + 2 for c in columns] lowercase_ : Any = max([len(__SCREAMING_SNAKE_CASE ) for name in model_names] ) + 2 # Build the table per se lowercase_ : str = '''|''' + '''|'''.join([_center_text(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for c, w in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" lowercase_ : int = {True: '''✅''', False: '''❌'''} for name in model_names: lowercase_ : Dict = model_name_to_prefix[name] lowercase_ : Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for l, w in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )] ) + "|\n" return table def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict=False ): """simple docstring""" lowercase_ , lowercase_ , lowercase_ , lowercase_ : Any = _find_text_in_file( filename=os.path.join(__SCREAMING_SNAKE_CASE , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) lowercase_ : str = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__SCREAMING_SNAKE_CASE , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": _lowercase : List[str] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _lowercase : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _lowercase : List[str] = logging.get_logger(__name__) # pylint: disable=invalid-name _lowercase : str = "\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"A red cartoon frog, 4k\"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n ... )\n >>> pipe.to(\"cuda\")\n\n >>> init_image = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/frog.png\"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save(\"red_frog.png\")\n ```\n" def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int]=8 ): """simple docstring""" lowercase_ : Dict = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 lowercase_ : int = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Any=512 , __SCREAMING_SNAKE_CASE : Dict=512 ): """simple docstring""" lowercase_ : str = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) lowercase_ : Any = np.array(pil_image.convert('''RGB''' ) ) lowercase_ : List[str] = arr.astype(np.floataa ) / 127.5 - 1 lowercase_ : List[str] = np.transpose(__SCREAMING_SNAKE_CASE , [2, 0, 1] ) lowercase_ : Union[str, Any] = torch.from_numpy(__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) return image class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__() self.register_modules( unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , movq=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = min(int(num_inference_steps * strength ) , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = max(num_inference_steps - init_timestep , 0 ) lowercase_ : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , (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(__SCREAMING_SNAKE_CASE )}''' ) lowercase_ : Union[str, Any] = image.to(device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = batch_size * num_images_per_prompt if image.shape[1] == 4: lowercase_ : Tuple = image else: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and len(__SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(__SCREAMING_SNAKE_CASE )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__SCREAMING_SNAKE_CASE ) ] lowercase_ : Any = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) else: lowercase_ : List[Any] = self.movq.encode(__SCREAMING_SNAKE_CASE ).latent_dist.sample(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.movq.config.scaling_factor * init_latents lowercase_ : List[Any] = torch.cat([init_latents] , dim=0 ) lowercase_ : List[Any] = init_latents.shape lowercase_ : str = randn_tensor(__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE ) # get latents lowercase_ : str = self.scheduler.add_noise(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = init_latents return latents def _snake_case ( self , __SCREAMING_SNAKE_CASE=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) lowercase_ : Tuple = torch.device(F'''cuda:{gpu_id}''' ) lowercase_ : str = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) lowercase_ : str = torch.device(F'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=__SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) lowercase_ : str = None for cpu_offloaded_model in [self.unet, self.movq]: lowercase_ , lowercase_ : Optional[int] = cpu_offload_with_hook(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , prev_module_hook=__SCREAMING_SNAKE_CASE ) # We'll offload the last model manually. lowercase_ : Any = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _snake_case ( self ): """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(__SCREAMING_SNAKE_CASE , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__SCREAMING_SNAKE_CASE ) def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 5_12 , __SCREAMING_SNAKE_CASE = 5_12 , __SCREAMING_SNAKE_CASE = 1_00 , __SCREAMING_SNAKE_CASE = 4.0 , __SCREAMING_SNAKE_CASE = 0.3 , __SCREAMING_SNAKE_CASE = 1 , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "pil" , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Tuple = self._execution_device lowercase_ : str = guidance_scale > 1.0 if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : str = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) lowercase_ : Union[str, Any] = image_embeds.shape[0] if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : str = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: lowercase_ : List[Any] = image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE , dim=0 ) lowercase_ : Optional[Any] = negative_image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE , dim=0 ) lowercase_ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [image] if not all(isinstance(__SCREAMING_SNAKE_CASE , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F'''Input is in incorrect format: {[type(__SCREAMING_SNAKE_CASE ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' ) lowercase_ : Any = torch.cat([prepare_image(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i in image] , dim=0 ) lowercase_ : Optional[Any] = image.to(dtype=image_embeds.dtype , device=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = self.movq.encode(__SCREAMING_SNAKE_CASE )['''latents'''] lowercase_ : List[Any] = latents.repeat_interleave(__SCREAMING_SNAKE_CASE , dim=0 ) self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = self.get_timesteps(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) lowercase_ , lowercase_ : Optional[Any] = downscale_height_and_width(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.movq_scale_factor ) lowercase_ : Tuple = self.prepare_latents( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , image_embeds.dtype , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i, t in enumerate(self.progress_bar(__SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance lowercase_ : List[Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowercase_ : Optional[int] = {'''image_embeds''': image_embeds} lowercase_ : List[Any] = self.unet( sample=__SCREAMING_SNAKE_CASE , timestep=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , added_cond_kwargs=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] if do_classifier_free_guidance: lowercase_ , lowercase_ : List[Any] = noise_pred.split(latents.shape[1] , dim=1 ) lowercase_ , lowercase_ : str = noise_pred.chunk(2 ) lowercase_ , lowercase_ : Optional[int] = variance_pred.chunk(2 ) lowercase_ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) lowercase_ : Dict = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): lowercase_ , lowercase_ : str = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 lowercase_ : Tuple = self.scheduler.step( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , )[0] # post-processing lowercase_ : Optional[int] = self.movq.decode(__SCREAMING_SNAKE_CASE , force_not_quantize=__SCREAMING_SNAKE_CASE )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: lowercase_ : Tuple = image * 0.5 + 0.5 lowercase_ : int = image.clamp(0 , 1 ) lowercase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowercase_ : Optional[Any] = self.numpy_to_pil(__SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=__SCREAMING_SNAKE_CASE )
93
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[str] = [0] * len(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = [] lowercase_ : int = [] lowercase_ : Optional[int] = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__SCREAMING_SNAKE_CASE ) ): if indegree[i] == 0: queue.append(__SCREAMING_SNAKE_CASE ) while queue: lowercase_ : List[str] = queue.pop(0 ) cnt += 1 topo.append(__SCREAMING_SNAKE_CASE ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(__SCREAMING_SNAKE_CASE ) if cnt != len(__SCREAMING_SNAKE_CASE ): print('''Cycle exists''' ) else: print(__SCREAMING_SNAKE_CASE ) # Adjacency List of Graph _lowercase : Dict = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
93
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
1
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [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 _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # [batch_size x 3] lowerCAmelCase_ = 42 # [batch_size x 3] lowerCAmelCase_ = 42 # [batch_size x 3] lowerCAmelCase_ = 42 # [batch_size x 3] lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 def _snake_case ( self ): """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def _snake_case ( self ): """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def _snake_case ( self ): """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = torch.arange(self.height * self.width ) lowercase_ : Union[str, Any] = torch.stack( [ pixel_indices % self.width, torch.div(__SCREAMING_SNAKE_CASE , self.width , rounding_mode='''trunc''' ), ] , axis=1 , ) return coords @property def _snake_case ( self ): """simple docstring""" lowercase_ , *lowercase_ : str = self.shape lowercase_ : List[Any] = int(np.prod(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = self.get_image_coords() lowercase_ : Tuple = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) lowercase_ : Dict = self.get_camera_rays(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = rays.view(__SCREAMING_SNAKE_CASE , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ , *lowercase_ , lowercase_ : str = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] lowercase_ : Any = coords.view(__SCREAMING_SNAKE_CASE , -1 , 2 ) lowercase_ : str = self.resolution() lowercase_ : Dict = self.fov() lowercase_ : Optional[Any] = (flat.float() / (res - 1)) * 2 - 1 lowercase_ : Any = fracs * torch.tan(fov / 2 ) lowercase_ : Optional[int] = fracs.view(__SCREAMING_SNAKE_CASE , -1 , 2 ) lowercase_ : Optional[Any] = ( self.z.view(__SCREAMING_SNAKE_CASE , 1 , 3 ) + self.x.view(__SCREAMING_SNAKE_CASE , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__SCREAMING_SNAKE_CASE , 1 , 3 ) * fracs[:, :, 1:] ) lowercase_ : List[str] = directions / directions.norm(dim=-1 , keepdim=__SCREAMING_SNAKE_CASE ) lowercase_ : str = torch.stack( [ torch.broadcast_to(self.origin.view(__SCREAMING_SNAKE_CASE , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , 2 , 3 ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__SCREAMING_SNAKE_CASE , height=__SCREAMING_SNAKE_CASE , x_fov=self.x_fov , y_fov=self.y_fov , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [] lowercase_ : List[str] = [] lowercase_ : int = [] lowercase_ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): lowercase_ : Dict = np.array([np.sin(__SCREAMING_SNAKE_CASE ), np.cos(__SCREAMING_SNAKE_CASE ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) lowercase_ : Tuple = -z * 4 lowercase_ : str = np.array([np.cos(__SCREAMING_SNAKE_CASE ), -np.sin(__SCREAMING_SNAKE_CASE ), 0.0] ) lowercase_ : Optional[Any] = np.cross(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) origins.append(__SCREAMING_SNAKE_CASE ) xs.append(__SCREAMING_SNAKE_CASE ) ys.append(__SCREAMING_SNAKE_CASE ) zs.append(__SCREAMING_SNAKE_CASE ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(__SCREAMING_SNAKE_CASE , axis=0 ) ).float() , x=torch.from_numpy(np.stack(__SCREAMING_SNAKE_CASE , axis=0 ) ).float() , y=torch.from_numpy(np.stack(__SCREAMING_SNAKE_CASE , axis=0 ) ).float() , z=torch.from_numpy(np.stack(__SCREAMING_SNAKE_CASE , axis=0 ) ).float() , width=__SCREAMING_SNAKE_CASE , height=__SCREAMING_SNAKE_CASE , x_fov=0.7 , y_fov=0.7 , shape=(1, len(__SCREAMING_SNAKE_CASE )) , )
93
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = 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(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
1
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets _lowercase : int = "\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n" _lowercase : Union[str, Any] = "\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.\n" _lowercase : Tuple = r"\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting \"1/2\" to \"\\frac{1}{2}\")\n\nExamples:\n >>> metric = datasets.load_metric(\"competition_math\")\n >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])\n >>> print(results)\n {'accuracy': 1.0}\n" @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def _snake_case ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = 0.0 for i, j in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): n_correct += 1.0 if math_equivalence.is_equiv(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else 0.0 lowercase_ : Union[str, Any] = n_correct / len(__SCREAMING_SNAKE_CASE ) return { "accuracy": accuracy, }
93
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
1
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Optional[int] , *__UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" warnings.warn( '''The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use PerceiverImageProcessor instead.''' , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
0
'''simple docstring''' # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path SCREAMING_SNAKE_CASE_: Any =Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) SCREAMING_SNAKE_CASE_: str ={'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} SCREAMING_SNAKE_CASE_: Union[str, Any] ='zero2' SCREAMING_SNAKE_CASE_: Dict ='zero3' SCREAMING_SNAKE_CASE_: Optional[Any] =[ZEROa, ZEROa] def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : Optional[Any] , snake_case_ : Optional[int] ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = parameterized.to_safe_name("_".join(str(snake_case_ ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test SCREAMING_SNAKE_CASE_: List[Any] =list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A ( UpperCamelCase__ ): @parameterized.expand(__a , name_func=__a ) def _lowercase (self : Union[str, Any] , __a : Dict , __a : Any ): self.run_and_check( stage=__a , model=__a , distributed=__a , fpaa=__a , ) @require_torch_multi_gpu @parameterized.expand(__a , name_func=__a ) def _lowercase (self : Tuple , __a : Dict , __a : List[Any] ): self.run_and_check( stage=__a , model=__a , distributed=__a , fpaa=__a , ) @parameterized.expand(__a , name_func=__a ) def _lowercase (self : Tuple , __a : Any , __a : str ): self.run_and_check( stage=__a , model=__a , distributed=__a , fpaa=__a , ) @require_torch_multi_gpu @parameterized.expand(__a , name_func=__a ) def _lowercase (self : int , __a : Union[str, Any] , __a : Any ): self.run_and_check( stage=__a , model=__a , distributed=__a , fpaa=__a , ) def _lowercase (self : str , __a : Optional[int] ): # XXX: run_asr is premature and doesn't save any results # so all we check for now is that the process didn't fail pass def _lowercase (self : List[str] , __a : str , __a : str , __a : int = 10 , __a : bool = True , __a : bool = True , __a : bool = True , ): UpperCAmelCase_ = models[model] UpperCAmelCase_ = self.run_trainer( stage=__a , model_name=__a , eval_steps=__a , num_train_epochs=1 , distributed=__a , fpaa=__a , ) self.do_checks(__a ) return output_dir def _lowercase (self : Any , __a : str , __a : str , __a : int = 10 , __a : int = 1 , __a : bool = True , __a : bool = True , ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir("./xxx" , after=__a ) UpperCAmelCase_ = f""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(__a )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["--fp16"] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files UpperCAmelCase_ = f"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() UpperCAmelCase_ = [f"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] UpperCAmelCase_ = self.get_launcher(__a ) UpperCAmelCase_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(__a , env=self.get_env() ) return output_dir def _lowercase (self : Any , __a : List[str]=False ): # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup # - it won't be able to handle that # 2. for now testing with just 2 gpus max (since some quality tests may give different # results with mode gpus because we use very little data) UpperCAmelCase_ = min(2 , get_gpu_count() ) if distributed else 1 return f"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
0
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : List[str] = { 'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json', 'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json', 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json', 'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json', 'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json', 'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json', 'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json', 'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json', 'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json', 'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json', 'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json', 'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Any = """codegen""" lowerCAmelCase__ : Union[str, Any] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__(self : Any , UpperCamelCase : List[Any]=50400 , UpperCamelCase : Optional[Any]=2048 , UpperCamelCase : List[Any]=2048 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : Union[str, Any]=28 , UpperCamelCase : Optional[Any]=16 , UpperCamelCase : Dict=64 , UpperCamelCase : Tuple=None , UpperCamelCase : Optional[int]="gelu_new" , UpperCamelCase : str=0.0 , UpperCamelCase : Dict=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : int=1E-5 , UpperCamelCase : str=0.02 , UpperCamelCase : Union[str, Any]=True , UpperCamelCase : Optional[Any]=50256 , UpperCamelCase : Dict=50256 , UpperCamelCase : int=False , **UpperCamelCase : Optional[int] , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = n_ctx lowercase__ = n_positions lowercase__ = n_embd lowercase__ = n_layer lowercase__ = n_head lowercase__ = n_inner lowercase__ = rotary_dim lowercase__ = activation_function lowercase__ = resid_pdrop lowercase__ = embd_pdrop lowercase__ = attn_pdrop lowercase__ = layer_norm_epsilon lowercase__ = initializer_range lowercase__ = use_cache lowercase__ = bos_token_id lowercase__ = eos_token_id super().__init__( bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , tie_word_embeddings=UpperCamelCase , **UpperCamelCase ) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Union[str, Any] , UpperCamelCase : PretrainedConfig , UpperCamelCase : str = "default" , UpperCamelCase : List[PatchingSpec] = None , UpperCamelCase : bool = False , ): '''simple docstring''' super().__init__(UpperCamelCase , task=UpperCamelCase , patching_specs=UpperCamelCase , use_past=UpperCamelCase ) if not getattr(self._config , '''pad_token_id''' , UpperCamelCase ): # TODO: how to do that better? lowercase__ = 0 @property def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(UpperCamelCase , direction='''inputs''' ) lowercase__ = {0: '''batch''', 1: '''past_sequence + sequence'''} else: lowercase__ = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def UpperCamelCase__ (self : Any ): '''simple docstring''' return self._config.n_layer @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return self._config.n_head def UpperCamelCase__ (self : List[Any] , UpperCamelCase : PreTrainedTokenizer , UpperCamelCase : int = -1 , UpperCamelCase : int = -1 , UpperCamelCase : bool = False , UpperCamelCase : Optional[TensorType] = None , ): '''simple docstring''' lowercase__ = super(UpperCamelCase , self ).generate_dummy_inputs( UpperCamelCase , batch_size=UpperCamelCase , seq_length=UpperCamelCase , is_pair=UpperCamelCase , framework=UpperCamelCase ) # We need to order the input in the way they appears in the forward() lowercase__ = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch lowercase__ ,lowercase__ = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values lowercase__ = seqlen + 2 lowercase__ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowercase__ = [ (torch.zeros(UpperCamelCase ), torch.zeros(UpperCamelCase )) for _ in range(self.num_layers ) ] lowercase__ = common_inputs['''attention_mask'''] if self.use_past: lowercase__ = ordered_inputs['''attention_mask'''].dtype lowercase__ = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(UpperCamelCase , UpperCamelCase , dtype=UpperCamelCase )] , dim=1 ) return ordered_inputs @property def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' return 13
2
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class A ( __snake_case ): __magic_name__ = '''Salesforce/blip-image-captioning-base''' __magic_name__ = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) __magic_name__ = '''image_captioner''' __magic_name__ = AutoModelForVisionaSeq __magic_name__ = ['''image'''] __magic_name__ = ['''text'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return self.pre_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" return self.model.generate(**SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.pre_processor.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE )[0].strip()
3
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __SCREAMING_SNAKE_CASE : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : int = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = tabu_search( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": _lowercase : Any = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
93
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case =logging.get_logger(__name__) __snake_case ={ """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""", """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""", } class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : int = '''roberta''' def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple=5_0_2_6_5 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : int=3_0_7_2 , UpperCAmelCase__ : Any="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Any=5_1_2 , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : Optional[Any]=1E-12 , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Optional[int]=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : List[str]="absolute" , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : List[Any] , ) -> Any: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = hidden_act lowerCAmelCase = intermediate_size 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 = position_embedding_type lowerCAmelCase = use_cache lowerCAmelCase = classifier_dropout class UpperCAmelCase_ ( __lowercase ): @property def __UpperCAmelCase ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowerCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
4
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
0
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = OrderedDict( [ # Base model mapping ('''albert''', '''FlaxAlbertModel'''), ('''bart''', '''FlaxBartModel'''), ('''beit''', '''FlaxBeitModel'''), ('''bert''', '''FlaxBertModel'''), ('''big_bird''', '''FlaxBigBirdModel'''), ('''blenderbot''', '''FlaxBlenderbotModel'''), ('''blenderbot-small''', '''FlaxBlenderbotSmallModel'''), ('''clip''', '''FlaxCLIPModel'''), ('''distilbert''', '''FlaxDistilBertModel'''), ('''electra''', '''FlaxElectraModel'''), ('''gpt-sw3''', '''FlaxGPT2Model'''), ('''gpt2''', '''FlaxGPT2Model'''), ('''gpt_neo''', '''FlaxGPTNeoModel'''), ('''gptj''', '''FlaxGPTJModel'''), ('''longt5''', '''FlaxLongT5Model'''), ('''marian''', '''FlaxMarianModel'''), ('''mbart''', '''FlaxMBartModel'''), ('''mt5''', '''FlaxMT5Model'''), ('''opt''', '''FlaxOPTModel'''), ('''pegasus''', '''FlaxPegasusModel'''), ('''regnet''', '''FlaxRegNetModel'''), ('''resnet''', '''FlaxResNetModel'''), ('''roberta''', '''FlaxRobertaModel'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormModel'''), ('''roformer''', '''FlaxRoFormerModel'''), ('''t5''', '''FlaxT5Model'''), ('''vision-text-dual-encoder''', '''FlaxVisionTextDualEncoderModel'''), ('''vit''', '''FlaxViTModel'''), ('''wav2vec2''', '''FlaxWav2Vec2Model'''), ('''whisper''', '''FlaxWhisperModel'''), ('''xglm''', '''FlaxXGLMModel'''), ('''xlm-roberta''', '''FlaxXLMRobertaModel'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for pre-training mapping ('''albert''', '''FlaxAlbertForPreTraining'''), ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''bert''', '''FlaxBertForPreTraining'''), ('''big_bird''', '''FlaxBigBirdForPreTraining'''), ('''electra''', '''FlaxElectraForPreTraining'''), ('''longt5''', '''FlaxLongT5ForConditionalGeneration'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''mt5''', '''FlaxMT5ForConditionalGeneration'''), ('''roberta''', '''FlaxRobertaForMaskedLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMaskedLM'''), ('''roformer''', '''FlaxRoFormerForMaskedLM'''), ('''t5''', '''FlaxT5ForConditionalGeneration'''), ('''wav2vec2''', '''FlaxWav2Vec2ForPreTraining'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMaskedLM'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Masked LM mapping ('''albert''', '''FlaxAlbertForMaskedLM'''), ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''bert''', '''FlaxBertForMaskedLM'''), ('''big_bird''', '''FlaxBigBirdForMaskedLM'''), ('''distilbert''', '''FlaxDistilBertForMaskedLM'''), ('''electra''', '''FlaxElectraForMaskedLM'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''roberta''', '''FlaxRobertaForMaskedLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMaskedLM'''), ('''roformer''', '''FlaxRoFormerForMaskedLM'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMaskedLM'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''blenderbot''', '''FlaxBlenderbotForConditionalGeneration'''), ('''blenderbot-small''', '''FlaxBlenderbotSmallForConditionalGeneration'''), ('''encoder-decoder''', '''FlaxEncoderDecoderModel'''), ('''longt5''', '''FlaxLongT5ForConditionalGeneration'''), ('''marian''', '''FlaxMarianMTModel'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''mt5''', '''FlaxMT5ForConditionalGeneration'''), ('''pegasus''', '''FlaxPegasusForConditionalGeneration'''), ('''t5''', '''FlaxT5ForConditionalGeneration'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Image-classsification ('''beit''', '''FlaxBeitForImageClassification'''), ('''regnet''', '''FlaxRegNetForImageClassification'''), ('''resnet''', '''FlaxResNetForImageClassification'''), ('''vit''', '''FlaxViTForImageClassification'''), ] ) UpperCAmelCase__ = OrderedDict( [ ('''vision-encoder-decoder''', '''FlaxVisionEncoderDecoderModel'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Causal LM mapping ('''bart''', '''FlaxBartForCausalLM'''), ('''bert''', '''FlaxBertForCausalLM'''), ('''big_bird''', '''FlaxBigBirdForCausalLM'''), ('''electra''', '''FlaxElectraForCausalLM'''), ('''gpt-sw3''', '''FlaxGPT2LMHeadModel'''), ('''gpt2''', '''FlaxGPT2LMHeadModel'''), ('''gpt_neo''', '''FlaxGPTNeoForCausalLM'''), ('''gptj''', '''FlaxGPTJForCausalLM'''), ('''opt''', '''FlaxOPTForCausalLM'''), ('''roberta''', '''FlaxRobertaForCausalLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForCausalLM'''), ('''xglm''', '''FlaxXGLMForCausalLM'''), ('''xlm-roberta''', '''FlaxXLMRobertaForCausalLM'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Sequence Classification mapping ('''albert''', '''FlaxAlbertForSequenceClassification'''), ('''bart''', '''FlaxBartForSequenceClassification'''), ('''bert''', '''FlaxBertForSequenceClassification'''), ('''big_bird''', '''FlaxBigBirdForSequenceClassification'''), ('''distilbert''', '''FlaxDistilBertForSequenceClassification'''), ('''electra''', '''FlaxElectraForSequenceClassification'''), ('''mbart''', '''FlaxMBartForSequenceClassification'''), ('''roberta''', '''FlaxRobertaForSequenceClassification'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForSequenceClassification'''), ('''roformer''', '''FlaxRoFormerForSequenceClassification'''), ('''xlm-roberta''', '''FlaxXLMRobertaForSequenceClassification'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Question Answering mapping ('''albert''', '''FlaxAlbertForQuestionAnswering'''), ('''bart''', '''FlaxBartForQuestionAnswering'''), ('''bert''', '''FlaxBertForQuestionAnswering'''), ('''big_bird''', '''FlaxBigBirdForQuestionAnswering'''), ('''distilbert''', '''FlaxDistilBertForQuestionAnswering'''), ('''electra''', '''FlaxElectraForQuestionAnswering'''), ('''mbart''', '''FlaxMBartForQuestionAnswering'''), ('''roberta''', '''FlaxRobertaForQuestionAnswering'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForQuestionAnswering'''), ('''roformer''', '''FlaxRoFormerForQuestionAnswering'''), ('''xlm-roberta''', '''FlaxXLMRobertaForQuestionAnswering'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Token Classification mapping ('''albert''', '''FlaxAlbertForTokenClassification'''), ('''bert''', '''FlaxBertForTokenClassification'''), ('''big_bird''', '''FlaxBigBirdForTokenClassification'''), ('''distilbert''', '''FlaxDistilBertForTokenClassification'''), ('''electra''', '''FlaxElectraForTokenClassification'''), ('''roberta''', '''FlaxRobertaForTokenClassification'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForTokenClassification'''), ('''roformer''', '''FlaxRoFormerForTokenClassification'''), ('''xlm-roberta''', '''FlaxXLMRobertaForTokenClassification'''), ] ) UpperCAmelCase__ = OrderedDict( [ # Model for Multiple Choice mapping ('''albert''', '''FlaxAlbertForMultipleChoice'''), ('''bert''', '''FlaxBertForMultipleChoice'''), ('''big_bird''', '''FlaxBigBirdForMultipleChoice'''), ('''distilbert''', '''FlaxDistilBertForMultipleChoice'''), ('''electra''', '''FlaxElectraForMultipleChoice'''), ('''roberta''', '''FlaxRobertaForMultipleChoice'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMultipleChoice'''), ('''roformer''', '''FlaxRoFormerForMultipleChoice'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMultipleChoice'''), ] ) UpperCAmelCase__ = OrderedDict( [ ('''bert''', '''FlaxBertForNextSentencePrediction'''), ] ) UpperCAmelCase__ = OrderedDict( [ ('''speech-encoder-decoder''', '''FlaxSpeechEncoderDecoderModel'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ] ) UpperCAmelCase__ = OrderedDict( [ ('''whisper''', '''FlaxWhisperForAudioClassification'''), ] ) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_MAPPING UpperCAmelCase__ = auto_class_update(FlaxAutoModel) class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase__ = auto_class_update(FlaxAutoModelForPreTraining, head_doc='''pretraining''') class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase__ = auto_class_update(FlaxAutoModelForCausalLM, head_doc='''causal language modeling''') class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase__ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='''masked language modeling''') class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase__ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='''sequence-to-sequence language modeling''', checkpoint_for_example='''t5-base''' ) class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase__ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='''sequence classification''' ) class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase__ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='''question answering''') class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase__ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='''token classification''' ) class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase__ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='''multiple choice''') class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase__ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='''next sentence prediction''' ) class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase__ = auto_class_update( FlaxAutoModelForImageClassification, head_doc='''image classification''' ) class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase__ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='''vision-to-text modeling''') class lowerCamelCase__ ( _BaseAutoModelClass): SCREAMING_SNAKE_CASE__ = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase__ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='''sequence-to-sequence speech-to-text modeling''' )
5
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
0
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __A( a ): snake_case_ = None snake_case_ = None snake_case_ = None snake_case_ = None class __A( a ): def __init__( self , _snake_case=1 , _snake_case=0 , _snake_case=2 , _snake_case=512 , _snake_case="cls" , _snake_case=False , _snake_case=True , **_snake_case , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case ) __a = project_dim __a = pooler_fn __a = learn_encoder __a = use_attention_mask class __A( a ): snake_case_ = [r'''pooler''', r'''logit_scale'''] snake_case_ = [r'''position_ids''', r'''predictions.decoder.bias'''] snake_case_ = '''roberta''' snake_case_ = RobertaSeriesConfig def __init__( self , _snake_case ) -> Tuple: '''simple docstring''' super().__init__(_snake_case ) __a = XLMRobertaModel(_snake_case ) __a = nn.Linear(config.hidden_size , config.project_dim ) __a = getattr(_snake_case , '''has_pre_transformation''' , _snake_case ) if self.has_pre_transformation: __a = nn.Linear(config.hidden_size , config.project_dim ) __a = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def SCREAMING_SNAKE_CASE_ ( self , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , ) -> int: '''simple docstring''' __a = return_dict if return_dict is not None else self.config.use_return_dict __a = self.base_model( input_ids=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , position_ids=_snake_case , head_mask=_snake_case , inputs_embeds=_snake_case , encoder_hidden_states=_snake_case , encoder_attention_mask=_snake_case , output_attentions=_snake_case , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=_snake_case , ) if self.has_pre_transformation: __a = outputs['''hidden_states'''][-2] __a = self.pre_LN(_snake_case ) __a = self.transformation_pre(_snake_case ) return TransformationModelOutput( projection_state=_snake_case , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: __a = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=_snake_case , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
6
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin lowercase_ = False @skip_mps class A ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = StableDiffusionAttendAndExcitePipeline lowerCamelCase = False lowerCamelCase = TEXT_TO_IMAGE_PARAMS lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'} ) lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def snake_case__ ( cls : Any )-> Optional[Any]: '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(lowercase_ ) @classmethod def snake_case__ ( cls : Optional[Any] )-> Dict: '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(lowercase_ ) def snake_case__ ( self : List[str] )-> int: '''simple docstring''' torch.manual_seed(0 ) A__ = UNetaDConditionModel( block_out_channels=(3_2, 6_4),layers_per_block=1,sample_size=3_2,in_channels=4,out_channels=4,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D'),up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D'),cross_attention_dim=3_2,attention_head_dim=(2, 4),use_linear_projection=lowercase_,) A__ = DDIMScheduler( beta_start=0.00_085,beta_end=0.012,beta_schedule='scaled_linear',clip_sample=lowercase_,set_alpha_to_one=lowercase_,) torch.manual_seed(0 ) A__ = AutoencoderKL( block_out_channels=[3_2, 6_4],in_channels=3,out_channels=3,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'],up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'],latent_channels=4,sample_size=1_2_8,) torch.manual_seed(0 ) A__ = CLIPTextConfig( bos_token_id=0,eos_token_id=2,hidden_size=3_2,intermediate_size=3_7,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1_0_0_0,hidden_act='gelu',projection_dim=5_1_2,) A__ = CLIPTextModel(lowercase_ ) A__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) A__ = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def snake_case__ ( self : Tuple,lowercase_ : str,lowercase_ : List[Any]=0 )-> int: '''simple docstring''' if str(lowercase_ ).startswith('mps' ): A__ = torch.manual_seed(lowercase_ ) else: A__ = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) A__ = A__ = { 'prompt': 'a cat and a frog', 'token_indices': [2, 5], 'generator': generator, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', 'max_iter_to_alter': 2, 'thresholds': {0: 0.7}, } return inputs def snake_case__ ( self : List[str] )-> Optional[Any]: '''simple docstring''' A__ = 'cpu' A__ = self.get_dummy_components() A__ = self.pipeline_class(**lowercase_ ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) A__ = self.get_dummy_inputs(lowercase_ ) A__ = pipe(**lowercase_ ).images A__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape,(1, 6_4, 6_4, 3) ) A__ = np.array( [0.63_905_364, 0.62_897_307, 0.48_599_017, 0.5_133_624, 0.5_550_048, 0.45_769_516, 0.50_326_973, 0.5_023_139, 0.45_384_496] ) A__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowercase_,1E-3 ) def snake_case__ ( self : str )-> Optional[Any]: '''simple docstring''' super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def snake_case__ ( self : str )-> int: '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def snake_case__ ( self : str )-> Optional[int]: '''simple docstring''' self._test_inference_batch_single_identical(batch_size=2,expected_max_diff=7E-4 ) def snake_case__ ( self : Optional[Any] )-> int: '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def snake_case__ ( self : Union[str, Any] )-> str: '''simple docstring''' super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def snake_case__ ( self : Dict )-> Any: '''simple docstring''' super().test_save_load_local(expected_max_difference=5E-4 ) def snake_case__ ( self : Dict )-> List[str]: '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class A ( unittest.TestCase ): """simple docstring""" @classmethod def snake_case__ ( cls : Any )-> Optional[int]: '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(lowercase_ ) @classmethod def snake_case__ ( cls : int )-> List[Any]: '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(lowercase_ ) def snake_case__ ( self : List[Any] )-> Any: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__ ( self : Union[str, Any] )-> List[Any]: '''simple docstring''' A__ = torch.manual_seed(5_1 ) A__ = StableDiffusionAttendAndExcitePipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4',safety_checker=lowercase_,torch_dtype=torch.floataa ) pipe.to('cuda' ) A__ = 'a painting of an elephant with glasses' A__ = [5, 7] A__ = pipe( prompt=lowercase_,token_indices=lowercase_,guidance_scale=7.5,generator=lowercase_,num_inference_steps=5,max_iter_to_alter=5,output_type='numpy',).images[0] A__ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy' ) assert np.abs((expected_image - image).max() ) < 5E-1
7
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
0
from itertools import product def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = sides_number snake_case_ = max_face_number * dice_number snake_case_ = [0] * (max_total + 1) snake_case_ = 1 snake_case_ = range(SCREAMING_SNAKE_CASE__ , max_face_number + 1 ) for dice_numbers in product(SCREAMING_SNAKE_CASE__ , repeat=SCREAMING_SNAKE_CASE__ ): snake_case_ = sum(SCREAMING_SNAKE_CASE__ ) totals_frequencies[total] += 1 return totals_frequencies def __SCREAMING_SNAKE_CASE (): snake_case_ = total_frequency_distribution( sides_number=4 , dice_number=9 ) snake_case_ = total_frequency_distribution( sides_number=6 , dice_number=6 ) snake_case_ = 0 snake_case_ = 9 snake_case_ = 4 * 9 snake_case_ = 6 for peter_total in range(SCREAMING_SNAKE_CASE__ , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) snake_case_ = (4**9) * (6**6) snake_case_ = peter_wins_count / total_games_number snake_case_ = round(SCREAMING_SNAKE_CASE__ , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(f"""{solution() = }""")
8
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : List[str] =logging.get_logger(__name__) def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : Any = SwinConfig( embed_dim=192 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['''stage2''', '''stage3''', '''stage4'''] , ) __SCREAMING_SNAKE_CASE : Tuple = DetaConfig( backbone_config=lowercase__ , num_queries=900 , encoder_ffn_dim=2048 , decoder_ffn_dim=2048 , num_feature_levels=5 , assign_first_stage=lowercase__ , with_box_refine=lowercase__ , two_stage=lowercase__ , ) # set labels __SCREAMING_SNAKE_CASE : Tuple = '''huggingface/label-files''' if "o365" in model_name: __SCREAMING_SNAKE_CASE : Dict = 366 __SCREAMING_SNAKE_CASE : Any = '''object365-id2label.json''' else: __SCREAMING_SNAKE_CASE : List[str] = 91 __SCREAMING_SNAKE_CASE : List[Any] = '''coco-detection-id2label.json''' __SCREAMING_SNAKE_CASE : List[str] = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='''dataset''' ) ) , '''r''' ) ) __SCREAMING_SNAKE_CASE : Dict = {int(lowercase__ ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : Optional[Any] = idalabel __SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in idalabel.items()} return config def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : int = [] # stem # fmt: off rename_keys.append(('''backbone.0.body.patch_embed.proj.weight''', '''model.backbone.model.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.proj.bias''', '''model.backbone.model.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.weight''', '''model.backbone.model.embeddings.norm.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.bias''', '''model.backbone.model.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append(('''backbone.0.body.norm1.weight''', '''model.backbone.model.hidden_states_norms.stage2.weight''') ) rename_keys.append(('''backbone.0.body.norm1.bias''', '''model.backbone.model.hidden_states_norms.stage2.bias''') ) rename_keys.append(('''backbone.0.body.norm2.weight''', '''model.backbone.model.hidden_states_norms.stage3.weight''') ) rename_keys.append(('''backbone.0.body.norm2.bias''', '''model.backbone.model.hidden_states_norms.stage3.bias''') ) rename_keys.append(('''backbone.0.body.norm3.weight''', '''model.backbone.model.hidden_states_norms.stage4.weight''') ) rename_keys.append(('''backbone.0.body.norm3.bias''', '''model.backbone.model.hidden_states_norms.stage4.bias''') ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias''') ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias''') ) # fmt: on return rename_keys def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Tuple = dct.pop(lowercase__ ) __SCREAMING_SNAKE_CASE : Any = val def _UpperCamelCase ( lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : str = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __SCREAMING_SNAKE_CASE : Optional[Any] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight''' ) __SCREAMING_SNAKE_CASE : Tuple = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __SCREAMING_SNAKE_CASE : Any = in_proj_weight[:dim, :] __SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[: dim] __SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : str = in_proj_bias[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[ -dim :, : ] __SCREAMING_SNAKE_CASE : Tuple = in_proj_bias[-dim :] # fmt: on def _UpperCamelCase ( lowercase__ , lowercase__ ): # transformer decoder self-attention layers __SCREAMING_SNAKE_CASE : Any = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention __SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) __SCREAMING_SNAKE_CASE : Any = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict __SCREAMING_SNAKE_CASE : Any = in_proj_weight[:hidden_size, :] __SCREAMING_SNAKE_CASE : Tuple = in_proj_bias[:hidden_size] __SCREAMING_SNAKE_CASE : str = in_proj_weight[ hidden_size : hidden_size * 2, : ] __SCREAMING_SNAKE_CASE : Optional[int] = in_proj_bias[hidden_size : hidden_size * 2] __SCREAMING_SNAKE_CASE : int = in_proj_weight[-hidden_size:, :] __SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-hidden_size:] def _UpperCamelCase ( ): __SCREAMING_SNAKE_CASE : int = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __SCREAMING_SNAKE_CASE : Optional[int] = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) return im @torch.no_grad() def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Tuple = get_deta_config(lowercase__ ) # load original state dict if model_name == "deta-swin-large": __SCREAMING_SNAKE_CASE : Union[str, Any] = hf_hub_download(repo_id='''nielsr/deta-checkpoints''' , filename='''adet_swin_ft.pth''' ) elif model_name == "deta-swin-large-o365": __SCREAMING_SNAKE_CASE : Optional[Any] = hf_hub_download(repo_id='''jozhang97/deta-swin-l-o365''' , filename='''deta_swin_pt_o365.pth''' ) else: raise ValueError(F'''Model name {model_name} not supported''' ) __SCREAMING_SNAKE_CASE : Dict = torch.load(lowercase__ , map_location='''cpu''' )['''model'''] # original state dict for name, param in state_dict.items(): print(lowercase__ , param.shape ) # rename keys __SCREAMING_SNAKE_CASE : Optional[int] = create_rename_keys(lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_swin_q_k_v(lowercase__ , config.backbone_config ) read_in_decoder_q_k_v(lowercase__ , lowercase__ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: __SCREAMING_SNAKE_CASE : Tuple = state_dict.pop(lowercase__ ) __SCREAMING_SNAKE_CASE : List[str] = val if "input_proj" in key: __SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(lowercase__ ) __SCREAMING_SNAKE_CASE : str = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: __SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(lowercase__ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = val # finally, create HuggingFace model and load state dict __SCREAMING_SNAKE_CASE : List[str] = DetaForObjectDetection(lowercase__ ) model.load_state_dict(lowercase__ ) model.eval() __SCREAMING_SNAKE_CASE : List[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu''' model.to(lowercase__ ) # load image processor __SCREAMING_SNAKE_CASE : Union[str, Any] = DetaImageProcessor(format='''coco_detection''' ) # verify our conversion on image __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : Optional[Any] = processor(images=lowercase__ , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Optional[int] = encoding['''pixel_values'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = model(pixel_values.to(lowercase__ ) ) # verify logits print('''Logits:''' , outputs.logits[0, :3, :3] ) print('''Boxes:''' , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": __SCREAMING_SNAKE_CASE : str = torch.tensor( [[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]] ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]] ) elif model_name == "deta-swin-large-o365": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]] ) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(lowercase__ ) , atol=1e-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(lowercase__ ) , atol=1e-4 ) print('''Everything ok!''' ) if pytorch_dump_folder_path: # Save model and processor logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...''' ) Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) # Push to hub if push_to_hub: print('''Pushing model and processor to hub...''' ) model.push_to_hub(F'''jozhang97/{model_name}''' ) processor.push_to_hub(F'''jozhang97/{model_name}''' ) if __name__ == "__main__": __lowerCAmelCase : str =argparse.ArgumentParser() parser.add_argument( '--model_name', type=str, default='deta-swin-large', choices=['deta-swin-large', 'deta-swin-large-o365'], help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowerCAmelCase : List[str] =parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
9
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = StableDiffusionXLImgaImgPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} lowercase_ = PipelineTesterMixin.required_optional_params - {"latents"} lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Tuple: '''simple docstring''' torch.manual_seed(0) lowerCamelCase__: Tuple =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=UpperCAmelCase_ , 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 , ) lowerCamelCase__: Tuple =EulerDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , steps_offset=1 , beta_schedule="scaled_linear" , timestep_spacing="leading" , ) torch.manual_seed(0) lowerCamelCase__: Tuple =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) lowerCamelCase__: Union[str, Any] =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=32 , ) lowerCamelCase__: Optional[Any] =CLIPTextModel(UpperCAmelCase_) lowerCamelCase__: List[str] =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =CLIPTextModelWithProjection(UpperCAmelCase_) lowerCamelCase__: Optional[int] =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=UpperCAmelCase_) lowerCamelCase__: int ={ "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_encoder_2": text_encoder_a, "tokenizer_2": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int]=0) ->List[Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase_)).to(UpperCAmelCase_) lowerCamelCase__: Any =image / 2 + 0.5 if str(UpperCAmelCase_).startswith("mps"): lowerCamelCase__: str =torch.manual_seed(UpperCAmelCase_) else: lowerCamelCase__: List[str] =torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_) lowerCamelCase__: Any ={ "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 SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict: '''simple docstring''' lowerCamelCase__: str ="cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase__: List[str] =self.get_dummy_components() lowerCamelCase__: Union[str, Any] =StableDiffusionXLImgaImgPipeline(**UpperCAmelCase_) lowerCamelCase__: Dict =sd_pipe.to(UpperCAmelCase_) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_) lowerCamelCase__: Dict =self.get_dummy_inputs(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =sd_pipe(**UpperCAmelCase_).images lowerCamelCase__: int =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCamelCase__: 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 SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[int]: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Dict: '''simple docstring''' lowerCamelCase__: Optional[int] =self.get_dummy_components() lowerCamelCase__: Dict =StableDiffusionXLImgaImgPipeline(**UpperCAmelCase_) lowerCamelCase__: str =sd_pipe.to(UpperCAmelCase_) lowerCamelCase__: List[Any] =sd_pipe.to(UpperCAmelCase_) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_) # forward without prompt embeds lowerCamelCase__: int =self.get_dummy_inputs(UpperCAmelCase_) lowerCamelCase__: List[Any] =3 * ["this is a negative prompt"] lowerCamelCase__: Tuple =negative_prompt lowerCamelCase__: int =3 * [inputs["prompt"]] lowerCamelCase__: Tuple =sd_pipe(**UpperCAmelCase_) lowerCamelCase__: Tuple =output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCamelCase__: Union[str, Any] =self.get_dummy_inputs(UpperCAmelCase_) lowerCamelCase__: Dict =3 * ["this is a negative prompt"] lowerCamelCase__: Any =3 * [inputs.pop("prompt")] ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ): Tuple =sd_pipe.encode_prompt(UpperCAmelCase_ , negative_prompt=UpperCAmelCase_) lowerCamelCase__: int =sd_pipe( **UpperCAmelCase_ , prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , pooled_prompt_embeds=UpperCAmelCase_ , negative_pooled_prompt_embeds=UpperCAmelCase_ , ) lowerCamelCase__: Optional[int] =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 ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]="cpu" , UpperCAmelCase_ : Optional[int]=torch.floataa , UpperCAmelCase_ : Any=0) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] =torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =np.random.RandomState(UpperCAmelCase_).standard_normal((1, 4, 64, 64)) lowerCamelCase__: Union[str, Any] =torch.from_numpy(UpperCAmelCase_).to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) lowerCamelCase__: Any ={ "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 SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: List[str] =DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base") pipe.to(UpperCAmelCase_) pipe.set_progress_bar_config(disable=UpperCAmelCase_) lowerCamelCase__: int =self.get_inputs(UpperCAmelCase_) lowerCamelCase__: str =pipe(**UpperCAmelCase_).images lowerCamelCase__: Tuple =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) lowerCamelCase__: int =np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]) assert np.abs(image_slice - expected_slice).max() < 7E-3
10
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
0
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
11
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
0
import functools def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = len(A__ ) __lowerCamelCase = len(A__ ) @functools.cache def min_distance(A__ : int , A__ : int ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa __lowerCamelCase = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , A__ ) , 1 + min_distance(A__ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
12
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
0
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = checkpoint SCREAMING_SNAKE_CASE_: Union[str, Any] = {} SCREAMING_SNAKE_CASE_: Any = vae_state_dict["encoder.conv_in.weight"] SCREAMING_SNAKE_CASE_: Tuple = vae_state_dict["encoder.conv_in.bias"] SCREAMING_SNAKE_CASE_: Dict = vae_state_dict["encoder.conv_out.weight"] SCREAMING_SNAKE_CASE_: Optional[Any] = vae_state_dict["encoder.conv_out.bias"] SCREAMING_SNAKE_CASE_: Any = vae_state_dict["encoder.norm_out.weight"] SCREAMING_SNAKE_CASE_: Dict = vae_state_dict["encoder.norm_out.bias"] SCREAMING_SNAKE_CASE_: Tuple = vae_state_dict["decoder.conv_in.weight"] SCREAMING_SNAKE_CASE_: Union[str, Any] = vae_state_dict["decoder.conv_in.bias"] SCREAMING_SNAKE_CASE_: int = vae_state_dict["decoder.conv_out.weight"] SCREAMING_SNAKE_CASE_: Optional[int] = vae_state_dict["decoder.conv_out.bias"] SCREAMING_SNAKE_CASE_: Any = vae_state_dict["decoder.norm_out.weight"] SCREAMING_SNAKE_CASE_: Optional[int] = vae_state_dict["decoder.norm_out.bias"] SCREAMING_SNAKE_CASE_: List[Any] = vae_state_dict["quant_conv.weight"] SCREAMING_SNAKE_CASE_: int = vae_state_dict["quant_conv.bias"] SCREAMING_SNAKE_CASE_: List[Any] = vae_state_dict["post_quant_conv.weight"] SCREAMING_SNAKE_CASE_: Optional[int] = vae_state_dict["post_quant_conv.bias"] # Retrieves the keys for the encoder down blocks only SCREAMING_SNAKE_CASE_: int = len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "encoder.down" in layer} ) SCREAMING_SNAKE_CASE_: Any = { layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(_UpperCAmelCase ) } # Retrieves the keys for the decoder up blocks only SCREAMING_SNAKE_CASE_: Optional[int] = len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "decoder.up" in layer} ) SCREAMING_SNAKE_CASE_: List[Any] = { layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(_UpperCAmelCase ) } for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key] if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict: SCREAMING_SNAKE_CASE_: str = vae_state_dict.pop( f"encoder.down.{i}.downsample.conv.weight" ) SCREAMING_SNAKE_CASE_: Dict = vae_state_dict.pop( f"encoder.down.{i}.downsample.conv.bias" ) SCREAMING_SNAKE_CASE_: Dict = renew_vae_resnet_paths(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: str = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"} assign_to_checkpoint(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , additional_replacements=[meta_path] , config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] = [key for key in vae_state_dict if "encoder.mid.block" in key] SCREAMING_SNAKE_CASE_: str = 2 for i in range(1 , num_mid_res_blocks + 1 ): SCREAMING_SNAKE_CASE_: Any = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key] SCREAMING_SNAKE_CASE_: List[Any] = renew_vae_resnet_paths(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: int = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"} assign_to_checkpoint(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , additional_replacements=[meta_path] , config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = [key for key in vae_state_dict if "encoder.mid.attn" in key] SCREAMING_SNAKE_CASE_: List[str] = renew_vae_attention_paths(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] = {"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , additional_replacements=[meta_path] , config=_UpperCAmelCase ) conv_attn_to_linear(_UpperCAmelCase ) for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Union[str, Any] = num_up_blocks - 1 - i SCREAMING_SNAKE_CASE_: Union[str, Any] = [ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key ] if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict: SCREAMING_SNAKE_CASE_: Dict = vae_state_dict[ f"decoder.up.{block_id}.upsample.conv.weight" ] SCREAMING_SNAKE_CASE_: Optional[Any] = vae_state_dict[ f"decoder.up.{block_id}.upsample.conv.bias" ] SCREAMING_SNAKE_CASE_: Optional[Any] = renew_vae_resnet_paths(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"} assign_to_checkpoint(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , additional_replacements=[meta_path] , config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = [key for key in vae_state_dict if "decoder.mid.block" in key] SCREAMING_SNAKE_CASE_: Tuple = 2 for i in range(1 , num_mid_res_blocks + 1 ): SCREAMING_SNAKE_CASE_: Dict = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key] SCREAMING_SNAKE_CASE_: Any = renew_vae_resnet_paths(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"} assign_to_checkpoint(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , additional_replacements=[meta_path] , config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple = [key for key in vae_state_dict if "decoder.mid.attn" in key] SCREAMING_SNAKE_CASE_: Any = renew_vae_attention_paths(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] = {"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , additional_replacements=[meta_path] , config=_UpperCAmelCase ) conv_attn_to_linear(_UpperCAmelCase ) return new_checkpoint def A_ ( _UpperCAmelCase , _UpperCAmelCase , ): # Only support V1 SCREAMING_SNAKE_CASE_: Tuple = requests.get( " https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml" ) SCREAMING_SNAKE_CASE_: Optional[int] = io.BytesIO(r.content ) SCREAMING_SNAKE_CASE_: Any = OmegaConf.load(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] = 5_12 SCREAMING_SNAKE_CASE_: Tuple = "cuda" if torch.cuda.is_available() else "cpu" if checkpoint_path.endswith("safetensors" ): from safetensors import safe_open SCREAMING_SNAKE_CASE_: Optional[Any] = {} with safe_open(_UpperCAmelCase , framework="pt" , device="cpu" ) as f: for key in f.keys(): SCREAMING_SNAKE_CASE_: Any = f.get_tensor(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE_: Optional[int] = torch.load(_UpperCAmelCase , map_location=_UpperCAmelCase )["state_dict"] # Convert the VAE model. SCREAMING_SNAKE_CASE_: Optional[int] = create_vae_diffusers_config(_UpperCAmelCase , image_size=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] = custom_convert_ldm_vae_checkpoint(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: int = AutoencoderKL(**_UpperCAmelCase ) vae.load_state_dict(_UpperCAmelCase ) vae.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--vae_pt_path""", default=None, type=str, required=True, help="""Path to the VAE.pt to convert.""") parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the VAE.pt to convert.""") lowerCAmelCase : Optional[int] = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
13
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
0
from __future__ import annotations _lowerCamelCase : Optional[Any] = 1.60_21E-19 # units = C def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , ) -> tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif conductivity < 0: raise ValueError('''Conductivity cannot be negative''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative''' ) elif mobility < 0: raise ValueError('''mobility cannot be negative''' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
14
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = update_image_and_anno( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , filter_scale=__SCREAMING_SNAKE_CASE , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : int = F'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(__SCREAMING_SNAKE_CASE ) with open(F'''{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__SCREAMING_SNAKE_CASE ) labels.append(__SCREAMING_SNAKE_CASE ) return img_paths, labels def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : tuple[int, int] , __SCREAMING_SNAKE_CASE : tuple[float, float] , __SCREAMING_SNAKE_CASE : float = 0.0 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ 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 snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
0
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def UpperCAmelCase ( a_ ) -> np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def UpperCAmelCase ( a_ , a_ , a_ ) -> np.ndarray: """simple docstring""" __A = np.nan for i in range(a_ ): __A = features[:, labels == i] __A = data.mean(1 ) # Centralize the data of class i __A = data - column_reshape(a_ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(a_ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __A = np.dot(a_ , centered_data.T ) return covariance_sum / features.shape[1] def UpperCAmelCase ( a_ , a_ , a_ ) -> np.ndarray: """simple docstring""" __A = features.mean(1 ) __A = np.nan for i in range(a_ ): __A = features[:, labels == i] __A = data.shape[1] __A = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(a_ ) - column_reshape(a_ ) , (column_reshape(a_ ) - column_reshape(a_ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __A = device_data * np.dot( column_reshape(a_ ) - column_reshape(a_ ) , (column_reshape(a_ ) - column_reshape(a_ )).T , ) return covariance_sum / features.shape[1] def UpperCAmelCase ( a_ , a_ ) -> np.ndarray: """simple docstring""" if features.any(): __A = features.mean(1 ) # Center the dataset __A = features - np.reshape(a_ , (data_mean.size, 1) ) __A = np.dot(a_ , centered_data.T ) / features.shape[1] __A , __A = np.linalg.eigh(a_ ) # Take all the columns in the reverse order (-1), and then takes only the first __A = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __A = np.dot(filtered_eigenvectors.T , a_ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=a_ ) logging.error("Dataset empty" ) raise AssertionError def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: __A , __A = eigh( covariance_between_classes(a_ , a_ , a_ ) , covariance_within_classes(a_ , a_ , a_ ) , ) __A = eigenvectors[:, ::-1][:, :dimensions] __A , __A , __A = np.linalg.svd(a_ ) __A = svd_matrix[:, 0:dimensions] __A = np.dot(filtered_svd_matrix.T , a_ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=a_ ) logging.error("Dataset empty" ) raise AssertionError def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __A = np.array([0, 0, 0, 1, 1] ) __A = 2 __A = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(a_ ) as error_info: __A = linear_discriminant_analysis( a_ , a_ , a_ , a_ ) if isinstance(a_ , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __A = 2 __A = np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]] ) with pytest.raises(a_ ) as error_info: __A = principal_component_analysis(a_ , a_ ) if not np.allclose(a_ , a_ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
15
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
0
"""simple docstring""" from importlib import import_module from .logging import get_logger lowerCAmelCase_ = get_logger(__name__) class __A : '''simple docstring''' def __init__( self : Tuple ,_snake_case : List[Any] ,_snake_case : Tuple=None ) -> Optional[int]: """simple docstring""" lowercase__ : Dict = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('''__''' ): setattr(self ,_snake_case ,getattr(_snake_case ,_snake_case ) ) lowercase__ : List[Any] = module._original_module if isinstance(_snake_case ,_PatchedModuleObj ) else module class __A : '''simple docstring''' lowerCAmelCase : str = [] def __init__( self : int ,_snake_case : List[Any] ,_snake_case : str ,_snake_case : Union[str, Any] ,_snake_case : Dict=None ) -> int: """simple docstring""" lowercase__ : Union[str, Any] = obj lowercase__ : Tuple = target lowercase__ : str = new lowercase__ : Union[str, Any] = target.split('''.''' )[0] lowercase__ : str = {} lowercase__ : str = attrs or [] def __enter__( self : Any ) -> Any: """simple docstring""" *lowercase__ , lowercase__ : Optional[Any] = self.target.split('''.''' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(_snake_case ) ): try: lowercase__ : int = import_module('''.'''.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): lowercase__ : Any = getattr(self.obj ,_snake_case ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(_snake_case ,_PatchedModuleObj ) and obj_attr._original_module is submodule) ): lowercase__ : Optional[Any] = obj_attr # patch at top level setattr(self.obj ,_snake_case ,_PatchedModuleObj(_snake_case ,attrs=self.attrs ) ) lowercase__ : Optional[int] = getattr(self.obj ,_snake_case ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(_snake_case ,_snake_case ,_PatchedModuleObj(getattr(_snake_case ,_snake_case ,_snake_case ) ,attrs=self.attrs ) ) lowercase__ : str = getattr(_snake_case ,_snake_case ) # finally set the target attribute setattr(_snake_case ,_snake_case ,self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: lowercase__ : Tuple = getattr(import_module('''.'''.join(_snake_case ) ) ,_snake_case ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj ,_snake_case ) is attr_value: lowercase__ : Union[str, Any] = getattr(self.obj ,_snake_case ) setattr(self.obj ,_snake_case ,self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" lowercase__ : Tuple = globals()['''__builtins__'''][target_attr] setattr(self.obj ,_snake_case ,self.new ) else: raise RuntimeError(f"""Tried to patch attribute {target_attr} instead of a submodule.""" ) def __exit__( self : Optional[int] ,*_snake_case : int ) -> Any: """simple docstring""" for attr in list(self.original ): setattr(self.obj ,_snake_case ,self.original.pop(_snake_case ) ) def UpperCAmelCase ( self : List[str] ) -> List[Any]: """simple docstring""" self.__enter__() self._active_patches.append(self ) def UpperCAmelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
16
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
0
"""simple docstring""" import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class _lowerCAmelCase : """simple docstring""" def __init__( self : List[Any], UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : List[Any]=1_3, UpperCAmelCase__ : Union[str, Any]=7, UpperCAmelCase__ : Tuple=True, UpperCAmelCase__ : Optional[Any]=True, UpperCAmelCase__ : Optional[int]=False, UpperCAmelCase__ : Union[str, Any]=True, UpperCAmelCase__ : Tuple=9_9, UpperCAmelCase__ : Optional[Any]=6_4, UpperCAmelCase__ : str=5, UpperCAmelCase__ : Optional[Any]=4, UpperCAmelCase__ : List[str]=6_4, UpperCAmelCase__ : Any="gelu", UpperCAmelCase__ : int=0.1, UpperCAmelCase__ : Tuple=0.1, UpperCAmelCase__ : Optional[Any]=5_1_2, UpperCAmelCase__ : Union[str, Any]=1_6, UpperCAmelCase__ : List[Any]=2, UpperCAmelCase__ : Tuple=0.02, UpperCAmelCase__ : str=3, UpperCAmelCase__ : List[str]=4, UpperCAmelCase__ : Dict=None, ): __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_input_mask __lowercase = use_token_type_ids __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = type_sequence_label_size __lowercase = initializer_range __lowercase = num_labels __lowercase = num_choices __lowercase = scope def _lowercase ( self : List[str] ): return MPNetConfig.from_pretrained("microsoft/mpnet-base" ) def _lowercase ( self : Union[str, Any] ): __lowercase = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __lowercase = None if self.use_input_mask: __lowercase = random_attention_mask([self.batch_size, self.seq_length] ) __lowercase = None __lowercase = None __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size], self.type_sequence_label_size ) __lowercase = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) __lowercase = ids_tensor([self.batch_size], self.num_choices ) __lowercase = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Dict ): return MPNetConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, ) def _lowercase ( self : Optional[int], UpperCAmelCase__ : str, UpperCAmelCase__ : Any, UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Optional[Any] ): __lowercase = MPNetModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __lowercase = model(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size) ) def _lowercase ( self : Optional[Any], UpperCAmelCase__ : int, UpperCAmelCase__ : str, UpperCAmelCase__ : Any, UpperCAmelCase__ : Tuple, UpperCAmelCase__ : int, UpperCAmelCase__ : str ): __lowercase = MPNetForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __lowercase = model( UpperCAmelCase__, attention_mask=UpperCAmelCase__, start_positions=UpperCAmelCase__, end_positions=UpperCAmelCase__, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def _lowercase ( self : Optional[Any], UpperCAmelCase__ : int, UpperCAmelCase__ : int, UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : List[str] ): __lowercase = self.num_labels __lowercase = MPNetForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __lowercase = model(UpperCAmelCase__, attention_mask=UpperCAmelCase__, labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def _lowercase ( self : int, UpperCAmelCase__ : int, UpperCAmelCase__ : List[str], UpperCAmelCase__ : Any, UpperCAmelCase__ : Any, UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : List[str] ): __lowercase = self.num_choices __lowercase = MPNetForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __lowercase = input_ids.unsqueeze(1 ).expand(-1, self.num_choices, -1 ).contiguous() __lowercase = input_mask.unsqueeze(1 ).expand(-1, self.num_choices, -1 ).contiguous() __lowercase = model( UpperCAmelCase__, attention_mask=UpperCAmelCase__, labels=UpperCAmelCase__, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices) ) def _lowercase ( self : Optional[int], UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : int, UpperCAmelCase__ : Tuple, UpperCAmelCase__ : Any, UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : List[Any] ): __lowercase = self.num_labels __lowercase = MPNetForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __lowercase = model(UpperCAmelCase__, attention_mask=UpperCAmelCase__, labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : int ): __lowercase = self.prepare_config_and_inputs() ((__lowercase) ,(__lowercase) ,(__lowercase) ,(__lowercase) ,(__lowercase) ,(__lowercase)) = config_and_inputs __lowercase = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _lowerCAmelCase ( lowercase ,lowercase ,unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) __UpperCAmelCase : Optional[int] = ( { "feature-extraction": MPNetModel, "fill-mask": MPNetForMaskedLM, "question-answering": MPNetForQuestionAnswering, "text-classification": MPNetForSequenceClassification, "token-classification": MPNetForTokenClassification, "zero-shot": MPNetForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Any = False __UpperCAmelCase : List[Any] = True def _lowercase ( self : int ): __lowercase = MPNetModelTester(self ) __lowercase = ConfigTester(self, config_class=UpperCAmelCase__, hidden_size=3_7 ) def _lowercase ( self : Dict ): self.config_tester.run_common_tests() def _lowercase ( self : Union[str, Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*UpperCAmelCase__ ) def _lowercase ( self : Optional[Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*UpperCAmelCase__ ) def _lowercase ( self : Optional[int] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*UpperCAmelCase__ ) def _lowercase ( self : Union[str, Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*UpperCAmelCase__ ) def _lowercase ( self : Optional[int] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*UpperCAmelCase__ ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @slow def _lowercase ( self : Dict ): __lowercase = MPNetModel.from_pretrained("microsoft/mpnet-base" ) __lowercase = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) __lowercase = model(UpperCAmelCase__ )[0] __lowercase = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape, UpperCAmelCase__ ) __lowercase = torch.tensor( [[[-0.0_550, 0.1_943, -0.0_740], [-0.0_562, 0.2_211, -0.0_579], [-0.0_437, 0.3_337, -0.0_641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3], UpperCAmelCase__, atol=1E-4 ) )
17
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
0
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __lowerCamelCase : Dict = 10 def _snake_case ( lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : list[int] , lowerCAmelCase : int ): """simple docstring""" for i in range(lowerCAmelCase , lowerCAmelCase ): if array[i] == target: return i return -1 def _snake_case ( lowerCAmelCase : list[int] , lowerCAmelCase : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : str = len(lowerCAmelCase ) while left <= right: if right - left < precision: return lin_search(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Dict = (left + right) // 3 + 1 SCREAMING_SNAKE_CASE_ : Dict = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: SCREAMING_SNAKE_CASE_ : Dict = one_third - 1 elif array[two_third] < target: SCREAMING_SNAKE_CASE_ : Any = two_third + 1 else: SCREAMING_SNAKE_CASE_ : List[str] = one_third + 1 SCREAMING_SNAKE_CASE_ : int = two_third - 1 else: return -1 def _snake_case ( lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : list[int] , lowerCAmelCase : int ): """simple docstring""" if left < right: if right - left < precision: return lin_search(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : str = (left + right) // 3 + 1 SCREAMING_SNAKE_CASE_ : Dict = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(lowerCAmelCase , one_third - 1 , lowerCAmelCase , lowerCAmelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , lowerCAmelCase , lowerCAmelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __lowerCamelCase : Optional[Any] = input('''Enter numbers separated by comma:\n''').strip() __lowerCamelCase : str = [int(item.strip()) for item in user_input.split(''',''')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __lowerCamelCase : str = int(input('''Enter the number to be found in the list:\n''').strip()) __lowerCamelCase : int = ite_ternary_search(collection, target) __lowerCamelCase : Tuple = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print('''Not found''')
18
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [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 _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
0
from __future__ import annotations def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = [True] * limit lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): lowerCamelCase_ = i * 2 while index < limit: lowerCamelCase_ = False lowerCamelCase_ = index + i lowerCamelCase_ = [2] for i in range(3 , lowerCamelCase__ , 2 ): if is_prime[i]: primes.append(lowerCamelCase__ ) return primes def lowerCamelCase_ ( lowerCamelCase__ = 1_0_0_0_0_0_0 ): lowerCamelCase_ = prime_sieve(lowerCamelCase__ ) lowerCamelCase_ = 0 lowerCamelCase_ = 0 for i in range(len(lowerCamelCase__ ) ): for j in range(i + length , len(lowerCamelCase__ ) ): lowerCamelCase_ = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: lowerCamelCase_ = j - i lowerCamelCase_ = sol return largest if __name__ == "__main__": print(F"""{solution() = }""")
19
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
0
import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowercase : List[Any] = logging.get_logger(__name__) class __snake_case ( enum.Enum ): _a : Any= 0 _a : Optional[Any]= 1 @add_end_docstrings(lowerCAmelCase ) class __snake_case ( lowerCAmelCase ): _a : int= "generated" def __init__( self ,*snake_case ,**snake_case ): '''simple docstring''' super().__init__(*snake_case ,**snake_case ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def _SCREAMING_SNAKE_CASE ( self ,snake_case=None ,snake_case=None ,snake_case=None ,snake_case=None ,snake_case=None ,snake_case=None ,**snake_case ,): '''simple docstring''' lowercase : Optional[Any] = {} if truncation is not None: lowercase : int = truncation lowercase : Union[str, Any] = generate_kwargs lowercase : List[Any] = {} if return_tensors is not None and return_type is None: lowercase : Any = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: lowercase : Dict = return_type if clean_up_tokenization_spaces is not None: lowercase : Optional[Any] = clean_up_tokenization_spaces if stop_sequence is not None: lowercase : Union[str, Any] = self.tokenizer.encode(snake_case ,add_special_tokens=snake_case ) if len(snake_case ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) lowercase : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self ,*snake_case ,snake_case ): '''simple docstring''' lowercase : Union[str, Any] = self.model.config.prefix if self.model.config.prefix is not None else """""" if isinstance(args[0] ,snake_case ): if self.tokenizer.pad_token_id is None: raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input""" ) lowercase : int = ([prefix + arg for arg in args[0]],) lowercase : str = True elif isinstance(args[0] ,snake_case ): lowercase : Optional[int] = (prefix + args[0],) lowercase : Union[str, Any] = False else: raise ValueError( f" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`" ) lowercase : Optional[int] = self.tokenizer(*snake_case ,padding=snake_case ,truncation=snake_case ,return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self ,*snake_case ,**snake_case ): '''simple docstring''' lowercase : Optional[Any] = super().__call__(*snake_case ,**snake_case ) if ( isinstance(args[0] ,snake_case ) and all(isinstance(snake_case ,snake_case ) for el in args[0] ) and all(len(snake_case ) == 1 for res in result ) ): return [res[0] for res in result] return result def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=TruncationStrategy.DO_NOT_TRUNCATE ,**snake_case ): '''simple docstring''' lowercase : Optional[Any] = self._parse_and_tokenize(snake_case ,truncation=snake_case ,**snake_case ) return inputs def _SCREAMING_SNAKE_CASE ( self ,snake_case ,**snake_case ): '''simple docstring''' if self.framework == "pt": lowercase , lowercase : Any = model_inputs["""input_ids"""].shape elif self.framework == "tf": lowercase , lowercase : Optional[Any] = tf.shape(model_inputs["""input_ids"""] ).numpy() lowercase : Union[str, Any] = generate_kwargs.get("""min_length""" ,self.model.config.min_length ) lowercase : Tuple = generate_kwargs.get("""max_length""" ,self.model.config.max_length ) self.check_inputs(snake_case ,generate_kwargs["""min_length"""] ,generate_kwargs["""max_length"""] ) lowercase : int = self.model.generate(**snake_case ,**snake_case ) lowercase : Union[str, Any] = output_ids.shape[0] if self.framework == "pt": lowercase : Any = output_ids.reshape(snake_case ,out_b // in_b ,*output_ids.shape[1:] ) elif self.framework == "tf": lowercase : List[Any] = tf.reshape(snake_case ,(in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=ReturnType.TEXT ,snake_case=False ): '''simple docstring''' lowercase : int = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: lowercase : Union[str, Any] = {f"{self.return_name}_token_ids": output_ids} elif return_type == ReturnType.TEXT: lowercase : Tuple = { f"{self.return_name}_text": self.tokenizer.decode( snake_case ,skip_special_tokens=snake_case ,clean_up_tokenization_spaces=snake_case ,) } records.append(snake_case ) return records @add_end_docstrings(lowerCAmelCase ) class __snake_case ( lowerCAmelCase ): _a : Optional[int]= "summary" def __call__( self ,*snake_case ,**snake_case ): '''simple docstring''' return super().__call__(*snake_case ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' if max_length < min_length: logger.warning(f"Your min_length={min_length} must be inferior than your max_length={max_length}." ) if input_length < max_length: logger.warning( f"Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is " """a summarization task, where outputs shorter than the input are typically wanted, you might """ f"consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})" ) @add_end_docstrings(lowerCAmelCase ) class __snake_case ( lowerCAmelCase ): _a : Tuple= "translation" def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' if input_length > 0.9 * max_length: logger.warning( f"Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider " """increasing your max_length manually, e.g. translator('...', max_length=400)""" ) return True def _SCREAMING_SNAKE_CASE ( self ,*snake_case ,snake_case=TruncationStrategy.DO_NOT_TRUNCATE ,snake_case=None ,snake_case=None ): '''simple docstring''' if getattr(self.tokenizer ,"""_build_translation_inputs""" ,snake_case ): return self.tokenizer._build_translation_inputs( *snake_case ,return_tensors=self.framework ,truncation=snake_case ,src_lang=snake_case ,tgt_lang=snake_case ) else: return super()._parse_and_tokenize(*snake_case ,truncation=snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case=None ,snake_case=None ,**snake_case ): '''simple docstring''' lowercase , lowercase , lowercase : List[Any] = super()._sanitize_parameters(**snake_case ) if src_lang is not None: lowercase : int = src_lang if tgt_lang is not None: lowercase : str = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. lowercase : List[str] = kwargs.get("""task""" ,self.task ) lowercase : Tuple = task.split("""_""" ) if task and len(snake_case ) == 4: # translation, XX, to YY lowercase : Any = items[1] lowercase : List[str] = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self ,*snake_case ,**snake_case ): '''simple docstring''' return super().__call__(*snake_case ,**snake_case )
20
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = 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(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class _lowerCamelCase( unittest.TestCase ): lowercase_ : Optional[Any] = ViTImageProcessor if is_vision_available() else None @property def UpperCamelCase ( self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : int = (3, 32, 1_28) _lowercase : str = tempfile.mkdtemp() # fmt: off _lowercase : Tuple = ['[GO]', '[s]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # fmt: on _lowercase : Optional[Any] = dict(zip(lowerCamelCase, range(len(lowerCamelCase)))) _lowercase : Union[str, Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['vocab_file']) with open(self.vocab_file, 'w', encoding='utf-8') as fp: fp.write(json.dumps(lowerCamelCase) + '\n') _lowercase : List[Any] = { 'do_normalize': False, 'do_resize': True, 'image_processor_type': 'ViTImageProcessor', 'resample': 3, 'size': {'height': 32, 'width': 1_28}, } _lowercase : Any = os.path.join(self.tmpdirname, lowerCamelCase) with open(self.image_processor_file, 'w', encoding='utf-8') as fp: json.dump(lowerCamelCase, lowerCamelCase) def UpperCamelCase ( self, **lowerCamelCase) -> int: """simple docstring""" return MgpstrTokenizer.from_pretrained(self.tmpdirname, **lowerCamelCase) def UpperCamelCase ( self, **lowerCamelCase) -> Optional[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname, **lowerCamelCase) def UpperCamelCase ( self) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname) def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : List[str] = np.random.randint(2_55, size=(3, 30, 4_00), dtype=np.uinta) _lowercase : Union[str, Any] = Image.fromarray(np.moveaxis(lowerCamelCase, 0, -1)) return image_input def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : int = self.get_tokenizer() _lowercase : Any = self.get_image_processor() _lowercase : Any = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) processor.save_pretrained(self.tmpdirname) _lowercase : Optional[int] = MgpstrProcessor.from_pretrained(self.tmpdirname, use_fast=lowerCamelCase) self.assertEqual(processor.char_tokenizer.get_vocab(), tokenizer.get_vocab()) self.assertIsInstance(processor.char_tokenizer, lowerCamelCase) self.assertEqual(processor.image_processor.to_json_string(), image_processor.to_json_string()) self.assertIsInstance(processor.image_processor, lowerCamelCase) def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" _lowercase : str = self.get_tokenizer() _lowercase : Any = self.get_image_processor() _lowercase : str = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) processor.save_pretrained(self.tmpdirname) _lowercase : List[str] = self.get_tokenizer(bos_token='(BOS)', eos_token='(EOS)') _lowercase : Optional[int] = self.get_image_processor(do_normalize=lowerCamelCase, padding_value=1.0) _lowercase : Dict = MgpstrProcessor.from_pretrained( self.tmpdirname, bos_token='(BOS)', eos_token='(EOS)', do_normalize=lowerCamelCase, padding_value=1.0) self.assertEqual(processor.char_tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.char_tokenizer, lowerCamelCase) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor, lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : int = self.get_image_processor() _lowercase : List[Any] = self.get_tokenizer() _lowercase : Dict = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) _lowercase : Any = self.prepare_image_inputs() _lowercase : str = image_processor(lowerCamelCase, return_tensors='np') _lowercase : Optional[Any] = processor(images=lowerCamelCase, return_tensors='np') for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum(), input_processor[key].sum(), delta=1E-2) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Dict = self.get_image_processor() _lowercase : List[Any] = self.get_tokenizer() _lowercase : Dict = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) _lowercase : Tuple = 'test' _lowercase : List[str] = processor(text=lowerCamelCase) _lowercase : List[str] = tokenizer(lowerCamelCase) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key], encoded_processor[key]) def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : int = self.get_image_processor() _lowercase : List[Any] = self.get_tokenizer() _lowercase : List[Any] = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) _lowercase : Optional[Any] = 'test' _lowercase : List[Any] = self.prepare_image_inputs() _lowercase : Any = processor(text=lowerCamelCase, images=lowerCamelCase) self.assertListEqual(list(inputs.keys()), ['pixel_values', 'labels']) # test if it raises when no input is passed with pytest.raises(lowerCamelCase): processor() def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Optional[int] = self.get_image_processor() _lowercase : int = self.get_tokenizer() _lowercase : Optional[int] = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) _lowercase : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] _lowercase : Dict = processor.char_decode(lowerCamelCase) _lowercase : List[str] = tokenizer.batch_decode(lowerCamelCase) _lowercase : Dict = [seq.replace(' ', '') for seq in decoded_tok] self.assertListEqual(lowerCamelCase, lowerCamelCase) def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Union[str, Any] = self.get_image_processor() _lowercase : Optional[Any] = self.get_tokenizer() _lowercase : Union[str, Any] = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) _lowercase : Dict = None _lowercase : Dict = self.prepare_image_inputs() _lowercase : int = processor(text=lowerCamelCase, images=lowerCamelCase) self.assertListEqual(list(inputs.keys()), processor.model_input_names) def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : Dict = self.get_image_processor() _lowercase : Optional[Any] = self.get_tokenizer() _lowercase : List[str] = MgpstrProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase) _lowercase : str = torch.randn(1, 27, 38) _lowercase : List[Any] = torch.randn(1, 27, 5_02_57) _lowercase : List[Any] = torch.randn(1, 27, 3_05_22) _lowercase : List[str] = processor.batch_decode([char_input, bpe_input, wp_input]) self.assertListEqual(list(results.keys()), ['generated_text', 'scores', 'char_preds', 'bpe_preds', 'wp_preds'])
21
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE :str = { '''configuration_time_series_transformer''': [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimeSeriesTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE :Optional[int] = [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TimeSeriesTransformerForPrediction''', '''TimeSeriesTransformerModel''', '''TimeSeriesTransformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE :List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
0
'''simple docstring''' from math import loga def snake_case_ ( _lowerCAmelCase : int ) -> int: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError('''Input value must be a \'int\' type''' ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
23
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
0
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process snake_case_ = logging.getLogger(__name__) snake_case_ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) snake_case_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class SCREAMING_SNAKE_CASE__ : A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(_UpperCAmelCase )} , ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) A_ : bool = field( default=_UpperCAmelCase , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) A_ : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A_ : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) def a (self : Tuple ): """simple docstring""" if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( '''--config_overrides can\'t be used in combination with --config_name or --model_name_or_path''' ) @dataclass class SCREAMING_SNAKE_CASE__ : A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) A_ : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'The input training data file (a text file).'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input train ref data file for whole word masking in Chinese.'} , ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input validation ref data file for whole word masking in Chinese.'} , ) A_ : bool = field( default=_UpperCAmelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) A_ : Optional[int] = field( default=5 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) A_ : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated. Default to the max input length of the model.' ) } , ) A_ : Optional[int] = field( default=_UpperCAmelCase , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) A_ : float = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) A_ : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Whether to pad all samples to `max_seq_length`. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch.' ) } , ) def a (self : int ): """simple docstring""" if self.train_file is not None: __snake_case = self.train_file.split('''.''' )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: __snake_case = self.validation_file.split('''.''' )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def lowerCamelCase__ ( snake_case_ : Optional[int] , snake_case_ : int ) -> Optional[Any]: with open(snake_case_ , '''r''' , encoding='''utf-8''' ) as f: __snake_case = [json.loads(snake_case_ ) for line in f.read().splitlines() if (len(snake_case_ ) > 0 and not line.isspace())] assert len(snake_case_ ) == len(snake_case_ ) __snake_case = {c: dataset[c] for c in dataset.column_names} __snake_case = refs return Dataset.from_dict(snake_case_ ) def lowerCamelCase__ ( ) -> List[str]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __snake_case , __snake_case , __snake_case = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case , __snake_case , __snake_case = parser.parse_args_into_dataclasses() # Detecting last checkpoint. __snake_case = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __snake_case = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , snake_case_ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. __snake_case = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): __snake_case = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""train[:{data_args.validation_split_percentage}%]""" , ) __snake_case = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""train[{data_args.validation_split_percentage}%:]""" , ) else: __snake_case = {} if data_args.train_file is not None: __snake_case = data_args.train_file if data_args.validation_file is not None: __snake_case = data_args.validation_file __snake_case = data_args.train_file.split('''.''' )[-1] if extension == "txt": __snake_case = '''text''' __snake_case = load_dataset(snake_case_ , data_files=snake_case_ ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __snake_case = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: __snake_case = AutoConfig.from_pretrained(model_args.config_name , **snake_case_ ) elif model_args.model_name_or_path: __snake_case = AutoConfig.from_pretrained(model_args.model_name_or_path , **snake_case_ ) else: __snake_case = CONFIG_MAPPING[model_args.model_type]() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(f"""New config: {config}""" ) __snake_case = { '''cache_dir''': model_args.cache_dir, '''use_fast''': model_args.use_fast_tokenizer, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.tokenizer_name: __snake_case = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **snake_case_ ) elif model_args.model_name_or_path: __snake_case = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **snake_case_ ) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) if model_args.model_name_or_path: __snake_case = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) __snake_case = AutoModelForMaskedLM.from_config(snake_case_ ) model.resize_token_embeddings(len(snake_case_ ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: __snake_case = datasets['''train'''].column_names else: __snake_case = datasets['''validation'''].column_names __snake_case = '''text''' if '''text''' in column_names else column_names[0] __snake_case = '''max_length''' if data_args.pad_to_max_length else False def tokenize_function(snake_case_ : Any ): # Remove empty lines __snake_case = [line for line in examples['''text'''] if len(snake_case_ ) > 0 and not line.isspace()] return tokenizer(examples['''text'''] , padding=snake_case_ , truncation=snake_case_ , max_length=data_args.max_seq_length ) __snake_case = datasets.map( snake_case_ , batched=snake_case_ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: __snake_case = add_chinese_references(tokenized_datasets['''train'''] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: __snake_case = add_chinese_references( tokenized_datasets['''validation'''] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer __snake_case = data_args.train_ref_file or data_args.validation_ref_file if has_ref: __snake_case = False # Data collator # This one will take care of randomly masking the tokens. __snake_case = DataCollatorForWholeWordMask(tokenizer=snake_case_ , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer __snake_case = Trainer( model=snake_case_ , args=snake_case_ , train_dataset=tokenized_datasets['''train'''] if training_args.do_train else None , eval_dataset=tokenized_datasets['''validation'''] if training_args.do_eval else None , tokenizer=snake_case_ , data_collator=snake_case_ , ) # Training if training_args.do_train: if last_checkpoint is not None: __snake_case = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): __snake_case = model_args.model_name_or_path else: __snake_case = None __snake_case = trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() # Saves the tokenizer too for easy upload __snake_case = os.path.join(training_args.output_dir , '''train_results.txt''' ) if trainer.is_world_process_zero(): with open(snake_case_ , '''w''' ) as writer: logger.info('''***** Train results *****''' ) for key, value in sorted(train_result.metrics.items() ): logger.info(f""" {key} = {value}""" ) writer.write(f"""{key} = {value}\n""" ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # Evaluation __snake_case = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __snake_case = trainer.evaluate() __snake_case = math.exp(eval_output['''eval_loss'''] ) __snake_case = perplexity __snake_case = os.path.join(training_args.output_dir , '''eval_results_mlm_wwm.txt''' ) if trainer.is_world_process_zero(): with open(snake_case_ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in sorted(results.items() ): logger.info(f""" {key} = {value}""" ) writer.write(f"""{key} = {value}\n""" ) return results def lowerCamelCase__ ( snake_case_ : int ) -> Optional[int]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
24
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
0
"""simple docstring""" import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback from torch import nn from torch.utils.data import DataLoader from transformers import MBartTokenizer, TaForConditionalGeneration from transformers.models.bart.modeling_bart import shift_tokens_right from utils import ( ROUGE_KEYS, LegacySeqaSeqDataset, SeqaSeqDataset, assert_all_frozen, calculate_bleu, calculate_rouge, check_output_dir, flatten_list, freeze_embeds, freeze_params, get_git_info, label_smoothed_nll_loss, lmap, pickle_save, save_git_info, save_json, use_task_specific_params, ) # need the parent dir module sys.path.insert(2, str(Path(__file__).resolve().parents[1])) from lightning_base import BaseTransformer, add_generic_args, generic_train # noqa UpperCAmelCase__ : Any = logging.getLogger(__name__) class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : int = '''summarization''' __UpperCamelCase : Tuple = ['''loss'''] __UpperCamelCase : List[Any] = ROUGE_KEYS __UpperCamelCase : Union[str, Any] = '''rouge2''' def __init__(self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> List[str]: """simple docstring""" if hparams.sortish_sampler and hparams.gpus > 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = False elif hparams.max_tokens_per_batch is not None: if hparams.gpus > 1: raise NotImplementedError("""Dynamic Batch size does not work for multi-gpu training""" ) if hparams.sortish_sampler: raise ValueError("""--sortish_sampler and --max_tokens_per_batch may not be used simultaneously""" ) super().__init__(SCREAMING_SNAKE_CASE__ , num_labels=SCREAMING_SNAKE_CASE__ , mode=self.mode , **SCREAMING_SNAKE_CASE__ ) use_task_specific_params(self.model , """summarization""" ) save_git_info(self.hparams.output_dir ) SCREAMING_SNAKE_CASE__ : int = Path(self.output_dir ) / """metrics.json""" SCREAMING_SNAKE_CASE__ : List[str] = Path(self.output_dir ) / """hparams.pkl""" pickle_save(self.hparams , self.hparams_save_path ) SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = defaultdict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = self.config.model_type SCREAMING_SNAKE_CASE__ : int = self.config.tgt_vocab_size if self.model_type == """fsmt""" else self.config.vocab_size SCREAMING_SNAKE_CASE__ : dict = { "data_dir": self.hparams.data_dir, "max_source_length": self.hparams.max_source_length, "prefix": self.model.config.prefix or "", } SCREAMING_SNAKE_CASE__ : Tuple = { """train""": self.hparams.n_train, """val""": self.hparams.n_val, """test""": self.hparams.n_test, } SCREAMING_SNAKE_CASE__ : Union[str, Any] = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()} SCREAMING_SNAKE_CASE__ : int = { """train""": self.hparams.max_target_length, """val""": self.hparams.val_max_target_length, """test""": self.hparams.test_max_target_length, } assert self.target_lens["train"] <= self.target_lens["val"], F'''target_lens: {self.target_lens}''' assert self.target_lens["train"] <= self.target_lens["test"], F'''target_lens: {self.target_lens}''' if self.hparams.freeze_embeds: freeze_embeds(self.model ) if self.hparams.freeze_encoder: freeze_params(self.model.get_encoder() ) assert_all_frozen(self.model.get_encoder() ) SCREAMING_SNAKE_CASE__ : Optional[Any] = get_git_info()["""repo_sha"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = hparams.num_workers SCREAMING_SNAKE_CASE__ : Tuple = None # default to config if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer.lang_code_to_id[hparams.tgt_lang] SCREAMING_SNAKE_CASE__ : Dict = self.decoder_start_token_id SCREAMING_SNAKE_CASE__ : Tuple = ( SeqaSeqDataset if hasattr(self.tokenizer , """prepare_seq2seq_batch""" ) else LegacySeqaSeqDataset ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = False SCREAMING_SNAKE_CASE__ : Optional[int] = self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams if self.hparams.eval_max_gen_length is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.hparams.eval_max_gen_length else: SCREAMING_SNAKE_CASE__ : int = self.model.config.max_length SCREAMING_SNAKE_CASE__ : Dict = self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Dict[str, List[str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = { k: self.tokenizer.batch_decode(v.tolist() ) if """mask""" not in k else v.shape for k, v in batch.items() } save_json(SCREAMING_SNAKE_CASE__ , Path(self.output_dir ) / """text_batch.json""" ) save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir ) / """tok_batch.json""" ) SCREAMING_SNAKE_CASE__ : int = True return readable_batch def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" return self.model(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.tokenizer.batch_decode( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return lmap(str.strip , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer.pad_token_id SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch["""input_ids"""], batch["""attention_mask"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = batch["""labels"""] if isinstance(self.model , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model._shift_right(SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = shift_tokens_right(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not self.already_saved_batch: # This would be slightly better if it only happened on rank zero SCREAMING_SNAKE_CASE__ : Tuple = decoder_input_ids self.save_readable_batch(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = self(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , decoder_input_ids=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs["""logits"""] if self.hparams.label_smoothing == 0: # Same behavior as modeling_bart.py, besides ignoring pad_token_id SCREAMING_SNAKE_CASE__ : Any = nn.CrossEntropyLoss(ignore_index=SCREAMING_SNAKE_CASE__ ) assert lm_logits.shape[-1] == self.vocab_size SCREAMING_SNAKE_CASE__ : int = ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1] ) , tgt_ids.view(-1 ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = nn.functional.log_softmax(SCREAMING_SNAKE_CASE__ , dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = label_smoothed_nll_loss( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.hparams.label_smoothing , ignore_index=SCREAMING_SNAKE_CASE__ ) return (loss,) @property def __magic_name__ (self ) -> int: """simple docstring""" return self.tokenizer.pad_token_id def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self._step(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = dict(zip(self.loss_names , SCREAMING_SNAKE_CASE__ ) ) # tokens per batch SCREAMING_SNAKE_CASE__ : List[Any] = batch["""input_ids"""].ne(self.pad ).sum() + batch["""labels"""].ne(self.pad ).sum() SCREAMING_SNAKE_CASE__ : str = batch["""input_ids"""].shape[0] SCREAMING_SNAKE_CASE__ : List[str] = batch["""input_ids"""].eq(self.pad ).sum() SCREAMING_SNAKE_CASE__ : List[Any] = batch["""input_ids"""].eq(self.pad ).float().mean() # TODO(SS): make a wandb summary metric for this return {"loss": loss_tensors[0], "log": logs} def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" return self._generative_step(SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="val" ) -> Dict: """simple docstring""" self.step_count += 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = {k: torch.stack([x[k] for x in outputs] ).mean() for k in self.loss_names} SCREAMING_SNAKE_CASE__ : Tuple = losses["""loss"""] SCREAMING_SNAKE_CASE__ : List[str] = { k: np.array([x[k] for x in outputs] ).mean() for k in self.metric_names + ["""gen_time""", """gen_len"""] } SCREAMING_SNAKE_CASE__ : Tuple = ( generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric] ) SCREAMING_SNAKE_CASE__ : torch.FloatTensor = torch.tensor(SCREAMING_SNAKE_CASE__ ).type_as(SCREAMING_SNAKE_CASE__ ) generative_metrics.update({k: v.item() for k, v in losses.items()} ) losses.update(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = {F'''{prefix}_avg_{k}''': x for k, x in losses.items()} SCREAMING_SNAKE_CASE__ : Tuple = self.step_count self.metrics[prefix].append(SCREAMING_SNAKE_CASE__ ) # callback writes this to self.metrics_save_path SCREAMING_SNAKE_CASE__ : int = flatten_list([x["""preds"""] for x in outputs] ) return { "log": all_metrics, "preds": preds, F'''{prefix}_loss''': loss, F'''{prefix}_{self.val_metric}''': metric_tensor, } def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" return calculate_rouge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = time.time() # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens') SCREAMING_SNAKE_CASE__ : int = self.model.generate( batch["""input_ids"""] , attention_mask=batch["""attention_mask"""] , use_cache=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = (time.time() - ta) / batch["""input_ids"""].shape[0] SCREAMING_SNAKE_CASE__ : List[str] = self.ids_to_clean_text(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[str] = self.ids_to_clean_text(batch["""labels"""] ) SCREAMING_SNAKE_CASE__ : str = self._step(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dict(zip(self.loss_names , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : Dict = self.calc_generative_metrics(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = np.mean(lmap(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) base_metrics.update(gen_time=SCREAMING_SNAKE_CASE__ , gen_len=SCREAMING_SNAKE_CASE__ , preds=SCREAMING_SNAKE_CASE__ , target=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return base_metrics def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" return self._generative_step(SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" return self.validation_epoch_end(SCREAMING_SNAKE_CASE__ , prefix="""test""" ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> SeqaSeqDataset: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.n_obs[type_path] SCREAMING_SNAKE_CASE__ : Tuple = self.target_lens[type_path] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dataset_class( self.tokenizer , type_path=SCREAMING_SNAKE_CASE__ , n_obs=SCREAMING_SNAKE_CASE__ , max_target_length=SCREAMING_SNAKE_CASE__ , **self.dataset_kwargs , ) return dataset def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False ) -> DataLoader: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dataset(SCREAMING_SNAKE_CASE__ ) if self.hparams.sortish_sampler and type_path != "test" and type_path != "val": SCREAMING_SNAKE_CASE__ : Tuple = dataset.make_sortish_sampler(SCREAMING_SNAKE_CASE__ , distributed=self.hparams.gpus > 1 ) return DataLoader( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , collate_fn=dataset.collate_fn , shuffle=SCREAMING_SNAKE_CASE__ , num_workers=self.num_workers , sampler=SCREAMING_SNAKE_CASE__ , ) elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val": SCREAMING_SNAKE_CASE__ : List[Any] = dataset.make_dynamic_sampler( self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1 ) return DataLoader( SCREAMING_SNAKE_CASE__ , batch_sampler=SCREAMING_SNAKE_CASE__ , collate_fn=dataset.collate_fn , num_workers=self.num_workers , ) else: return DataLoader( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , collate_fn=dataset.collate_fn , shuffle=SCREAMING_SNAKE_CASE__ , num_workers=self.num_workers , sampler=SCREAMING_SNAKE_CASE__ , ) def __magic_name__ (self ) -> DataLoader: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dataloader("""train""" , batch_size=self.hparams.train_batch_size , shuffle=SCREAMING_SNAKE_CASE__ ) return dataloader def __magic_name__ (self ) -> DataLoader: """simple docstring""" return self.get_dataloader("""val""" , batch_size=self.hparams.eval_batch_size ) def __magic_name__ (self ) -> DataLoader: """simple docstring""" return self.get_dataloader("""test""" , batch_size=self.hparams.eval_batch_size ) @staticmethod def __magic_name__ (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" BaseTransformer.add_model_specific_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) add_generic_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) parser.add_argument( """--max_source_length""" , default=10_24 , type=SCREAMING_SNAKE_CASE__ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--max_target_length""" , default=56 , type=SCREAMING_SNAKE_CASE__ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--val_max_target_length""" , default=1_42 , type=SCREAMING_SNAKE_CASE__ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--test_max_target_length""" , default=1_42 , type=SCREAMING_SNAKE_CASE__ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument("""--freeze_encoder""" , action="""store_true""" ) parser.add_argument("""--freeze_embeds""" , action="""store_true""" ) parser.add_argument("""--sortish_sampler""" , action="""store_true""" , default=SCREAMING_SNAKE_CASE__ ) parser.add_argument("""--overwrite_output_dir""" , action="""store_true""" , default=SCREAMING_SNAKE_CASE__ ) parser.add_argument("""--max_tokens_per_batch""" , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ ) parser.add_argument("""--logger_name""" , type=SCREAMING_SNAKE_CASE__ , choices=["""default""", """wandb""", """wandb_shared"""] , default="""default""" ) parser.add_argument("""--n_train""" , type=SCREAMING_SNAKE_CASE__ , default=-1 , required=SCREAMING_SNAKE_CASE__ , help="""# examples. -1 means use all.""" ) parser.add_argument("""--n_val""" , type=SCREAMING_SNAKE_CASE__ , default=5_00 , required=SCREAMING_SNAKE_CASE__ , help="""# examples. -1 means use all.""" ) parser.add_argument("""--n_test""" , type=SCREAMING_SNAKE_CASE__ , default=-1 , required=SCREAMING_SNAKE_CASE__ , help="""# examples. -1 means use all.""" ) parser.add_argument( """--task""" , type=SCREAMING_SNAKE_CASE__ , default="""summarization""" , required=SCREAMING_SNAKE_CASE__ , help="""# examples. -1 means use all.""" ) parser.add_argument("""--label_smoothing""" , type=SCREAMING_SNAKE_CASE__ , default=0.0 , required=SCREAMING_SNAKE_CASE__ ) parser.add_argument("""--src_lang""" , type=SCREAMING_SNAKE_CASE__ , default="""""" , required=SCREAMING_SNAKE_CASE__ ) parser.add_argument("""--tgt_lang""" , type=SCREAMING_SNAKE_CASE__ , default="""""" , required=SCREAMING_SNAKE_CASE__ ) parser.add_argument("""--eval_beams""" , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ ) parser.add_argument( """--val_metric""" , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , choices=["""bleu""", """rouge2""", """loss""", None] ) parser.add_argument("""--eval_max_gen_length""" , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , help="""never generate more than n tokens""" ) parser.add_argument("""--save_top_k""" , type=SCREAMING_SNAKE_CASE__ , default=1 , required=SCREAMING_SNAKE_CASE__ , help="""How many checkpoints to save""" ) parser.add_argument( """--early_stopping_patience""" , type=SCREAMING_SNAKE_CASE__ , default=-1 , required=SCREAMING_SNAKE_CASE__ , help=( """-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So""" """ val_check_interval will effect it.""" ) , ) return parser class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : Optional[Any] = '''translation''' __UpperCamelCase : List[Any] = ['''loss'''] __UpperCamelCase : Optional[Any] = ['''bleu'''] __UpperCamelCase : Dict = '''bleu''' def __init__(self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = hparams.src_lang SCREAMING_SNAKE_CASE__ : Optional[Any] = hparams.tgt_lang def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> dict: """simple docstring""" return calculate_bleu(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowercase_ ( _snake_case ,_snake_case=None ): Path(args.output_dir ).mkdir(exist_ok=_snake_case ) check_output_dir(_snake_case ,expected_items=3 ) if model is None: if "summarization" in args.task: SCREAMING_SNAKE_CASE__ : SummarizationModule = SummarizationModule(_snake_case ) else: SCREAMING_SNAKE_CASE__ : SummarizationModule = TranslationModule(_snake_case ) SCREAMING_SNAKE_CASE__ : Tuple = Path(args.data_dir ).name if ( args.logger_name == "default" or args.fast_dev_run or str(args.output_dir ).startswith("""/tmp""" ) or str(args.output_dir ).startswith("""/var""" ) ): SCREAMING_SNAKE_CASE__ : int = True # don't pollute wandb logs unnecessarily elif args.logger_name == "wandb": from pytorch_lightning.loggers import WandbLogger SCREAMING_SNAKE_CASE__ : Dict = os.environ.get("""WANDB_PROJECT""" ,_snake_case ) SCREAMING_SNAKE_CASE__ : Optional[int] = WandbLogger(name=model.output_dir.name ,project=_snake_case ) elif args.logger_name == "wandb_shared": from pytorch_lightning.loggers import WandbLogger SCREAMING_SNAKE_CASE__ : List[Any] = WandbLogger(name=model.output_dir.name ,project=f'''hf_{dataset}''' ) if args.early_stopping_patience >= 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_early_stopping_callback(model.val_metric ,args.early_stopping_patience ) else: SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = args.val_metric == """loss""" SCREAMING_SNAKE_CASE__ : pl.Trainer = generic_train( _snake_case ,_snake_case ,logging_callback=SeqaSeqLoggingCallback() ,checkpoint_callback=get_checkpoint_callback( args.output_dir ,model.val_metric ,args.save_top_k ,_snake_case ) ,early_stopping_callback=_snake_case ,logger=_snake_case ,) pickle_save(model.hparams ,model.output_dir / """hparams.pkl""" ) if not args.do_predict: return model SCREAMING_SNAKE_CASE__ : Dict = """""" SCREAMING_SNAKE_CASE__ : List[Any] = sorted(glob.glob(os.path.join(args.output_dir ,"""*.ckpt""" ) ,recursive=_snake_case ) ) if checkpoints: SCREAMING_SNAKE_CASE__ : Optional[Any] = checkpoints[-1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = checkpoints[-1] trainer.logger.log_hyperparams(model.hparams ) # test() without a model tests using the best checkpoint automatically trainer.test() return model if __name__ == "__main__": UpperCAmelCase__ : Tuple = argparse.ArgumentParser() UpperCAmelCase__ : Optional[int] = pl.Trainer.add_argparse_args(parser) UpperCAmelCase__ : int = SummarizationModule.add_model_specific_args(parser, os.getcwd()) UpperCAmelCase__ : List[str] = parser.parse_args() main(args)
25
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __SCREAMING_SNAKE_CASE : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : int = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = tabu_search( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": _lowercase : Any = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
93
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "CLIPImageProcessor" _a = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self , _a=None , _a=None , **_a ) -> Dict: _A : Any = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _a , ) _A : Union[str, Any] = kwargs.pop("""feature_extractor""" ) _A : Optional[int] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(_a , _a ) def __call__( self , _a=None , _a=None , _a=None , **_a ) -> int: if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: _A : List[str] = self.tokenizer(_a , return_tensors=_a , **_a ) if images is not None: _A : Dict = self.image_processor(_a , return_tensors=_a , **_a ) if text is not None and images is not None: _A : Tuple = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_a ) , tensor_type=_a ) def a__ ( self , *_a , **_a ) -> List[Any]: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> Any: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> List[Any]: _A : Union[str, Any] = self.tokenizer.model_input_names _A : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def a__ ( self ) -> List[str]: warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _a , ) return self.image_processor_class @property def a__ ( self ) -> List[Any]: warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , _a , ) return self.image_processor
26
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowercase : int = logging.get_logger(__name__) __lowercase : Optional[Any] = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "roberta-prelayernorm" def __init__( self , __a=5_0265 , __a=768 , __a=12 , __a=12 , __a=3072 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=2 , __a=0.02 , __a=1E-1_2 , __a=1 , __a=0 , __a=2 , __a="absolute" , __a=True , __a=None , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __a : Optional[Any] = vocab_size __a : str = hidden_size __a : int = num_hidden_layers __a : Union[str, Any] = num_attention_heads __a : Any = hidden_act __a : Union[str, Any] = intermediate_size __a : int = hidden_dropout_prob __a : Optional[int] = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : str = type_vocab_size __a : Tuple = initializer_range __a : Any = layer_norm_eps __a : List[str] = position_embedding_type __a : str = use_cache __a : str = classifier_dropout class __UpperCamelCase ( lowerCAmelCase_ ): @property def __UpperCAmelCase ( self ): '''simple docstring''' if self.task == "multiple-choice": __a : List[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Any = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
27
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
0
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
28
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
0
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __UpperCAmelCase = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582' } def lowercase__ ( __snake_case : str = "dhaka" , __snake_case : int = 5 ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = min(__snake_case , 50 ) # Prevent abuse! UpperCAmelCase_ : Dict = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } UpperCAmelCase_ : Any = requests.get('https://www.google.com/search' , params=__snake_case , headers=__snake_case ) UpperCAmelCase_ : Dict = BeautifulSoup(html.text , 'html.parser' ) UpperCAmelCase_ : Any = ''.join( re.findall(R'AF_initDataCallback\(([^<]+)\);' , str(soup.select('script' ) ) ) ) UpperCAmelCase_ : int = json.dumps(__snake_case ) UpperCAmelCase_ : List[Any] = json.loads(__snake_case ) UpperCAmelCase_ : Union[str, Any] = re.findall( R'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",' , __snake_case , ) if not matched_google_image_data: return 0 UpperCAmelCase_ : Union[str, Any] = re.sub( R'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]' , '' , str(__snake_case ) , ) UpperCAmelCase_ : Optional[int] = re.findall( R'(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]' , __snake_case , ) for index, fixed_full_res_image in enumerate(__snake_case ): if index >= max_images: return index UpperCAmelCase_ : Optional[int] = bytes(__snake_case , 'ascii' ).decode( 'unicode-escape' ) UpperCAmelCase_ : Union[str, Any] = bytes(__snake_case , 'ascii' ).decode( 'unicode-escape' ) UpperCAmelCase_ : Union[str, Any] = urllib.request.build_opener() UpperCAmelCase_ : Dict = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(__snake_case ) UpperCAmelCase_ : Union[str, Any] = F"query_{query.replace(' ' , '_' )}" if not os.path.exists(__snake_case ): os.makedirs(__snake_case ) urllib.request.urlretrieve( # noqa: S310 __snake_case , F"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: __UpperCAmelCase = download_images_from_google_query(sys.argv[1]) print(F'{image_count} images were downloaded to disk.') except IndexError: print('Please provide a search term.') raise
29
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
0
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters __a = logging.get_logger(__name__) def a ( snake_case__: Optional[int] , snake_case__: Dict , snake_case__: int , snake_case__: List[str]=None , snake_case__: List[Any]=None ): '''simple docstring''' # Recurse if needed if "." in tensor_name: lowercase_ = tensor_name.split('''.''' ) for split in splits[:-1]: lowercase_ = getattr(snake_case__ , snake_case__ ) if new_module is None: raise ValueError(F'''{module} has no attribute {split}.''' ) lowercase_ = new_module lowercase_ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F'''{module} does not have a parameter or a buffer named {tensor_name}.''' ) lowercase_ = tensor_name in module._buffers lowercase_ = getattr(snake_case__ , snake_case__ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(F'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''' ) lowercase_ = False lowercase_ = False if is_buffer or not is_bitsandbytes_available(): lowercase_ = False lowercase_ = False else: lowercase_ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) lowercase_ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: lowercase_ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: lowercase_ = old_value.to(snake_case__ ) elif isinstance(snake_case__ , torch.Tensor ): lowercase_ = value.to('''cpu''' ) if value.dtype == torch.inta: lowercase_ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: lowercase_ = torch.tensor(snake_case__ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , snake_case__ ) and fpaa_statistics is None: lowercase_ = new_value.T lowercase_ = old_value.__dict__ if is_abit: lowercase_ = bnb.nn.IntaParams(snake_case__ , requires_grad=snake_case__ , **snake_case__ ).to(snake_case__ ) elif is_abit: lowercase_ = bnb.nn.Paramsabit(snake_case__ , requires_grad=snake_case__ , **snake_case__ ).to(snake_case__ ) lowercase_ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(snake_case__ ) ) else: if value is None: lowercase_ = old_value.to(snake_case__ ) elif isinstance(snake_case__ , torch.Tensor ): lowercase_ = value.to(snake_case__ ) else: lowercase_ = torch.tensor(snake_case__ , device=snake_case__ ) if is_buffer: lowercase_ = new_value else: lowercase_ = nn.Parameter(snake_case__ , requires_grad=old_value.requires_grad ) lowercase_ = new_value def a ( snake_case__: str , snake_case__: Union[str, Any]=None , snake_case__: Any=None , snake_case__: List[str]=None , snake_case__: Optional[Any]=False ): '''simple docstring''' for name, module in model.named_children(): if current_key_name is None: lowercase_ = [] current_key_name.append(snake_case__ ) if (isinstance(snake_case__ , nn.Linear ) or isinstance(snake_case__ , snake_case__ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(snake_case__ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(snake_case__ , snake_case__ ): lowercase_ , lowercase_ = module.weight.shape else: lowercase_ = module.in_features lowercase_ = module.out_features if quantization_config.quantization_method() == "llm_int8": lowercase_ = bnb.nn.LinearabitLt( snake_case__ , snake_case__ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) lowercase_ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: lowercase_ = bnb.nn.Linearabit( snake_case__ , snake_case__ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) lowercase_ = True # Store the module class in case we need to transpose the weight later lowercase_ = type(snake_case__ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(snake_case__ ) if len(list(module.children() ) ) > 0: lowercase_ , lowercase_ = _replace_with_bnb_linear( snake_case__ , snake_case__ , snake_case__ , snake_case__ , has_been_replaced=snake_case__ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def a ( snake_case__: Any , snake_case__: Any=None , snake_case__: Union[str, Any]=None , snake_case__: str=None ): '''simple docstring''' lowercase_ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert lowercase_ , lowercase_ = _replace_with_bnb_linear( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def a ( *snake_case__: str , **snake_case__: Dict ): '''simple docstring''' warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , snake_case__ , ) return replace_with_bnb_linear(*snake_case__ , **snake_case__ ) def a ( *snake_case__: Any , **snake_case__: List[Any] ): '''simple docstring''' warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , snake_case__ , ) return set_module_quantized_tensor_to_device(*snake_case__ , **snake_case__ ) def a ( snake_case__: Optional[Any] ): '''simple docstring''' lowercase_ = deepcopy(snake_case__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() lowercase_ = find_tied_parameters(snake_case__ ) # For compatibility with Accelerate < 0.18 if isinstance(snake_case__ , snake_case__ ): lowercase_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowercase_ = sum(snake_case__ , [] ) lowercase_ = len(snake_case__ ) > 0 # Check if it is a base model lowercase_ = not hasattr(snake_case__ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowercase_ = list(model.named_children() ) lowercase_ = [list_modules[-1][0]] # add last module together with tied weights lowercase_ = set(snake_case__ ) - set(snake_case__ ) lowercase_ = list(set(snake_case__ ) ) + list(snake_case__ ) # remove ".weight" from the keys lowercase_ = ['''.weight''', '''.bias'''] lowercase_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowercase_ = name.replace(snake_case__ , '''''' ) filtered_module_names.append(snake_case__ ) return filtered_module_names
30
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCamelCase_ (snake_case__ ): '''simple docstring''' __UpperCamelCase: torch.FloatTensor class lowerCamelCase_ (snake_case__ , snake_case__ ): '''simple docstring''' @register_to_config def __init__( self : Union[str, Any] , A : int = 65536 , A : Optional[int] = None , A : int = 2 , A : int = 2 , A : int = 0 , A : str = "fourier" , A : bool = True , A : bool = False , A : float = 0.0 , A : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , A : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , A : Tuple[str] = "UNetMidBlock1D" , A : str = None , A : Tuple[int] = (32, 32, 64) , A : str = None , A : int = 8 , A : int = 1 , A : bool = False , ): super().__init__() _UpperCAmelCase : List[str] = sample_size # time if time_embedding_type == "fourier": _UpperCAmelCase : List[str] = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=A , log=A , flip_sin_to_cos=A ) _UpperCAmelCase : Union[str, Any] = 2 * block_out_channels[0] elif time_embedding_type == "positional": _UpperCAmelCase : Dict = Timesteps( block_out_channels[0] , flip_sin_to_cos=A , downscale_freq_shift=A ) _UpperCAmelCase : str = block_out_channels[0] if use_timestep_embedding: _UpperCAmelCase : List[str] = block_out_channels[0] * 4 _UpperCAmelCase : List[str] = TimestepEmbedding( in_channels=A , time_embed_dim=A , act_fn=A , out_dim=block_out_channels[0] , ) _UpperCAmelCase : Optional[int] = nn.ModuleList([] ) _UpperCAmelCase : Tuple = None _UpperCAmelCase : Optional[Any] = nn.ModuleList([] ) _UpperCAmelCase : str = None # down _UpperCAmelCase : Optional[int] = in_channels for i, down_block_type in enumerate(A ): _UpperCAmelCase : Union[str, Any] = output_channel _UpperCAmelCase : Tuple = block_out_channels[i] if i == 0: input_channel += extra_in_channels _UpperCAmelCase : str = i == len(A ) - 1 _UpperCAmelCase : Union[str, Any] = get_down_block( A , num_layers=A , in_channels=A , out_channels=A , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(A ) # mid _UpperCAmelCase : Optional[int] = get_mid_block( A , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=A , add_downsample=A , ) # up _UpperCAmelCase : int = list(reversed(A ) ) _UpperCAmelCase : Union[str, Any] = reversed_block_out_channels[0] if out_block_type is None: _UpperCAmelCase : Optional[Any] = out_channels else: _UpperCAmelCase : Any = block_out_channels[0] for i, up_block_type in enumerate(A ): _UpperCAmelCase : Dict = output_channel _UpperCAmelCase : int = ( reversed_block_out_channels[i + 1] if i < len(A ) - 1 else final_upsample_channels ) _UpperCAmelCase : Optional[Any] = i == len(A ) - 1 _UpperCAmelCase : Optional[Any] = get_up_block( A , num_layers=A , in_channels=A , out_channels=A , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(A ) _UpperCAmelCase : Tuple = output_channel # out _UpperCAmelCase : Optional[int] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) _UpperCAmelCase : List[str] = get_out_block( out_block_type=A , num_groups_out=A , embed_dim=block_out_channels[0] , out_channels=A , act_fn=A , fc_dim=block_out_channels[-1] // 4 , ) def _A ( self : Dict , A : torch.FloatTensor , A : Union[torch.Tensor, float, int] , A : bool = True , ): _UpperCAmelCase : List[Any] = timestep if not torch.is_tensor(A ): _UpperCAmelCase : Optional[int] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(A ) and len(timesteps.shape ) == 0: _UpperCAmelCase : Tuple = timesteps[None].to(sample.device ) _UpperCAmelCase : Dict = self.time_proj(A ) if self.config.use_timestep_embedding: _UpperCAmelCase : Union[str, Any] = self.time_mlp(A ) else: _UpperCAmelCase : str = timestep_embed[..., None] _UpperCAmelCase : Tuple = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) _UpperCAmelCase : List[Any] = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down _UpperCAmelCase : Dict = () for downsample_block in self.down_blocks: _UpperCAmelCase , _UpperCAmelCase : List[str] = downsample_block(hidden_states=A , temb=A ) down_block_res_samples += res_samples # 3. mid if self.mid_block: _UpperCAmelCase : Optional[int] = self.mid_block(A , A ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): _UpperCAmelCase : int = down_block_res_samples[-1:] _UpperCAmelCase : Optional[int] = down_block_res_samples[:-1] _UpperCAmelCase : Optional[Any] = upsample_block(A , res_hidden_states_tuple=A , temb=A ) # 5. post-process if self.out_block: _UpperCAmelCase : Optional[Any] = self.out_block(A , A ) if not return_dict: return (sample,) return UNetaDOutput(sample=A )
31
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
0
def SCREAMING_SNAKE_CASE_ ( __A : int = 10_00 ) -> int: """simple docstring""" return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
32
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Union[str, Any] = logging.get_logger(__name__) __A : int = { '''s-JoL/Open-Llama-V1''': '''https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json''', } class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : List[str] = "open-llama" def __init__( self : Dict , A : Optional[Any]=10_00_00 , A : Optional[int]=40_96 , A : Tuple=1_10_08 , A : List[Any]=32 , A : Optional[Any]=32 , A : List[str]="silu" , A : Optional[int]=20_48 , A : Dict=0.02 , A : Tuple=1e-6 , A : Optional[int]=True , A : Dict=0 , A : Any=1 , A : Optional[Any]=2 , A : Tuple=False , A : Dict=True , A : Dict=0.1 , A : int=0.1 , A : Optional[Any]=True , A : List[str]=True , A : int=None , **A : Optional[int] , ) -> int: lowercase_ : Tuple = vocab_size lowercase_ : Tuple = max_position_embeddings lowercase_ : int = hidden_size lowercase_ : Any = intermediate_size lowercase_ : Dict = num_hidden_layers lowercase_ : str = num_attention_heads lowercase_ : Optional[Any] = hidden_act lowercase_ : List[Any] = initializer_range lowercase_ : Optional[Any] = rms_norm_eps lowercase_ : List[str] = use_cache lowercase_ : Dict = kwargs.pop( '''use_memorry_efficient_attention''' , A ) lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Tuple = attention_dropout_prob lowercase_ : Tuple = use_stable_embedding lowercase_ : Optional[int] = shared_input_output_embedding lowercase_ : Optional[int] = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=A , bos_token_id=A , eos_token_id=A , tie_word_embeddings=A , **A , ) def A ( self : Optional[int] ) -> List[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , A ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F'''got {self.rope_scaling}''' ) lowercase_ : Any = self.rope_scaling.get('''type''' , A ) lowercase_ : int = self.rope_scaling.get('''factor''' , A ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(A , A ) or rope_scaling_factor <= 1.0: raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
33
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
0
'''simple docstring''' import os from distutils.util import strtobool def snake_case_ (_a : Union[str, Any] , _a : List[Any] ): for e in env_keys: UpperCAmelCase = int(os.environ.get(_a , -1 ) ) if val >= 0: return val return default def snake_case_ (_a : Dict , _a : Any=False ): UpperCAmelCase = os.environ.get(_a , str(_a ) ) return strtobool(_a ) == 1 # As its name indicates `strtobool` actually returns an int... def snake_case_ (_a : str , _a : Optional[Any]="no" ): UpperCAmelCase = os.environ.get(_a , str(_a ) ) return value
34
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
0
'''simple docstring''' from collections.abc import Sequence def __snake_case( _lowerCAmelCase , _lowerCAmelCase = False ) -> float: if not arr: return 0 snake_case__ : Optional[Any] = 0 if allow_empty_subarrays else float("""-inf""" ) snake_case__ : List[str] = 0.0 for num in arr: snake_case__ : Any = max(0 if allow_empty_subarrays else num , curr_sum + num ) snake_case__ : Optional[Any] = max(_lowerCAmelCase , _lowerCAmelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() __a = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F"{max_subarray_sum(nums) = }")
35
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _snake_case = { "configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "MEGA_PRETRAINED_MODEL_ARCHIVE_LIST", "MegaForCausalLM", "MegaForMaskedLM", "MegaForMultipleChoice", "MegaForQuestionAnswering", "MegaForSequenceClassification", "MegaForTokenClassification", "MegaModel", "MegaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
36
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = update_image_and_anno( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , filter_scale=__SCREAMING_SNAKE_CASE , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : int = F'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(__SCREAMING_SNAKE_CASE ) with open(F'''{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__SCREAMING_SNAKE_CASE ) labels.append(__SCREAMING_SNAKE_CASE ) return img_paths, labels def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : tuple[int, int] , __SCREAMING_SNAKE_CASE : tuple[float, float] , __SCREAMING_SNAKE_CASE : float = 0.0 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ 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 snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
0
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# _lowerCAmelCase = [ # (stable-diffusion, HF Diffusers) ('''time_embed.0.weight''', '''time_embedding.linear_1.weight'''), ('''time_embed.0.bias''', '''time_embedding.linear_1.bias'''), ('''time_embed.2.weight''', '''time_embedding.linear_2.weight'''), ('''time_embed.2.bias''', '''time_embedding.linear_2.bias'''), ('''input_blocks.0.0.weight''', '''conv_in.weight'''), ('''input_blocks.0.0.bias''', '''conv_in.bias'''), ('''out.0.weight''', '''conv_norm_out.weight'''), ('''out.0.bias''', '''conv_norm_out.bias'''), ('''out.2.weight''', '''conv_out.weight'''), ('''out.2.bias''', '''conv_out.bias'''), ] _lowerCAmelCase = [ # (stable-diffusion, HF Diffusers) ('''in_layers.0''', '''norm1'''), ('''in_layers.2''', '''conv1'''), ('''out_layers.0''', '''norm2'''), ('''out_layers.3''', '''conv2'''), ('''emb_layers.1''', '''time_emb_proj'''), ('''skip_connection''', '''conv_shortcut'''), ] _lowerCAmelCase = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks _lowerCAmelCase = F"""down_blocks.{i}.resnets.{j}.""" _lowerCAmelCase = F"""input_blocks.{3*i + j + 1}.0.""" unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 _lowerCAmelCase = F"""down_blocks.{i}.attentions.{j}.""" _lowerCAmelCase = F"""input_blocks.{3*i + j + 1}.1.""" unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks _lowerCAmelCase = F"""up_blocks.{i}.resnets.{j}.""" _lowerCAmelCase = F"""output_blocks.{3*i + j}.0.""" unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 _lowerCAmelCase = F"""up_blocks.{i}.attentions.{j}.""" _lowerCAmelCase = F"""output_blocks.{3*i + j}.1.""" unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 _lowerCAmelCase = F"""down_blocks.{i}.downsamplers.0.conv.""" _lowerCAmelCase = F"""input_blocks.{3*(i+1)}.0.op.""" unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 _lowerCAmelCase = F"""up_blocks.{i}.upsamplers.0.""" _lowerCAmelCase = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}.""" unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) _lowerCAmelCase = '''mid_block.attentions.0.''' _lowerCAmelCase = '''middle_block.1.''' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): _lowerCAmelCase = F"""mid_block.resnets.{j}.""" _lowerCAmelCase = F"""middle_block.{2*j}.""" unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Any = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: lowerCAmelCase__ : Optional[int] = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: lowerCAmelCase__ : Any = v.replace(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : List[Any] = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: lowerCAmelCase__ : List[Any] = v.replace(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = v lowerCAmelCase__ : Tuple = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# _lowerCAmelCase = [ # (stable-diffusion, HF Diffusers) ('''nin_shortcut''', '''conv_shortcut'''), ('''norm_out''', '''conv_norm_out'''), ('''mid.attn_1.''', '''mid_block.attentions.0.'''), ] for i in range(4): # down_blocks have two resnets for j in range(2): _lowerCAmelCase = F"""encoder.down_blocks.{i}.resnets.{j}.""" _lowerCAmelCase = F"""encoder.down.{i}.block.{j}.""" vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: _lowerCAmelCase = F"""down_blocks.{i}.downsamplers.0.""" _lowerCAmelCase = F"""down.{i}.downsample.""" vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) _lowerCAmelCase = F"""up_blocks.{i}.upsamplers.0.""" _lowerCAmelCase = F"""up.{3-i}.upsample.""" vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): _lowerCAmelCase = F"""decoder.up_blocks.{i}.resnets.{j}.""" _lowerCAmelCase = F"""decoder.up.{3-i}.block.{j}.""" vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): _lowerCAmelCase = F"""mid_block.resnets.{i}.""" _lowerCAmelCase = F"""mid.block_{i+1}.""" vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) _lowerCAmelCase = [ # (stable-diffusion, HF Diffusers) ('''norm.''', '''group_norm.'''), ('''q.''', '''query.'''), ('''k.''', '''key.'''), ('''v.''', '''value.'''), ('''proj_out.''', '''proj_attn.'''), ] def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" return w.reshape(*w.shape , 1 , 1 ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Optional[int] = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: lowerCAmelCase__ : str = v.replace(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: lowerCAmelCase__ : Dict = v.replace(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : List[Any] = v lowerCAmelCase__ : Union[str, Any] = {v: vae_state_dict[k] for k, v in mapping.items()} lowerCAmelCase__ : Tuple = ["""q""", """k""", """v""", """proj_out"""] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) lowerCAmelCase__ : Optional[int] = reshape_weight_for_sd(UpperCamelCase ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# _lowerCAmelCase = [ # (stable-diffusion, HF Diffusers) ('''resblocks.''', '''text_model.encoder.layers.'''), ('''ln_1''', '''layer_norm1'''), ('''ln_2''', '''layer_norm2'''), ('''.c_fc.''', '''.fc1.'''), ('''.c_proj.''', '''.fc2.'''), ('''.attn''', '''.self_attn'''), ('''ln_final.''', '''transformer.text_model.final_layer_norm.'''), ('''token_embedding.weight''', '''transformer.text_model.embeddings.token_embedding.weight'''), ('''positional_embedding''', '''transformer.text_model.embeddings.position_embedding.weight'''), ] _lowerCAmelCase = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} _lowerCAmelCase = re.compile('''|'''.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp _lowerCAmelCase = {'''q''': 0, '''k''': 1, '''v''': 2} def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Optional[Any] = {} lowerCAmelCase__ : int = {} lowerCAmelCase__ : List[Any] = {} for k, v in text_enc_dict.items(): if ( k.endswith(""".self_attn.q_proj.weight""" ) or k.endswith(""".self_attn.k_proj.weight""" ) or k.endswith(""".self_attn.v_proj.weight""" ) ): lowerCAmelCase__ : Optional[int] = k[: -len(""".q_proj.weight""" )] lowerCAmelCase__ : Tuple = k[-len("""q_proj.weight""" )] if k_pre not in capture_qkv_weight: lowerCAmelCase__ : List[Any] = [None, None, None] lowerCAmelCase__ : Dict = v continue if ( k.endswith(""".self_attn.q_proj.bias""" ) or k.endswith(""".self_attn.k_proj.bias""" ) or k.endswith(""".self_attn.v_proj.bias""" ) ): lowerCAmelCase__ : str = k[: -len(""".q_proj.bias""" )] lowerCAmelCase__ : List[str] = k[-len("""q_proj.bias""" )] if k_pre not in capture_qkv_bias: lowerCAmelCase__ : Union[str, Any] = [None, None, None] lowerCAmelCase__ : Any = v continue lowerCAmelCase__ : Dict = textenc_pattern.sub(lambda UpperCamelCase : protected[re.escape(m.group(0 ) )] , UpperCamelCase ) lowerCAmelCase__ : Union[str, Any] = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) lowerCAmelCase__ : Any = textenc_pattern.sub(lambda UpperCamelCase : protected[re.escape(m.group(0 ) )] , UpperCamelCase ) lowerCAmelCase__ : Tuple = torch.cat(UpperCamelCase ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) lowerCAmelCase__ : str = textenc_pattern.sub(lambda UpperCamelCase : protected[re.escape(m.group(0 ) )] , UpperCamelCase ) lowerCAmelCase__ : List[Any] = torch.cat(UpperCamelCase ) return new_state_dict def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" return text_enc_dict if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument('''--model_path''', default=None, type=str, required=True, help='''Path to the model to convert.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''') parser.add_argument( '''--use_safetensors''', action='''store_true''', help='''Save weights use safetensors, default is ckpt.''' ) _lowerCAmelCase = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors _lowerCAmelCase = osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.safetensors''') _lowerCAmelCase = osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.safetensors''') _lowerCAmelCase = osp.join(args.model_path, '''text_encoder''', '''model.safetensors''') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): _lowerCAmelCase = load_file(unet_path, device='''cpu''') else: _lowerCAmelCase = osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.bin''') _lowerCAmelCase = torch.load(unet_path, map_location='''cpu''') if osp.exists(vae_path): _lowerCAmelCase = load_file(vae_path, device='''cpu''') else: _lowerCAmelCase = osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.bin''') _lowerCAmelCase = torch.load(vae_path, map_location='''cpu''') if osp.exists(text_enc_path): _lowerCAmelCase = load_file(text_enc_path, device='''cpu''') else: _lowerCAmelCase = osp.join(args.model_path, '''text_encoder''', '''pytorch_model.bin''') _lowerCAmelCase = torch.load(text_enc_path, map_location='''cpu''') # Convert the UNet model _lowerCAmelCase = convert_unet_state_dict(unet_state_dict) _lowerCAmelCase = {'''model.diffusion_model.''' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model _lowerCAmelCase = convert_vae_state_dict(vae_state_dict) _lowerCAmelCase = {'''first_stage_model.''' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper _lowerCAmelCase = '''text_model.encoder.layers.22.layer_norm2.bias''' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm _lowerCAmelCase = {'''transformer.''' + k: v for k, v in text_enc_dict.items()} _lowerCAmelCase = convert_text_enc_state_dict_vaa(text_enc_dict) _lowerCAmelCase = {'''cond_stage_model.model.''' + k: v for k, v in text_enc_dict.items()} else: _lowerCAmelCase = convert_text_enc_state_dict(text_enc_dict) _lowerCAmelCase = {'''cond_stage_model.transformer.''' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint _lowerCAmelCase = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: _lowerCAmelCase = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: _lowerCAmelCase = {'''state_dict''': state_dict} torch.save(state_dict, args.checkpoint_path)
37
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
0
# 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
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
0
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() _a = { '''bart''': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''bert''': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-base-cased-finetuned-mrpc''': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''dpr''': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''gpt2''': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlnet''': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlm''': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlm-roberta''': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''transfo-xl''': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''openai-gpt''': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''roberta''': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''layoutlm''': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''roberta-large-mnli''': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''camembert''': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''flaubert''': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''distilbert''': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''distilbert-base-distilled-squad''': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''lxmert''': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''lxmert-visual-feature-encoder''': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''ctrl''': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''albert''': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''t5''': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''electra''': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''wav2vec2''': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False , __lowerCAmelCase=True )-> Optional[Any]: """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F"""Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.""" ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: _UpperCAmelCase = cached_file(__lowerCAmelCase , __lowerCAmelCase , force_download=not use_cached_models ) _UpperCAmelCase = config_class.from_json_file(__lowerCAmelCase ) _UpperCAmelCase = True _UpperCAmelCase = True print(F"""Building TensorFlow model from configuration: {config}""" ) _UpperCAmelCase = model_class(__lowerCAmelCase ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): _UpperCAmelCase = cached_file( __lowerCAmelCase , __lowerCAmelCase , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: _UpperCAmelCase = load_pytorch_checkpoint_in_tfa_model(__lowerCAmelCase , __lowerCAmelCase ) if compare_with_pt_model: _UpperCAmelCase = tf_model(tf_model.dummy_inputs , training=__lowerCAmelCase ) # build the network _UpperCAmelCase = torch.load(__lowerCAmelCase , map_location='cpu' ) _UpperCAmelCase = pt_model_class.from_pretrained( pretrained_model_name_or_path=__lowerCAmelCase , config=__lowerCAmelCase , state_dict=__lowerCAmelCase ) with torch.no_grad(): _UpperCAmelCase = pt_model(**pt_model.dummy_inputs ) _UpperCAmelCase = pto[0].numpy() _UpperCAmelCase = tfo[0].numpy() _UpperCAmelCase = np.amax(np.abs(np_pt - np_tf ) ) print(F"""Max absolute difference between models outputs {diff}""" ) assert diff <= 2E-2, F"""Error, model absolute difference is >2e-2: {diff}""" # Save pytorch-model print(F"""Save TensorFlow model to {tf_dump_path}""" ) tf_model.save_weights(__lowerCAmelCase , save_format='h5' ) def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=False , __lowerCAmelCase=False , __lowerCAmelCase=False , __lowerCAmelCase=False , )-> Tuple: """simple docstring""" if args_model_type is None: _UpperCAmelCase = list(MODEL_CLASSES.keys() ) else: _UpperCAmelCase = [args_model_type] for j, model_type in enumerate(__lowerCAmelCase , start=1 ): print('=' * 100 ) print(F""" Converting model type {j}/{len(__lowerCAmelCase )}: {model_type}""" ) print('=' * 100 ) if model_type not in MODEL_CLASSES: raise ValueError(F"""Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.""" ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: _UpperCAmelCase = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: _UpperCAmelCase = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(__lowerCAmelCase , __lowerCAmelCase ) , start=1 ): print('-' * 100 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F""" Skipping finetuned checkpoint {model_shortcut_name}""" ) continue _UpperCAmelCase = model_shortcut_name elif only_convert_finetuned_models: print(F""" Skipping not finetuned checkpoint {model_shortcut_name}""" ) continue print( F""" Converting checkpoint {i}/{len(__lowerCAmelCase )}: {model_shortcut_name} - model_type {model_type}""" ) print('-' * 100 ) if config_shortcut_name in aws_config_map: _UpperCAmelCase = cached_file(__lowerCAmelCase , __lowerCAmelCase , force_download=not use_cached_models ) else: _UpperCAmelCase = config_shortcut_name if model_shortcut_name in aws_model_maps: _UpperCAmelCase = cached_file(__lowerCAmelCase , __lowerCAmelCase , force_download=not use_cached_models ) else: _UpperCAmelCase = model_shortcut_name if os.path.isfile(__lowerCAmelCase ): _UpperCAmelCase = 'converted_model' convert_pt_checkpoint_to_tf( model_type=__lowerCAmelCase , pytorch_checkpoint_path=__lowerCAmelCase , config_file=__lowerCAmelCase , tf_dump_path=os.path.join(__lowerCAmelCase , model_shortcut_name + '-tf_model.h5' ) , compare_with_pt_model=__lowerCAmelCase , ) if remove_cached_files: os.remove(__lowerCAmelCase ) os.remove(__lowerCAmelCase ) if __name__ == "__main__": _a = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_dump_path''', default=None, type=str, required=True, help='''Path to the output Tensorflow dump file.''' ) parser.add_argument( '''--model_type''', default=None, type=str, help=( F'''Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and ''' '''convert all the models from AWS.''' ), ) parser.add_argument( '''--pytorch_checkpoint_path''', default=None, type=str, help=( '''Path to the PyTorch checkpoint path or shortcut name to download from AWS. ''' '''If not given, will download and convert all the checkpoints from AWS.''' ), ) parser.add_argument( '''--config_file''', default=None, type=str, help=( '''The config json file corresponding to the pre-trained model. \n''' '''This specifies the model architecture. If not given and ''' '''--pytorch_checkpoint_path is not given or is a shortcut name ''' '''use the configuration associated to the shortcut name on the AWS''' ), ) parser.add_argument( '''--compare_with_pt_model''', action='''store_true''', help='''Compare Tensorflow and PyTorch model predictions.''' ) parser.add_argument( '''--use_cached_models''', action='''store_true''', help='''Use cached models if possible instead of updating to latest checkpoint versions.''', ) parser.add_argument( '''--remove_cached_files''', action='''store_true''', help='''Remove pytorch models after conversion (save memory when converting in batches).''', ) parser.add_argument('''--only_convert_finetuned_models''', action='''store_true''', help='''Only convert finetuned models.''') _a = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
39
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
0
"""simple docstring""" import itertools import math def lowercase ( A_ )-> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(A_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( )-> Tuple: '''simple docstring''' a : Tuple = 2 while True: if is_prime(A_ ): yield num num += 1 def lowercase ( A_ = 10_001 )-> int: '''simple docstring''' return next(itertools.islice(prime_generator() , nth - 1 , A_ ) ) if __name__ == "__main__": print(f'''{solution() = }''')
40
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [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 _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
0
'''simple docstring''' from manim import * class _lowercase ( _lowercase ): def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : List[Any] = Rectangle(height=0.5 , width=0.5 ) lowerCamelCase__ : int = Rectangle(height=0.25 , width=0.25 ) lowerCamelCase__ : Optional[int] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowerCamelCase__ : List[str] = [mem.copy() for i in range(6 )] lowerCamelCase__ : List[Any] = [mem.copy() for i in range(6 )] lowerCamelCase__ : int = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : Dict = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : str = VGroup(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : List[str] = Text("""CPU""" , font_size=24 ) lowerCamelCase__ : Dict = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(UpperCamelCase__ ) lowerCamelCase__ : str = [mem.copy() for i in range(4 )] lowerCamelCase__ : Dict = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : Dict = Text("""GPU""" , font_size=24 ) lowerCamelCase__ : Union[str, Any] = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) gpu.move_to([-1, -1, 0] ) self.add(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = [mem.copy() for i in range(6 )] lowerCamelCase__ : Tuple = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : List[Any] = Text("""Model""" , font_size=24 ) lowerCamelCase__ : Any = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) model.move_to([3, -1.0, 0] ) self.add(UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = [] lowerCamelCase__ : Tuple = [] lowerCamelCase__ : Union[str, Any] = [] for i, rect in enumerate(UpperCamelCase__ ): rect.set_stroke(UpperCamelCase__ ) lowerCamelCase__ : Dict = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(UpperCamelCase__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=UpperCamelCase__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=UpperCamelCase__ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=UpperCamelCase__ , buff=0.0 ) self.add(UpperCamelCase__ ) model_cpu_arr.append(UpperCamelCase__ ) self.add(*UpperCamelCase__ , *UpperCamelCase__ , *UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = [mem.copy() for i in range(6 )] lowerCamelCase__ : Any = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : Dict = Text("""Loaded Checkpoint""" , font_size=24 ) lowerCamelCase__ : Tuple = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) checkpoint.move_to([3, 0.5, 0] ) self.add(UpperCamelCase__ ) lowerCamelCase__ : Dict = [] lowerCamelCase__ : Dict = [] for i, rect in enumerate(UpperCamelCase__ ): lowerCamelCase__ : Tuple = fill.copy().set_fill(UpperCamelCase__ , opacity=0.7 ) target.move_to(UpperCamelCase__ ) ckpt_arr.append(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(UpperCamelCase__ ) self.add(*UpperCamelCase__ , *UpperCamelCase__ ) lowerCamelCase__ : str = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCamelCase__ : int = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(UpperCamelCase__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(UpperCamelCase__ ) lowerCamelCase__ : Tuple = MarkupText( F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) lowerCamelCase__ : int = [meta_mem.copy() for i in range(6 )] lowerCamelCase__ : Union[str, Any] = [meta_mem.copy() for i in range(6 )] lowerCamelCase__ : List[str] = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : Optional[int] = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : List[str] = VGroup(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) lowerCamelCase__ : Any = Text("""Disk""" , font_size=24 ) lowerCamelCase__ : List[str] = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(UpperCamelCase__ , run_time=3 ) , Write(UpperCamelCase__ , run_time=1 ) , Create(UpperCamelCase__ , run_time=1 ) ) lowerCamelCase__ : Union[str, Any] = [] for i, rect in enumerate(UpperCamelCase__ ): lowerCamelCase__ : List[Any] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(UpperCamelCase__ , run_time=1.5 ) ) self.play(*UpperCamelCase__ ) self.play(FadeOut(UpperCamelCase__ ) ) lowerCamelCase__ : Any = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(UpperCamelCase__ , run_time=3 ) ) self.play( FadeOut(UpperCamelCase__ , UpperCamelCase__ , *UpperCamelCase__ , *UpperCamelCase__ ) , ) self.wait()
41
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class __UpperCAmelCase ( unittest.TestCase ): __lowercase = StableDiffusionLDMaDPipeline __lowercase = TEXT_TO_IMAGE_PARAMS __lowercase = TEXT_TO_IMAGE_BATCH_PARAMS __lowercase = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _snake_case = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) _snake_case = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=lowerCAmelCase_ , set_alpha_to_one=lowerCAmelCase_ , ) torch.manual_seed(0 ) _snake_case = AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) _snake_case = 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=10_00 , ) _snake_case = CLIPTextModel(lowerCAmelCase_ ) _snake_case = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _snake_case = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=0 ): """simple docstring""" if str(lowerCAmelCase_ ).startswith('mps' ): _snake_case = torch.manual_seed(lowerCAmelCase_ ) else: _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _snake_case = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def lowerCamelCase ( self ): """simple docstring""" _snake_case = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = StableDiffusionLDMaDPipeline(**lowerCAmelCase_ ) _snake_case = ldmad_pipe.to(lowerCAmelCase_ ) ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase_ ) _snake_case = ldmad_pipe(**lowerCAmelCase_ ) _snake_case , _snake_case = output.rgb, output.depth _snake_case = rgb[0, -3:, -3:, -1] _snake_case = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) _snake_case = np.array( [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262] ) _snake_case = np.array([103.46727, 85.812004, 87.849236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1E-2 def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.get_dummy_components() _snake_case = StableDiffusionLDMaDPipeline(**lowerCAmelCase_ ) _snake_case = ldmad_pipe.to(lowerCAmelCase_ ) ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase_ ) _snake_case = 3 * [inputs['prompt']] # forward _snake_case = ldmad_pipe(**lowerCAmelCase_ ) _snake_case , _snake_case = output.rgb, output.depth _snake_case = rgb_slice_a[0, -3:, -3:, -1] _snake_case = depth_slice_a[0, -3:, -1] _snake_case = self.get_dummy_inputs(lowerCAmelCase_ ) _snake_case = 3 * [inputs.pop('prompt' )] _snake_case = ldmad_pipe.tokenizer( lowerCAmelCase_ , padding='max_length' , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=lowerCAmelCase_ , return_tensors='pt' , ) _snake_case = text_inputs['input_ids'].to(lowerCAmelCase_ ) _snake_case = ldmad_pipe.text_encoder(lowerCAmelCase_ )[0] _snake_case = prompt_embeds # forward _snake_case = ldmad_pipe(**lowerCAmelCase_ ) _snake_case , _snake_case = output.rgb, output.depth _snake_case = rgb_slice_a[0, -3:, -3:, -1] _snake_case = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1E-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1E-4 def lowerCamelCase ( self ): """simple docstring""" _snake_case = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = PNDMScheduler(skip_prk_steps=lowerCAmelCase_ ) _snake_case = StableDiffusionLDMaDPipeline(**lowerCAmelCase_ ) _snake_case = ldmad_pipe.to(lowerCAmelCase_ ) ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase_ ) _snake_case = 'french fries' _snake_case = ldmad_pipe(**lowerCAmelCase_ , negative_prompt=lowerCAmelCase_ ) _snake_case , _snake_case = output.rgb, output.depth _snake_case = rgb[0, -3:, -3:, -1] _snake_case = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) _snake_case = np.array( [0.37044, 0.71811503, 0.7223251, 0.48603675, 0.5638391, 0.6364948, 0.42833704, 0.4901315, 0.47926217] ) _snake_case = np.array([107.84738, 84.62802, 89.962135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1E-2 @slow @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_="cpu" , lowerCAmelCase_=torch.floataa , lowerCAmelCase_=0 ): """simple docstring""" _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _snake_case = np.random.RandomState(lowerCAmelCase_ ).standard_normal((1, 4, 64, 64) ) _snake_case = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ) _snake_case = { '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 lowerCamelCase ( self ): """simple docstring""" _snake_case = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ) _snake_case = ldmad_pipe.to(lowerCAmelCase_ ) ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_inputs(lowerCAmelCase_ ) _snake_case = ldmad_pipe(**lowerCAmelCase_ ) _snake_case , _snake_case = output.rgb, output.depth _snake_case = rgb[0, -3:, -3:, -1].flatten() _snake_case = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 5_12, 5_12, 3) assert depth.shape == (1, 5_12, 5_12) _snake_case = np.array( [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706] ) _snake_case = np.array( [0.9263781, 0.6678672, 0.5486515, 0.92202145, 0.67831135, 0.56253487, 0.9241694, 0.7551478, 0.6459706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3E-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3E-3 @nightly @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_="cpu" , lowerCAmelCase_=torch.floataa , lowerCAmelCase_=0 ): """simple docstring""" _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _snake_case = np.random.RandomState(lowerCAmelCase_ ).standard_normal((1, 4, 64, 64) ) _snake_case = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ) _snake_case = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 50, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def lowerCamelCase ( self ): """simple docstring""" _snake_case = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ).to(lowerCAmelCase_ ) ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_inputs(lowerCAmelCase_ ) _snake_case = ldmad_pipe(**lowerCAmelCase_ ) _snake_case , _snake_case = output.rgb, output.depth _snake_case = 0.495586 _snake_case = 0.33795515 _snake_case = 112.48518 _snake_case = 98.489746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3 def lowerCamelCase ( self ): """simple docstring""" _snake_case = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d-4c' ).to(lowerCAmelCase_ ) ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_inputs(lowerCAmelCase_ ) _snake_case = ldmad_pipe(**lowerCAmelCase_ ) _snake_case , _snake_case = output.rgb, output.depth _snake_case = 0.4194127 _snake_case = 0.35375586 _snake_case = 0.5638502 _snake_case = 0.34686103 assert rgb.shape == (1, 5_12, 5_12, 3) assert depth.shape == (1, 5_12, 5_12, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3
42
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = 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(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase = { '''configuration_data2vec_audio''': ['''DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecAudioConfig'''], '''configuration_data2vec_text''': [ '''DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecTextConfig''', '''Data2VecTextOnnxConfig''', ], '''configuration_data2vec_vision''': [ '''DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecVisionConfig''', '''Data2VecVisionOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecAudioForAudioFrameClassification''', '''Data2VecAudioForCTC''', '''Data2VecAudioForSequenceClassification''', '''Data2VecAudioForXVector''', '''Data2VecAudioModel''', '''Data2VecAudioPreTrainedModel''', ] __lowercase = [ '''DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecTextForCausalLM''', '''Data2VecTextForMaskedLM''', '''Data2VecTextForMultipleChoice''', '''Data2VecTextForQuestionAnswering''', '''Data2VecTextForSequenceClassification''', '''Data2VecTextForTokenClassification''', '''Data2VecTextModel''', '''Data2VecTextPreTrainedModel''', ] __lowercase = [ '''DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecVisionForImageClassification''', '''Data2VecVisionForMaskedImageModeling''', '''Data2VecVisionForSemanticSegmentation''', '''Data2VecVisionModel''', '''Data2VecVisionPreTrainedModel''', ] if is_tf_available(): __lowercase = [ '''TFData2VecVisionForImageClassification''', '''TFData2VecVisionForSemanticSegmentation''', '''TFData2VecVisionModel''', '''TFData2VecVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
43
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a : Optional[int] = logging.get_logger(__name__) _a : Tuple = { 'sail/poolformer_s12': 'https://huggingface.co/sail/poolformer_s12/resolve/main/config.json', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Union[str, Any] = "poolformer" def __init__( self , a__=3 , a__=16 , a__=16 , a__=3 , a__=4.0 , a__=[2, 2, 6, 2] , a__=[64, 128, 320, 512] , a__=[7, 3, 3, 3] , a__=[4, 2, 2, 2] , a__=[2, 1, 1, 1] , a__=4 , a__=0.0 , a__="gelu" , a__=True , a__=1e-5 , a__=0.0_2 , **a__ , ): _lowerCAmelCase : List[Any] = num_channels _lowerCAmelCase : str = patch_size _lowerCAmelCase : Dict = stride _lowerCAmelCase : Optional[int] = padding _lowerCAmelCase : Optional[int] = pool_size _lowerCAmelCase : Dict = hidden_sizes _lowerCAmelCase : Optional[int] = mlp_ratio _lowerCAmelCase : Optional[int] = depths _lowerCAmelCase : Dict = patch_sizes _lowerCAmelCase : Tuple = strides _lowerCAmelCase : Any = num_encoder_blocks _lowerCAmelCase : Any = drop_path_rate _lowerCAmelCase : Tuple = hidden_act _lowerCAmelCase : Optional[Any] = use_layer_scale _lowerCAmelCase : List[str] = layer_scale_init_value _lowerCAmelCase : List[Any] = initializer_range super().__init__(**a__ ) class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = version.parse("1.11" ) @property def __A ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __A ( self ): return 2e-3
44
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
0
"""simple docstring""" from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): if isinstance(_a , _a ): __a = [label.strip() for label in labels.split(''',''' ) if label.strip()] return labels def __call__( self , _a , _a , _a ): if len(_a ) == 0 or len(_a ) == 0: raise ValueError('''You must include at least one label and at least one sequence.''' ) if hypothesis_template.format(labels[0] ) == hypothesis_template: raise ValueError( ( '''The provided hypothesis_template "{}" was not able to be formatted with the target labels. ''' '''Make sure the passed template includes formatting syntax such as {{}} where the label should go.''' ).format(_a ) ) if isinstance(_a , _a ): __a = [sequences] __a = [] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(_a )] for label in labels] ) return sequence_pairs, sequences @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=ZeroShotClassificationArgumentHandler() , *_a , **_a ): __a = args_parser super().__init__(*_a , **_a ) if self.entailment_id == -1: logger.warning( '''Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to ''' '''-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.''' ) @property def __UpperCAmelCase ( self ): for label, ind in self.model.config.labelaid.items(): if label.lower().startswith('''entail''' ): return ind return -1 def __UpperCAmelCase ( self , _a , _a=True , _a=True , _a=TruncationStrategy.ONLY_FIRST , **_a ): __a = self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( '''Tokenizer was not supporting padding necessary for zero-shot, attempting to use ''' ''' `pad_token=eos_token`''' ) __a = self.tokenizer.eos_token try: __a = self.tokenizer( _a , add_special_tokens=_a , return_tensors=_a , padding=_a , truncation=_a , ) except Exception as e: if "too short" in str(_a ): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. __a = self.tokenizer( _a , add_special_tokens=_a , return_tensors=_a , padding=_a , truncation=TruncationStrategy.DO_NOT_TRUNCATE , ) else: raise e return inputs def __UpperCAmelCase ( self , **_a ): if kwargs.get('''multi_class''' , _a ) is not None: __a = kwargs['''multi_class'''] logger.warning( '''The `multi_class` argument has been deprecated and renamed to `multi_label`. ''' '''`multi_class` will be removed in a future version of Transformers.''' ) __a = {} if "candidate_labels" in kwargs: __a = self._args_parser._parse_labels(kwargs['''candidate_labels'''] ) if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] __a = {} if "multi_label" in kwargs: __a = kwargs['''multi_label'''] return preprocess_params, {}, postprocess_params def __call__( self , _a , *_a , **_a , ): if len(_a ) == 0: pass elif len(_a ) == 1 and "candidate_labels" not in kwargs: __a = args[0] else: raise ValueError(f'''Unable to understand extra arguments {args}''' ) return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , _a , _a=None , _a="This example is {}." ): __a , __a = self._args_parser(_a , _a , _a ) for i, (candidate_label, sequence_pair) in enumerate(zip(_a , _a ) ): __a = self._parse_and_tokenize([sequence_pair] ) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(_a ) - 1, **model_input, } def __UpperCAmelCase ( self , _a ): __a = inputs['''candidate_label'''] __a = inputs['''sequence'''] __a = {k: inputs[k] for k in self.tokenizer.model_input_names} __a = self.model(**_a ) __a = { '''candidate_label''': candidate_label, '''sequence''': sequence, '''is_last''': inputs['''is_last'''], **outputs, } return model_outputs def __UpperCAmelCase ( self , _a , _a=False ): __a = [outputs['''candidate_label'''] for outputs in model_outputs] __a = [outputs['''sequence'''] for outputs in model_outputs] __a = np.concatenate([output['''logits'''].numpy() for output in model_outputs] ) __a = logits.shape[0] __a = len(_a ) __a = N // n __a = logits.reshape((num_sequences, n, -1) ) if multi_label or len(_a ) == 1: # softmax over the entailment vs. contradiction dim for each label independently __a = self.entailment_id __a = -1 if entailment_id == 0 else 0 __a = reshaped_outputs[..., [contradiction_id, entailment_id]] __a = np.exp(_a ) / np.exp(_a ).sum(-1 , keepdims=_a ) __a = scores[..., 1] else: # softmax the "entailment" logits over all candidate labels __a = reshaped_outputs[..., self.entailment_id] __a = np.exp(_a ) / np.exp(_a ).sum(-1 , keepdims=_a ) __a = list(reversed(scores[0].argsort() ) ) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
45
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
0
"""simple docstring""" import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback from torch import nn from torch.utils.data import DataLoader from transformers import MBartTokenizer, TaForConditionalGeneration from transformers.models.bart.modeling_bart import shift_tokens_right from utils import ( ROUGE_KEYS, LegacySeqaSeqDataset, SeqaSeqDataset, assert_all_frozen, calculate_bleu, calculate_rouge, check_output_dir, flatten_list, freeze_embeds, freeze_params, get_git_info, label_smoothed_nll_loss, lmap, pickle_save, save_git_info, save_json, use_task_specific_params, ) # need the parent dir module sys.path.insert(2, str(Path(__file__).resolve().parents[1])) from lightning_base import BaseTransformer, add_generic_args, generic_train # noqa SCREAMING_SNAKE_CASE__ = logging.getLogger(__name__) class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = 'summarization' _SCREAMING_SNAKE_CASE = ['loss'] _SCREAMING_SNAKE_CASE = ROUGE_KEYS _SCREAMING_SNAKE_CASE = 'rouge2' def __init__( self , lowercase , **lowercase ) -> str: if hparams.sortish_sampler and hparams.gpus > 1: lowerCAmelCase = False elif hparams.max_tokens_per_batch is not None: if hparams.gpus > 1: raise NotImplementedError("""Dynamic Batch size does not work for multi-gpu training""" ) if hparams.sortish_sampler: raise ValueError("""--sortish_sampler and --max_tokens_per_batch may not be used simultaneously""" ) super().__init__(lowercase , num_labels=lowercase , mode=self.mode , **lowercase ) use_task_specific_params(self.model , """summarization""" ) save_git_info(self.hparams.output_dir ) lowerCAmelCase = Path(self.output_dir ) / """metrics.json""" lowerCAmelCase = Path(self.output_dir ) / """hparams.pkl""" pickle_save(self.hparams , self.hparams_save_path ) lowerCAmelCase = 0 lowerCAmelCase = defaultdict(lowercase ) lowerCAmelCase = self.config.model_type lowerCAmelCase = self.config.tgt_vocab_size if self.model_type == """fsmt""" else self.config.vocab_size lowerCAmelCase = { "data_dir": self.hparams.data_dir, "max_source_length": self.hparams.max_source_length, "prefix": self.model.config.prefix or "", } lowerCAmelCase = { """train""": self.hparams.n_train, """val""": self.hparams.n_val, """test""": self.hparams.n_test, } lowerCAmelCase = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()} lowerCAmelCase = { """train""": self.hparams.max_target_length, """val""": self.hparams.val_max_target_length, """test""": self.hparams.test_max_target_length, } assert self.target_lens["train"] <= self.target_lens["val"], f'target_lens: {self.target_lens}' assert self.target_lens["train"] <= self.target_lens["test"], f'target_lens: {self.target_lens}' if self.hparams.freeze_embeds: freeze_embeds(self.model ) if self.hparams.freeze_encoder: freeze_params(self.model.get_encoder() ) assert_all_frozen(self.model.get_encoder() ) lowerCAmelCase = get_git_info()["""repo_sha"""] lowerCAmelCase = hparams.num_workers lowerCAmelCase = None # default to config if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , lowercase ): lowerCAmelCase = self.tokenizer.lang_code_to_id[hparams.tgt_lang] lowerCAmelCase = self.decoder_start_token_id lowerCAmelCase = ( SeqaSeqDataset if hasattr(self.tokenizer , """prepare_seq2seq_batch""" ) else LegacySeqaSeqDataset ) lowerCAmelCase = False lowerCAmelCase = self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams if self.hparams.eval_max_gen_length is not None: lowerCAmelCase = self.hparams.eval_max_gen_length else: lowerCAmelCase = self.model.config.max_length lowerCAmelCase = self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric def _snake_case ( self , lowercase ) -> Dict[str, List[str]]: lowerCAmelCase = { k: self.tokenizer.batch_decode(v.tolist() ) if """mask""" not in k else v.shape for k, v in batch.items() } save_json(lowercase , Path(self.output_dir ) / """text_batch.json""" ) save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir ) / """tok_batch.json""" ) lowerCAmelCase = True return readable_batch def _snake_case ( self , lowercase , **lowercase ) -> Union[str, Any]: return self.model(lowercase , **lowercase ) def _snake_case ( self , lowercase ) -> Union[str, Any]: lowerCAmelCase = self.tokenizer.batch_decode( lowercase , skip_special_tokens=lowercase , clean_up_tokenization_spaces=lowercase ) return lmap(str.strip , lowercase ) def _snake_case ( self , lowercase ) -> Tuple: lowerCAmelCase = self.tokenizer.pad_token_id lowerCAmelCase , lowerCAmelCase = batch["""input_ids"""], batch["""attention_mask"""] lowerCAmelCase = batch["""labels"""] if isinstance(self.model , lowercase ): lowerCAmelCase = self.model._shift_right(lowercase ) else: lowerCAmelCase = shift_tokens_right(lowercase , lowercase ) if not self.already_saved_batch: # This would be slightly better if it only happened on rank zero lowerCAmelCase = decoder_input_ids self.save_readable_batch(lowercase ) lowerCAmelCase = self(lowercase , attention_mask=lowercase , decoder_input_ids=lowercase , use_cache=lowercase ) lowerCAmelCase = outputs["""logits"""] if self.hparams.label_smoothing == 0: # Same behavior as modeling_bart.py, besides ignoring pad_token_id lowerCAmelCase = nn.CrossEntropyLoss(ignore_index=lowercase ) assert lm_logits.shape[-1] == self.vocab_size lowerCAmelCase = ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1] ) , tgt_ids.view(-1 ) ) else: lowerCAmelCase = nn.functional.log_softmax(lowercase , dim=-1 ) lowerCAmelCase , lowerCAmelCase = label_smoothed_nll_loss( lowercase , lowercase , self.hparams.label_smoothing , ignore_index=lowercase ) return (loss,) @property def _snake_case ( self ) -> int: return self.tokenizer.pad_token_id def _snake_case ( self , lowercase , lowercase ) -> Dict: lowerCAmelCase = self._step(lowercase ) lowerCAmelCase = dict(zip(self.loss_names , lowercase ) ) # tokens per batch lowerCAmelCase = batch["""input_ids"""].ne(self.pad ).sum() + batch["""labels"""].ne(self.pad ).sum() lowerCAmelCase = batch["""input_ids"""].shape[0] lowerCAmelCase = batch["""input_ids"""].eq(self.pad ).sum() lowerCAmelCase = batch["""input_ids"""].eq(self.pad ).float().mean() # TODO(SS): make a wandb summary metric for this return {"loss": loss_tensors[0], "log": logs} def _snake_case ( self , lowercase , lowercase ) -> Dict: return self._generative_step(lowercase ) def _snake_case ( self , lowercase , lowercase="val" ) -> Dict: self.step_count += 1 lowerCAmelCase = {k: torch.stack([x[k] for x in outputs] ).mean() for k in self.loss_names} lowerCAmelCase = losses["""loss"""] lowerCAmelCase = { k: np.array([x[k] for x in outputs] ).mean() for k in self.metric_names + ["""gen_time""", """gen_len"""] } lowerCAmelCase = ( generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric] ) lowerCAmelCase = torch.tensor(lowercase ).type_as(lowercase ) generative_metrics.update({k: v.item() for k, v in losses.items()} ) losses.update(lowercase ) lowerCAmelCase = {f'{prefix}_avg_{k}': x for k, x in losses.items()} lowerCAmelCase = self.step_count self.metrics[prefix].append(lowercase ) # callback writes this to self.metrics_save_path lowerCAmelCase = flatten_list([x["""preds"""] for x in outputs] ) return { "log": all_metrics, "preds": preds, f'{prefix}_loss': loss, f'{prefix}_{self.val_metric}': metric_tensor, } def _snake_case ( self , lowercase , lowercase ) -> Dict: return calculate_rouge(lowercase , lowercase ) def _snake_case ( self , lowercase ) -> dict: lowerCAmelCase = time.time() # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens') lowerCAmelCase = self.model.generate( batch["""input_ids"""] , attention_mask=batch["""attention_mask"""] , use_cache=lowercase , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , ) lowerCAmelCase = (time.time() - ta) / batch["""input_ids"""].shape[0] lowerCAmelCase = self.ids_to_clean_text(lowercase ) lowerCAmelCase = self.ids_to_clean_text(batch["""labels"""] ) lowerCAmelCase = self._step(lowercase ) lowerCAmelCase = dict(zip(self.loss_names , lowercase ) ) lowerCAmelCase = self.calc_generative_metrics(lowercase , lowercase ) lowerCAmelCase = np.mean(lmap(lowercase , lowercase ) ) base_metrics.update(gen_time=lowercase , gen_len=lowercase , preds=lowercase , target=lowercase , **lowercase ) return base_metrics def _snake_case ( self , lowercase , lowercase ) -> Dict: return self._generative_step(lowercase ) def _snake_case ( self , lowercase ) -> int: return self.validation_epoch_end(lowercase , prefix="""test""" ) def _snake_case ( self , lowercase ) -> SeqaSeqDataset: lowerCAmelCase = self.n_obs[type_path] lowerCAmelCase = self.target_lens[type_path] lowerCAmelCase = self.dataset_class( self.tokenizer , type_path=lowercase , n_obs=lowercase , max_target_length=lowercase , **self.dataset_kwargs , ) return dataset def _snake_case ( self , lowercase , lowercase , lowercase = False ) -> DataLoader: lowerCAmelCase = self.get_dataset(lowercase ) if self.hparams.sortish_sampler and type_path != "test" and type_path != "val": lowerCAmelCase = dataset.make_sortish_sampler(lowercase , distributed=self.hparams.gpus > 1 ) return DataLoader( lowercase , batch_size=lowercase , collate_fn=dataset.collate_fn , shuffle=lowercase , num_workers=self.num_workers , sampler=lowercase , ) elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val": lowerCAmelCase = dataset.make_dynamic_sampler( self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1 ) return DataLoader( lowercase , batch_sampler=lowercase , collate_fn=dataset.collate_fn , num_workers=self.num_workers , ) else: return DataLoader( lowercase , batch_size=lowercase , collate_fn=dataset.collate_fn , shuffle=lowercase , num_workers=self.num_workers , sampler=lowercase , ) def _snake_case ( self ) -> DataLoader: lowerCAmelCase = self.get_dataloader("""train""" , batch_size=self.hparams.train_batch_size , shuffle=lowercase ) return dataloader def _snake_case ( self ) -> DataLoader: return self.get_dataloader("""val""" , batch_size=self.hparams.eval_batch_size ) def _snake_case ( self ) -> DataLoader: return self.get_dataloader("""test""" , batch_size=self.hparams.eval_batch_size ) @staticmethod def _snake_case ( lowercase , lowercase ) -> Optional[int]: BaseTransformer.add_model_specific_args(lowercase , lowercase ) add_generic_args(lowercase , lowercase ) parser.add_argument( """--max_source_length""" , default=1_024 , type=lowercase , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--max_target_length""" , default=56 , type=lowercase , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--val_max_target_length""" , default=142 , type=lowercase , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--test_max_target_length""" , default=142 , type=lowercase , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument("""--freeze_encoder""" , action="""store_true""" ) parser.add_argument("""--freeze_embeds""" , action="""store_true""" ) parser.add_argument("""--sortish_sampler""" , action="""store_true""" , default=lowercase ) parser.add_argument("""--overwrite_output_dir""" , action="""store_true""" , default=lowercase ) parser.add_argument("""--max_tokens_per_batch""" , type=lowercase , default=lowercase ) parser.add_argument("""--logger_name""" , type=lowercase , choices=["""default""", """wandb""", """wandb_shared"""] , default="""default""" ) parser.add_argument("""--n_train""" , type=lowercase , default=-1 , required=lowercase , help="""# examples. -1 means use all.""" ) parser.add_argument("""--n_val""" , type=lowercase , default=500 , required=lowercase , help="""# examples. -1 means use all.""" ) parser.add_argument("""--n_test""" , type=lowercase , default=-1 , required=lowercase , help="""# examples. -1 means use all.""" ) parser.add_argument( """--task""" , type=lowercase , default="""summarization""" , required=lowercase , help="""# examples. -1 means use all.""" ) parser.add_argument("""--label_smoothing""" , type=lowercase , default=0.0 , required=lowercase ) parser.add_argument("""--src_lang""" , type=lowercase , default="""""" , required=lowercase ) parser.add_argument("""--tgt_lang""" , type=lowercase , default="""""" , required=lowercase ) parser.add_argument("""--eval_beams""" , type=lowercase , default=lowercase , required=lowercase ) parser.add_argument( """--val_metric""" , type=lowercase , default=lowercase , required=lowercase , choices=["""bleu""", """rouge2""", """loss""", None] ) parser.add_argument("""--eval_max_gen_length""" , type=lowercase , default=lowercase , help="""never generate more than n tokens""" ) parser.add_argument("""--save_top_k""" , type=lowercase , default=1 , required=lowercase , help="""How many checkpoints to save""" ) parser.add_argument( """--early_stopping_patience""" , type=lowercase , default=-1 , required=lowercase , help=( """-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So""" """ val_check_interval will effect it.""" ) , ) return parser class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = 'translation' _SCREAMING_SNAKE_CASE = ['loss'] _SCREAMING_SNAKE_CASE = ['bleu'] _SCREAMING_SNAKE_CASE = 'bleu' def __init__( self , lowercase , **lowercase ) -> Union[str, Any]: super().__init__(lowercase , **lowercase ) lowerCAmelCase = hparams.src_lang lowerCAmelCase = hparams.tgt_lang def _snake_case ( self , lowercase , lowercase ) -> dict: return calculate_bleu(lowercase , lowercase ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : int=None ): '''simple docstring''' Path(args.output_dir ).mkdir(exist_ok=SCREAMING_SNAKE_CASE ) check_output_dir(SCREAMING_SNAKE_CASE , expected_items=3 ) if model is None: if "summarization" in args.task: lowerCAmelCase = SummarizationModule(SCREAMING_SNAKE_CASE ) else: lowerCAmelCase = TranslationModule(SCREAMING_SNAKE_CASE ) lowerCAmelCase = Path(args.data_dir ).name if ( args.logger_name == "default" or args.fast_dev_run or str(args.output_dir ).startswith("""/tmp""" ) or str(args.output_dir ).startswith("""/var""" ) ): lowerCAmelCase = True # don't pollute wandb logs unnecessarily elif args.logger_name == "wandb": from pytorch_lightning.loggers import WandbLogger lowerCAmelCase = os.environ.get("""WANDB_PROJECT""" , SCREAMING_SNAKE_CASE ) lowerCAmelCase = WandbLogger(name=model.output_dir.name , project=SCREAMING_SNAKE_CASE ) elif args.logger_name == "wandb_shared": from pytorch_lightning.loggers import WandbLogger lowerCAmelCase = WandbLogger(name=model.output_dir.name , project=F'hf_{dataset}' ) if args.early_stopping_patience >= 0: lowerCAmelCase = get_early_stopping_callback(model.val_metric , args.early_stopping_patience ) else: lowerCAmelCase = False lowerCAmelCase = args.val_metric == """loss""" lowerCAmelCase = generic_train( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , logging_callback=SeqaSeqLoggingCallback() , checkpoint_callback=get_checkpoint_callback( args.output_dir , model.val_metric , args.save_top_k , SCREAMING_SNAKE_CASE ) , early_stopping_callback=SCREAMING_SNAKE_CASE , logger=SCREAMING_SNAKE_CASE , ) pickle_save(model.hparams , model.output_dir / """hparams.pkl""" ) if not args.do_predict: return model lowerCAmelCase = """""" lowerCAmelCase = sorted(glob.glob(os.path.join(args.output_dir , """*.ckpt""" ) , recursive=SCREAMING_SNAKE_CASE ) ) if checkpoints: lowerCAmelCase = checkpoints[-1] lowerCAmelCase = checkpoints[-1] trainer.logger.log_hyperparams(model.hparams ) # test() without a model tests using the best checkpoint automatically trainer.test() return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() SCREAMING_SNAKE_CASE__ = pl.Trainer.add_argparse_args(parser) SCREAMING_SNAKE_CASE__ = SummarizationModule.add_model_specific_args(parser, os.getcwd()) SCREAMING_SNAKE_CASE__ = parser.parse_args() main(args)
46
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
0
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Any ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE ='https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert('RGB' ) _SCREAMING_SNAKE_CASE =transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73) , (0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11) ), ] ) _SCREAMING_SNAKE_CASE =transform(_UpperCamelCase ).unsqueeze(0 ).to(_UpperCamelCase ) return image def _lowerCAmelCase ( _UpperCamelCase : Dict ) -> str: """simple docstring""" if "visual_encoder" in key: _SCREAMING_SNAKE_CASE =re.sub('visual_encoder*' , 'vision_model.encoder' , _UpperCamelCase ) if "blocks" in key: _SCREAMING_SNAKE_CASE =re.sub(r'blocks' , 'layers' , _UpperCamelCase ) if "attn" in key: _SCREAMING_SNAKE_CASE =re.sub(r'attn' , 'self_attn' , _UpperCamelCase ) if "norm1" in key: _SCREAMING_SNAKE_CASE =re.sub(r'norm1' , 'layer_norm1' , _UpperCamelCase ) if "norm2" in key: _SCREAMING_SNAKE_CASE =re.sub(r'norm2' , 'layer_norm2' , _UpperCamelCase ) if "encoder.norm" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.norm' , 'post_layernorm' , _UpperCamelCase ) if "encoder.patch_embed.proj" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.patch_embed.proj' , 'embeddings.patch_embedding' , _UpperCamelCase ) if "encoder.pos_embed" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.pos_embed' , 'embeddings.position_embedding' , _UpperCamelCase ) if "encoder.cls_token" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.cls_token' , 'embeddings.class_embedding' , _UpperCamelCase ) if "self_attn" in key: _SCREAMING_SNAKE_CASE =re.sub(r'self_attn.proj' , 'self_attn.projection' , _UpperCamelCase ) return key @torch.no_grad() def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : int=None ) -> Tuple: """simple docstring""" if config_path is not None: _SCREAMING_SNAKE_CASE =BlipConfig.from_pretrained(_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) _SCREAMING_SNAKE_CASE =BlipForConditionalGeneration(_UpperCamelCase ).eval() _SCREAMING_SNAKE_CASE ='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth' _SCREAMING_SNAKE_CASE =blip_decoder(pretrained=_UpperCamelCase , image_size=3_84 , vit='base' ) _SCREAMING_SNAKE_CASE =pt_model.eval() _SCREAMING_SNAKE_CASE =pt_model.state_dict() for key in modified_state_dict.copy(): _SCREAMING_SNAKE_CASE =modified_state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =rename_key(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =value hf_model.load_state_dict(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =3_84 _SCREAMING_SNAKE_CASE =load_demo_image(image_size=_UpperCamelCase , device='cpu' ) _SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('bert-base-uncased' ) _SCREAMING_SNAKE_CASE =tokenizer(['a picture of'] ).input_ids _SCREAMING_SNAKE_CASE =hf_model.generate(_UpperCamelCase , _UpperCamelCase ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] _SCREAMING_SNAKE_CASE =hf_model.generate(_UpperCamelCase ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_UpperCamelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' _SCREAMING_SNAKE_CASE =( 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth' ) _SCREAMING_SNAKE_CASE =blip_vqa(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit='base' ) vqa_model.eval() _SCREAMING_SNAKE_CASE =vqa_model.state_dict() for key in modified_state_dict.copy(): _SCREAMING_SNAKE_CASE =modified_state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =rename_key(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =BlipForQuestionAnswering(_UpperCamelCase ) hf_vqa_model.load_state_dict(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =['How many dogs are in this image?'] _SCREAMING_SNAKE_CASE =tokenizer(_UpperCamelCase , return_tensors='pt' ).input_ids _SCREAMING_SNAKE_CASE =hf_vqa_model.generate(_UpperCamelCase , _UpperCamelCase ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '_vqa' ) _SCREAMING_SNAKE_CASE ='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth' _SCREAMING_SNAKE_CASE =blip_itm(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit='base' ) itm_model.eval() _SCREAMING_SNAKE_CASE =itm_model.state_dict() for key in modified_state_dict.copy(): _SCREAMING_SNAKE_CASE =modified_state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =rename_key(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =BlipForImageTextRetrieval(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =['A picture of a woman with a dog sitting in a beach'] _SCREAMING_SNAKE_CASE =tokenizer( _UpperCamelCase , return_tensors='pt' , padding='max_length' , truncation=_UpperCamelCase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_UpperCamelCase ) hf_itm_model.eval() _SCREAMING_SNAKE_CASE =hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) assert out[0].item() == 0.21_10_68_74_94_27_79_54 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_56_98_84_53_86_50_51_27 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm' ) if __name__ == "__main__": lowerCamelCase : Dict = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") lowerCamelCase : int = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
47
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __SCREAMING_SNAKE_CASE : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : int = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = tabu_search( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": _lowercase : Any = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
93
0
import torch from diffusers import DiffusionPipeline class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: super().__init__() self.register_modules(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) def __call__( self ) -> List[Any]: lowerCamelCase : Dict = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) lowerCamelCase : Optional[Any] = 1 lowerCamelCase : Optional[Any] = self.unet(UpperCamelCase__ , UpperCamelCase__ ).sample lowerCamelCase : int = self.scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample lowerCamelCase : Optional[Any] = scheduler_output - scheduler_output + torch.ones_like(UpperCamelCase__ ) return result
48
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
0
import functools def __snake_case ( _UpperCAmelCase , _UpperCAmelCase ): __a = len(_UpperCAmelCase ) __a = len(_UpperCAmelCase ) @functools.cache def min_distance(_UpperCAmelCase , _UpperCAmelCase ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa __a = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , _UpperCAmelCase ) , 1 + min_distance(_UpperCAmelCase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
49
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
0
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase = 100_0000 ) -> int: lowerCamelCase__ : int = limit + 1 lowerCamelCase__ : Optional[Any] = [0] * limit for first_term in range(1 , _UpperCAmelCase ): for n in range(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): lowerCamelCase__ : Optional[Any] = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a lowerCamelCase__ : List[str] = sum(1 for x in frequency[1:limit] if x == 10 ) return count if __name__ == "__main__": print(F"""{solution() = }""")
50
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
0
def A (__A : int , __A : int ) -> bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
0
from argparse import ArgumentParser from .env import EnvironmentCommand def A_ ( ) -> str: UpperCamelCase : List[str] = ArgumentParser("Diffusers CLI tool" , usage="diffusers-cli <command> [<args>]" ) UpperCamelCase : Optional[Any] = parser.add_subparsers(help="diffusers-cli command helpers" ) # Register commands EnvironmentCommand.register_subcommand(_lowerCAmelCase ) # Let's go UpperCamelCase : Optional[int] = parser.parse_args() if not hasattr(_lowerCAmelCase , "func" ): parser.print_help() exit(1 ) # Run UpperCamelCase : str = args.func(_lowerCAmelCase ) service.run() if __name__ == "__main__": main()
52
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig a__ : List[str] =logging.get_logger(__name__) a__ : str ={ '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class snake_case ( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] ="dpt" def __init__( self : int , __A : Optional[int]=7_6_8 , __A : Any=1_2 , __A : Tuple=1_2 , __A : Optional[Any]=3_0_7_2 , __A : List[Any]="gelu" , __A : Tuple=0.0 , __A : List[Any]=0.0 , __A : List[Any]=0.02 , __A : Dict=1e-12 , __A : List[Any]=3_8_4 , __A : List[str]=1_6 , __A : Union[str, Any]=3 , __A : Optional[int]=False , __A : str=True , __A : Union[str, Any]=[2, 5, 8, 1_1] , __A : Any="project" , __A : List[str]=[4, 2, 1, 0.5] , __A : Union[str, Any]=[9_6, 1_9_2, 3_8_4, 7_6_8] , __A : List[str]=2_5_6 , __A : str=-1 , __A : Dict=False , __A : Tuple=True , __A : Union[str, Any]=0.4 , __A : int=2_5_5 , __A : Tuple=0.1 , __A : Optional[Any]=[1, 1_0_2_4, 2_4, 2_4] , __A : List[str]=[0, 1] , __A : Optional[Any]=None , **__A : Tuple , ): super().__init__(**__A ) __UpperCamelCase = hidden_size __UpperCamelCase = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) __UpperCamelCase = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } __UpperCamelCase = BitConfig(**__A ) elif isinstance(__A , __A ): logger.info('Initializing the config with a `BiT` backbone.' ) __UpperCamelCase = BitConfig(**__A ) elif isinstance(__A , __A ): __UpperCamelCase = backbone_config else: raise ValueError( f'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''' ) __UpperCamelCase = backbone_featmap_shape __UpperCamelCase = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = [] __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = initializer_range __UpperCamelCase = layer_norm_eps __UpperCamelCase = image_size __UpperCamelCase = patch_size __UpperCamelCase = num_channels __UpperCamelCase = qkv_bias __UpperCamelCase = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) __UpperCamelCase = readout_type __UpperCamelCase = reassemble_factors __UpperCamelCase = neck_hidden_sizes __UpperCamelCase = fusion_hidden_size __UpperCamelCase = head_in_index __UpperCamelCase = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) __UpperCamelCase = use_auxiliary_head __UpperCamelCase = auxiliary_loss_weight __UpperCamelCase = semantic_loss_ignore_index __UpperCamelCase = semantic_classifier_dropout def _lowerCamelCase ( self : List[Any] ): __UpperCamelCase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: __UpperCamelCase = self.backbone_config.to_dict() __UpperCamelCase = self.__class__.model_type return output
53
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) self.assertTrue(isinstance(dc.token_ids , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
0
'''simple docstring''' 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 a_ : Tuple = 16 a_ : Tuple = 32 def __snake_case ( UpperCAmelCase_ : Accelerator , UpperCAmelCase_ : int = 16 , UpperCAmelCase_ : str = "bert-base-cased" ): lowerCamelCase_ = AutoTokenizer.from_pretrained(UpperCAmelCase_ ) lowerCamelCase_ = load_dataset("glue" , "mrpc" ) def tokenize_function(UpperCAmelCase_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase_ = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCamelCase_ = datasets.map( UpperCAmelCase_ , batched=UpperCAmelCase_ , remove_columns=["idx", "sentence1", "sentence2"] , load_from_cache_file=UpperCAmelCase_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase_ = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(UpperCAmelCase_ : str ): # 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(UpperCAmelCase_ , padding="max_length" , max_length=128 , return_tensors="pt" ) return tokenizer.pad(UpperCAmelCase_ , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. lowerCamelCase_ = DataLoader( tokenized_datasets["train"] , shuffle=UpperCAmelCase_ , collate_fn=UpperCAmelCase_ , batch_size=UpperCAmelCase_ ) lowerCamelCase_ = DataLoader( tokenized_datasets["validation"] , shuffle=UpperCAmelCase_ , collate_fn=UpperCAmelCase_ , batch_size=UpperCAmelCase_ ) return train_dataloader, eval_dataloader def __snake_case ( UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any ): # Initialize accelerator lowerCamelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase_ = config["lr"] lowerCamelCase_ = int(config["num_epochs"] ) lowerCamelCase_ = int(config["seed"] ) lowerCamelCase_ = int(config["batch_size"] ) lowerCamelCase_ = args.model_name_or_path set_seed(UpperCAmelCase_ ) lowerCamelCase_ ,lowerCamelCase_ = get_dataloaders(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase_ = AutoModelForSequenceClassification.from_pretrained(UpperCAmelCase_ , return_dict=UpperCAmelCase_ ) # Instantiate optimizer lowerCamelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCamelCase_ = optimizer_cls(params=model.parameters() , lr=UpperCAmelCase_ ) if accelerator.state.deepspeed_plugin is not None: lowerCamelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ "gradient_accumulation_steps" ] else: lowerCamelCase_ = 1 lowerCamelCase_ = (len(UpperCAmelCase_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCamelCase_ = get_linear_schedule_with_warmup( optimizer=UpperCAmelCase_ , num_warmup_steps=0 , num_training_steps=UpperCAmelCase_ , ) else: lowerCamelCase_ = DummyScheduler(UpperCAmelCase_ , total_num_steps=UpperCAmelCase_ , 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. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = accelerator.prepare( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # We need to keep track of how many total steps we have iterated over lowerCamelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly lowerCamelCase_ = 0 # Now we train the model lowerCamelCase_ = evaluate.load("glue" , "mrpc" ) lowerCamelCase_ = 0 lowerCamelCase_ = {} for epoch in range(UpperCAmelCase_ , UpperCAmelCase_ ): model.train() for step, batch in enumerate(UpperCAmelCase_ ): lowerCamelCase_ = model(**UpperCAmelCase_ ) lowerCamelCase_ = outputs.loss lowerCamelCase_ = loss / gradient_accumulation_steps accelerator.backward(UpperCAmelCase_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() lowerCamelCase_ = 0 for step, batch in enumerate(UpperCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCamelCase_ = model(**UpperCAmelCase_ ) lowerCamelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowerCamelCase_ ,lowerCamelCase_ = accelerator.gather( (predictions, batch["labels"]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(UpperCAmelCase_ ) - 1: lowerCamelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCamelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=UpperCAmelCase_ , references=UpperCAmelCase_ , ) lowerCamelCase_ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , UpperCAmelCase_ ) lowerCamelCase_ = eval_metric["accuracy"] if best_performance < eval_metric["accuracy"]: lowerCamelCase_ = 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(UpperCAmelCase_ , UpperCAmelCase_ ) def __snake_case ( ): lowerCamelCase_ = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." ) parser.add_argument( "--model_name_or_path" , type=UpperCAmelCase_ , default="bert-base-cased" , help="Path to pretrained model or model identifier from huggingface.co/models." , required=UpperCAmelCase_ , ) parser.add_argument( "--output_dir" , type=UpperCAmelCase_ , 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=UpperCAmelCase_ , default=UpperCAmelCase_ , 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=UpperCAmelCase_ , default=3 , help="Number of train epochs." , ) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = {"lr": 2E-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} training_function(UpperCAmelCase_ , UpperCAmelCase_ ) if __name__ == "__main__": main()
55
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a : List[str] = { 'configuration_pix2struct': [ 'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Pix2StructConfig', 'Pix2StructTextConfig', 'Pix2StructVisionConfig', ], 'processing_pix2struct': ['Pix2StructProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Union[str, Any] = ['Pix2StructImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Union[str, Any] = [ 'PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Pix2StructPreTrainedModel', 'Pix2StructForConditionalGeneration', 'Pix2StructVisionModel', 'Pix2StructTextModel', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys a : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
56
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
0
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = SwinConfig(image_size=192 ) if "base" in model_name: __lowerCAmelCase = 6 __lowerCAmelCase = 128 __lowerCAmelCase = (2, 2, 18, 2) __lowerCAmelCase = (4, 8, 16, 32) elif "large" in model_name: __lowerCAmelCase = 12 __lowerCAmelCase = 192 __lowerCAmelCase = (2, 2, 18, 2) __lowerCAmelCase = (6, 12, 24, 48) else: raise ValueError("Model not supported, only supports base and large variants" ) __lowerCAmelCase = window_size __lowerCAmelCase = embed_dim __lowerCAmelCase = depths __lowerCAmelCase = num_heads return config def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' if "encoder.mask_token" in name: __lowerCAmelCase = name.replace("encoder.mask_token" , "embeddings.mask_token" ) if "encoder.patch_embed.proj" in name: __lowerCAmelCase = name.replace("encoder.patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "encoder.patch_embed.norm" in name: __lowerCAmelCase = name.replace("encoder.patch_embed.norm" , "embeddings.norm" ) if "attn.proj" in name: __lowerCAmelCase = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: __lowerCAmelCase = name.replace("attn" , "attention.self" ) if "norm1" in name: __lowerCAmelCase = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: __lowerCAmelCase = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: __lowerCAmelCase = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: __lowerCAmelCase = name.replace("mlp.fc2" , "output.dense" ) if name == "encoder.norm.weight": __lowerCAmelCase = "layernorm.weight" if name == "encoder.norm.bias": __lowerCAmelCase = "layernorm.bias" if "decoder" in name: pass else: __lowerCAmelCase = "swin." + name return name def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' for key in orig_state_dict.copy().keys(): __lowerCAmelCase = orig_state_dict.pop(_UpperCamelCase ) if "attn_mask" in key: pass elif "qkv" in key: __lowerCAmelCase = key.split("." ) __lowerCAmelCase = int(key_split[2] ) __lowerCAmelCase = int(key_split[4] ) __lowerCAmelCase = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __lowerCAmelCase = val[:dim, :] __lowerCAmelCase = val[ dim : dim * 2, : ] __lowerCAmelCase = val[-dim:, :] else: __lowerCAmelCase = val[ :dim ] __lowerCAmelCase = val[ dim : dim * 2 ] __lowerCAmelCase = val[ -dim: ] else: __lowerCAmelCase = val return orig_state_dict def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = torch.load(_UpperCamelCase , map_location="cpu" )["model"] __lowerCAmelCase = get_swin_config(_UpperCamelCase ) __lowerCAmelCase = SwinForMaskedImageModeling(_UpperCamelCase ) model.eval() __lowerCAmelCase = convert_state_dict(_UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) __lowerCAmelCase = "http://images.cocodataset.org/val2017/000000039769.jpg" __lowerCAmelCase = ViTImageProcessor(size={"height": 192, "width": 192} ) __lowerCAmelCase = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) __lowerCAmelCase = image_processor(images=_UpperCamelCase , return_tensors="pt" ) with torch.no_grad(): __lowerCAmelCase = model(**_UpperCamelCase ).logits print(outputs.keys() ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCamelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: print(f"Pushing model and image processor for {model_name} to hub" ) model.push_to_hub(f"microsoft/{model_name}" ) image_processor.push_to_hub(f"microsoft/{model_name}" ) if __name__ == "__main__": A : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="swin-base-simmim-window6-192", type=str, choices=["swin-base-simmim-window6-192", "swin-large-simmim-window12-192"], help="Name of the Swin SimMIM model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default="/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth", type=str, help="Path to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) A : Optional[int] = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
57
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json""", } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''lxmert''' UpperCamelCase = {} def __init__( self , A=3_0522 , A=768 , A=12 , A=9500 , A=1600 , A=400 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=2 , A=0.02 , A=1e-12 , A=9 , A=5 , A=5 , A=2048 , A=4 , A=6.67 , A=True , A=True , A=True , A=True , A=True , A=True , A=True , **A , ) -> int: _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = num_qa_labels _SCREAMING_SNAKE_CASE = num_object_labels _SCREAMING_SNAKE_CASE = num_attr_labels _SCREAMING_SNAKE_CASE = l_layers _SCREAMING_SNAKE_CASE = x_layers _SCREAMING_SNAKE_CASE = r_layers _SCREAMING_SNAKE_CASE = visual_feat_dim _SCREAMING_SNAKE_CASE = visual_pos_dim _SCREAMING_SNAKE_CASE = visual_loss_normalizer _SCREAMING_SNAKE_CASE = task_matched _SCREAMING_SNAKE_CASE = task_mask_lm _SCREAMING_SNAKE_CASE = task_obj_predict _SCREAMING_SNAKE_CASE = task_qa _SCREAMING_SNAKE_CASE = visual_obj_loss _SCREAMING_SNAKE_CASE = visual_attr_loss _SCREAMING_SNAKE_CASE = visual_feat_loss _SCREAMING_SNAKE_CASE = {"""vision""": r_layers, """cross_encoder""": x_layers, """language""": l_layers} super().__init__(**A )
58
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = update_image_and_anno( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , filter_scale=__SCREAMING_SNAKE_CASE , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : int = F'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(__SCREAMING_SNAKE_CASE ) with open(F'''{file_root}.txt''' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__SCREAMING_SNAKE_CASE ) labels.append(__SCREAMING_SNAKE_CASE ) return img_paths, labels def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : tuple[int, int] , __SCREAMING_SNAKE_CASE : tuple[float, float] , __SCREAMING_SNAKE_CASE : float = 0.0 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ 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 snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
0
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str , **__lowerCamelCase : Optional[int] ): snake_case : int = AutoConfig.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) snake_case : Any = AutoModelForSeqaSeqLM.from_config(__lowerCamelCase ) model.save_pretrained(__lowerCamelCase ) AutoTokenizer.from_pretrained(__lowerCamelCase ).save_pretrained(__lowerCamelCase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
59
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
0