code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def A_ ( _lowercase, _lowercase, _lowercase, _lowercase, _lowercase ): '''simple docstring''' snake_case_ :Tuple = StableDiffusionPipeline.from_pretrained(_lowercase, torch_dtype=torch.floataa ) # load LoRA weight from .safetensors snake_case_ :List[Any] = load_file(_lowercase ) snake_case_ :Any = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: snake_case_ :List[str] = key.split(""".""" )[0].split(LORA_PREFIX_TEXT_ENCODER + """_""" )[-1].split("""_""" ) snake_case_ :str = pipeline.text_encoder else: snake_case_ :List[str] = key.split(""".""" )[0].split(LORA_PREFIX_UNET + """_""" )[-1].split("""_""" ) snake_case_ :Dict = pipeline.unet # find the target layer snake_case_ :List[Any] = layer_infos.pop(0 ) while len(_lowercase ) > -1: try: snake_case_ :List[Any] = curr_layer.__getattr__(_lowercase ) if len(_lowercase ) > 0: snake_case_ :Dict = layer_infos.pop(0 ) elif len(_lowercase ) == 0: break except Exception: if len(_lowercase ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: snake_case_ :Tuple = layer_infos.pop(0 ) snake_case_ :Optional[int] = [] if "lora_down" in key: pair_keys.append(key.replace("""lora_down""", """lora_up""" ) ) pair_keys.append(_lowercase ) else: pair_keys.append(_lowercase ) pair_keys.append(key.replace("""lora_up""", """lora_down""" ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: snake_case_ :str = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) snake_case_ :Tuple = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_lowercase, _lowercase ).unsqueeze(2 ).unsqueeze(3 ) else: snake_case_ :List[str] = state_dict[pair_keys[0]].to(torch.floataa ) snake_case_ :List[Any] = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_lowercase, _lowercase ) # update visited list for item in pair_keys: visited.append(_lowercase ) return pipeline if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument( "--base_model_path", default=None, type=str, required=True, help="Path to the base model in diffusers format." ) parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--lora_prefix_unet", default="lora_unet", type=str, help="The prefix of UNet weight in safetensors" ) parser.add_argument( "--lora_prefix_text_encoder", default="lora_te", type=str, help="The prefix of text encoder weight in safetensors", ) parser.add_argument("--alpha", default=0.75, type=float, help="The merging ratio in W = W0 + alpha * deltaW") parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not." ) parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") __a = parser.parse_args() __a = args.base_model_path __a = args.checkpoint_path __a = args.dump_path __a = args.lora_prefix_unet __a = args.lora_prefix_text_encoder __a = args.alpha __a = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) __a = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
66
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __a = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ "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 __a = _LazyModule(__name__, globals()["__file__"], _import_structure)
66
1
"""simple docstring""" import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowerCAmelCase__ : Dict ='''Usage of script: script_name <size_of_canvas:int>''' lowerCAmelCase__ : Dict =[0] * 100 + [1] * 10 random.shuffle(choice) def __lowercase ( a__ ) -> list[list[bool]]: __SCREAMING_SNAKE_CASE = [[False for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] return canvas def __lowercase ( a__ ) -> None: for i, row in enumerate(__lowerCAmelCase ): for j, _ in enumerate(__lowerCAmelCase ): __SCREAMING_SNAKE_CASE = bool(random.getrandbits(1 ) ) def __lowercase ( a__ ) -> list[list[bool]]: __SCREAMING_SNAKE_CASE = np.array(__lowerCAmelCase ) __SCREAMING_SNAKE_CASE = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__lowerCAmelCase ): for c, pt in enumerate(__lowerCAmelCase ): __SCREAMING_SNAKE_CASE = __judge_point( __lowerCAmelCase , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __SCREAMING_SNAKE_CASE = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __SCREAMING_SNAKE_CASE = current_canvas.tolist() return return_canvas def __lowercase ( a__ , a__ ) -> bool: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __SCREAMING_SNAKE_CASE = pt if pt: if alive < 2: __SCREAMING_SNAKE_CASE = False elif alive == 2 or alive == 3: __SCREAMING_SNAKE_CASE = True elif alive > 3: __SCREAMING_SNAKE_CASE = False else: if alive == 3: __SCREAMING_SNAKE_CASE = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowerCAmelCase__ : str =int(sys.argv[1]) # main working structure of this module. lowerCAmelCase__ : List[str] =create_canvas(canvas_size) seed(c) lowerCAmelCase__ , lowerCAmelCase__ : Tuple =plt.subplots() fig.show() lowerCAmelCase__ : Optional[int] =ListedColormap(['''w''', '''k''']) try: while True: lowerCAmelCase__ : str =run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
353
def __lowercase ( a__ = 10_00 ) -> int: __SCREAMING_SNAKE_CASE = -1 __SCREAMING_SNAKE_CASE = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c __SCREAMING_SNAKE_CASE = (n * n - 2 * a * n) // (2 * n - 2 * a) __SCREAMING_SNAKE_CASE = n - a - b if c * c == (a * a + b * b): __SCREAMING_SNAKE_CASE = a * b * c if candidate >= product: __SCREAMING_SNAKE_CASE = candidate return product if __name__ == "__main__": print(F'''{solution() = }''')
118
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar _UpperCamelCase = TypeVar('''T''') _UpperCamelCase = TypeVar('''U''') class _A ( Generic[T, U] ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : Tuple = key __UpperCAmelCase : List[str] = val __UpperCAmelCase : DoubleLinkedListNode[T, U] | None = None __UpperCAmelCase : DoubleLinkedListNode[T, U] | None = None def __repr__( self ) -> str: '''simple docstring''' return ( f'Node: key: {self.key}, val: {self.val}, ' f'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class _A ( Generic[T, U] ): def __init__( self ) -> None: '''simple docstring''' __UpperCAmelCase : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase , __UpperCAmelCase : List[Any] = self.rear, self.head def __repr__( self ) -> str: '''simple docstring''' __UpperCAmelCase : int = ["""DoubleLinkedList"""] __UpperCAmelCase : Dict = self.head while node.next is not None: rep.append(str(__UpperCAmelCase ) ) __UpperCAmelCase : str = node.next rep.append(str(self.rear ) ) return ",\n ".join(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None __UpperCAmelCase : Dict = node __UpperCAmelCase : str = previous __UpperCAmelCase : Dict = node __UpperCAmelCase : Any = self.rear def __A ( self , __UpperCAmelCase ) -> DoubleLinkedListNode[T, U] | None: '''simple docstring''' if node.prev is None or node.next is None: return None __UpperCAmelCase : Optional[int] = node.next __UpperCAmelCase : List[Any] = node.prev __UpperCAmelCase : Any = None __UpperCAmelCase : str = None return node class _A ( Generic[T, U] ): _SCREAMING_SNAKE_CASE : dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__( self , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : DoubleLinkedList[T, U] = DoubleLinkedList() __UpperCAmelCase : List[str] = capacity __UpperCAmelCase : int = 0 __UpperCAmelCase : Any = 0 __UpperCAmelCase : Dict = 0 __UpperCAmelCase : dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__( self ) -> str: '''simple docstring''' return ( f'CacheInfo(hits={self.hits}, misses={self.miss}, ' f'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self , __UpperCAmelCase ) -> bool: '''simple docstring''' return key in self.cache def __A ( self , __UpperCAmelCase ) -> U | None: '''simple docstring''' # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 __UpperCAmelCase : DoubleLinkedListNode[T, U] = self.cache[key] __UpperCAmelCase : Tuple = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(__UpperCAmelCase ) return node.val self.miss += 1 return None def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity __UpperCAmelCase : List[Any] = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(__UpperCAmelCase ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 __UpperCAmelCase : str = DoubleLinkedListNode(__UpperCAmelCase , __UpperCAmelCase ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value __UpperCAmelCase : Tuple = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list __UpperCAmelCase : List[str] = value self.list.add(__UpperCAmelCase ) @classmethod def __A ( cls , __UpperCAmelCase = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: '''simple docstring''' def cache_decorator_inner(__UpperCAmelCase ) -> Callable[..., U]: def cache_decorator_wrapper(*__UpperCAmelCase ) -> U: if func not in cls.decorator_function_to_instance_map: __UpperCAmelCase : Optional[Any] = LRUCache(__UpperCAmelCase ) __UpperCAmelCase : int = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: __UpperCAmelCase : Tuple = func(*__UpperCAmelCase ) cls.decorator_function_to_instance_map[func].put(args[0] , __UpperCAmelCase ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(__UpperCAmelCase , """cache_info""" , __UpperCAmelCase ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
254
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version _UpperCamelCase = get_logger(__name__) class _A : _SCREAMING_SNAKE_CASE : Dict = "dummy_data" _SCREAMING_SNAKE_CASE : int = "datasets" _SCREAMING_SNAKE_CASE : Union[str, Any] = False def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = True , __UpperCAmelCase = None , ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : int = 0 __UpperCAmelCase : Tuple = dataset_name __UpperCAmelCase : List[Any] = cache_dir __UpperCAmelCase : List[Any] = use_local_dummy_data __UpperCAmelCase : str = config # download_callbacks take a single url as input __UpperCAmelCase : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __UpperCAmelCase : Tuple = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __UpperCAmelCase : Dict = str(__UpperCAmelCase ) # to be downloaded __UpperCAmelCase : Any = None __UpperCAmelCase : List[str] = None @property def __A ( self ) -> Dict: '''simple docstring''' if self._dummy_file is None: __UpperCAmelCase : Dict = self.download_dummy_data() return self._dummy_file @property def __A ( self ) -> Any: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("""dummy""" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("""dummy""" , self.version_name ) @property def __A ( self ) -> Optional[Any]: '''simple docstring''' return os.path.join(self.dummy_data_folder , """dummy_data.zip""" ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Tuple = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __UpperCAmelCase : Tuple = cached_path( __UpperCAmelCase , cache_dir=self.cache_dir , extract_compressed_file=__UpperCAmelCase , force_extract=__UpperCAmelCase ) return os.path.join(__UpperCAmelCase , self.dummy_file_name ) @property def __A ( self ) -> Any: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __A ( self ) -> List[Any]: '''simple docstring''' if self._bucket_url is None: __UpperCAmelCase : Optional[Any] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , """/""" ) ) return self._bucket_url @property def __A ( self ) -> Dict: '''simple docstring''' # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , """/""" ).split("""/""" )[:-1] ) def __A ( self , __UpperCAmelCase , *__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested __UpperCAmelCase : Dict = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __UpperCAmelCase : Optional[int] = self.dummy_file_name # special case when data_url is a dict if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.create_dummy_data_dict(__UpperCAmelCase , __UpperCAmelCase ) elif isinstance(__UpperCAmelCase , (list, tuple) ): return self.create_dummy_data_list(__UpperCAmelCase , __UpperCAmelCase ) else: return self.create_dummy_data_single(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase , *__UpperCAmelCase ) -> Dict: '''simple docstring''' return self.download_and_extract(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' return self.download_and_extract(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' return path def __A ( self ) -> List[Any]: '''simple docstring''' return {} def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : str = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__UpperCAmelCase , __UpperCAmelCase ): for single_url in single_urls: download_callback(__UpperCAmelCase ) else: __UpperCAmelCase : Union[str, Any] = single_urls download_callback(__UpperCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__UpperCAmelCase , __UpperCAmelCase ): __UpperCAmelCase : str = [os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(Path(__UpperCAmelCase ).name ) ) for x in single_urls] else: __UpperCAmelCase : List[str] = single_urls __UpperCAmelCase : Any = os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(Path(__UpperCAmelCase ).name ) ) __UpperCAmelCase : Union[str, Any] = value # make sure that values are unique if all(isinstance(__UpperCAmelCase , __UpperCAmelCase ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __UpperCAmelCase : Tuple = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __UpperCAmelCase : Tuple = all(bool(re.findall("""[0-9]{3,}-of-[0-9]{3,}""" , __UpperCAmelCase ) ) for url in data_url ) __UpperCAmelCase : str = all( url.startswith("""https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed""" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __UpperCAmelCase : int = [data_url[0]] * len(__UpperCAmelCase ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__UpperCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __UpperCAmelCase : List[str] = os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(single_url.split("""/""" )[-1] ) ) dummy_data_list.append(__UpperCAmelCase ) return dummy_data_list def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(__UpperCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __UpperCAmelCase : List[str] = os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(data_url.split("""/""" )[-1] ) ) if os.path.exists(__UpperCAmelCase ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __A ( self ) -> Tuple: '''simple docstring''' pass def __A ( self ) -> int: '''simple docstring''' pass def __A ( self , __UpperCAmelCase ) -> Any: '''simple docstring''' def _iter_archive_members(__UpperCAmelCase ): # this preserves the order of the members inside the ZIP archive __UpperCAmelCase : Dict = Path(self.dummy_file ).parent __UpperCAmelCase : Dict = path.relative_to(__UpperCAmelCase ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __UpperCAmelCase : List[str] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__UpperCAmelCase ) __UpperCAmelCase : Any = Path(__UpperCAmelCase ) __UpperCAmelCase : int = _iter_archive_members(__UpperCAmelCase ) if self.use_local_dummy_data else path.rglob("""*""" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((""".""", """__""") ): yield file_path.relative_to(__UpperCAmelCase ).as_posix(), file_path.open("""rb""" ) def __A ( self , __UpperCAmelCase ) -> Dict: '''simple docstring''' if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): __UpperCAmelCase : List[Any] = [paths] for path in paths: if os.path.isfile(__UpperCAmelCase ): if os.path.basename(__UpperCAmelCase ).startswith((""".""", """__""") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__UpperCAmelCase ): if os.path.basename(__UpperCAmelCase ).startswith((""".""", """__""") ): continue dirnames.sort() for filename in sorted(__UpperCAmelCase ): if filename.startswith((""".""", """__""") ): continue yield os.path.join(__UpperCAmelCase , __UpperCAmelCase )
254
1
from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowerCamelCase = logging.get_logger(__name__) class _a ( _lowercase): _a : int = ['''input_values''', '''padding_mask'''] def __init__( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : int = 1 , _SCREAMING_SNAKE_CASE : int = 2_4000 , _SCREAMING_SNAKE_CASE : float = 0.0 , _SCREAMING_SNAKE_CASE : float = None , _SCREAMING_SNAKE_CASE : float = None , **_SCREAMING_SNAKE_CASE : str , )-> Dict: super().__init__(feature_size=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , padding_value=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : Dict = chunk_length_s lowerCAmelCase__ : int = overlap @property def UpperCAmelCase__( self : int )-> Optional[int]: if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def UpperCAmelCase__( self : Union[str, Any] )-> Optional[int]: if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self : Tuple , _SCREAMING_SNAKE_CASE : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , _SCREAMING_SNAKE_CASE : Optional[Union[bool, str, PaddingStrategy]] = None , _SCREAMING_SNAKE_CASE : Optional[bool] = False , _SCREAMING_SNAKE_CASE : Optional[int] = None , _SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE : Optional[int] = None , )-> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' F' {self.sampling_rate}. Please make sure that the provided audio input was sampled with' F' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) if padding and truncation: raise ValueError('''Both padding and truncation were set. Make sure you only set one.''' ) elif padding is None: # by default let's pad the inputs lowerCAmelCase__ : Union[str, Any] = True lowerCAmelCase__ : Any = bool( isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCAmelCase__ : str = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): lowerCAmelCase__ : str = np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) elif isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): lowerCAmelCase__ : Any = raw_audio.astype(np.floataa ) # always return batch if not is_batched: lowerCAmelCase__ : Any = [np.asarray(_SCREAMING_SNAKE_CASE ).T] # verify inputs are valid for idx, example in enumerate(_SCREAMING_SNAKE_CASE ): if example.ndim > 2: raise ValueError(F'Expected input shape (channels, length) but got shape {example.shape}' ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(F'Expected mono audio but example has {example.shape[-1]} channels' ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(F'Expected stereo audio but example has {example.shape[-1]} channels' ) lowerCAmelCase__ : Any = None lowerCAmelCase__ : Dict = BatchFeature({'''input_values''': raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: lowerCAmelCase__ : str = min(array.shape[0] for array in raw_audio ) lowerCAmelCase__ : Optional[Any] = int(np.floor(max_length / self.chunk_stride ) ) lowerCAmelCase__ : Any = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: lowerCAmelCase__ : Union[str, Any] = max(array.shape[0] for array in raw_audio ) lowerCAmelCase__ : Optional[Any] = int(np.ceil(max_length / self.chunk_stride ) ) lowerCAmelCase__ : Any = (nb_step - 1) * self.chunk_stride + self.chunk_length lowerCAmelCase__ : str = '''max_length''' else: lowerCAmelCase__ : Tuple = input_values # normal padding on batch if padded_inputs is None: lowerCAmelCase__ : Union[str, Any] = self.pad( _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) if padding: lowerCAmelCase__ : Optional[Any] = padded_inputs.pop('''attention_mask''' ) lowerCAmelCase__ : Union[str, Any] = [] for example in padded_inputs.pop('''input_values''' ): if self.feature_size == 1: lowerCAmelCase__ : Optional[int] = example[..., None] input_values.append(example.T ) lowerCAmelCase__ : Dict = input_values if return_tensors is not None: lowerCAmelCase__ : Any = padded_inputs.convert_to_tensors(_SCREAMING_SNAKE_CASE ) return padded_inputs
211
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = 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'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = OrderedDict( [ # Model for Image-classsification ('''beit''', '''FlaxBeitForImageClassification'''), ('''regnet''', '''FlaxRegNetForImageClassification'''), ('''resnet''', '''FlaxResNetForImageClassification'''), ('''vit''', '''FlaxViTForImageClassification'''), ] ) lowerCamelCase = OrderedDict( [ ('''vision-encoder-decoder''', '''FlaxVisionEncoderDecoderModel'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = 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'''), ] ) lowerCamelCase = OrderedDict( [ ('''bert''', '''FlaxBertForNextSentencePrediction'''), ] ) lowerCamelCase = OrderedDict( [ ('''speech-encoder-decoder''', '''FlaxSpeechEncoderDecoderModel'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ] ) lowerCamelCase = OrderedDict( [ ('''whisper''', '''FlaxWhisperForAudioClassification'''), ] ) lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class _a ( _BaseAutoModelClass): _a : List[str] = FLAX_MODEL_MAPPING lowerCamelCase = auto_class_update(FlaxAutoModel) class _a ( _BaseAutoModelClass): _a : Union[str, Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING lowerCamelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc='''pretraining''') class _a ( _BaseAutoModelClass): _a : Optional[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING lowerCamelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc='''causal language modeling''') class _a ( _BaseAutoModelClass): _a : Tuple = FLAX_MODEL_FOR_MASKED_LM_MAPPING lowerCamelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='''masked language modeling''') class _a ( _BaseAutoModelClass): _a : Dict = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCamelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='''sequence-to-sequence language modeling''', checkpoint_for_example='''t5-base''' ) class _a ( _BaseAutoModelClass): _a : Union[str, Any] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowerCamelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='''sequence classification''' ) class _a ( _BaseAutoModelClass): _a : str = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING lowerCamelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='''question answering''') class _a ( _BaseAutoModelClass): _a : Union[str, Any] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='''token classification''' ) class _a ( _BaseAutoModelClass): _a : List[Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING lowerCamelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='''multiple choice''') class _a ( _BaseAutoModelClass): _a : Any = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING lowerCamelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='''next sentence prediction''' ) class _a ( _BaseAutoModelClass): _a : List[Any] = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowerCamelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc='''image classification''' ) class _a ( _BaseAutoModelClass): _a : List[Any] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING lowerCamelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='''vision-to-text modeling''') class _a ( _BaseAutoModelClass): _a : Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING lowerCamelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='''sequence-to-sequence speech-to-text modeling''' )
211
1
def lowercase ( SCREAMING_SNAKE_CASE__ : str ) -> str: _snake_case : int = 1 _snake_case : Dict = 2 while i * i <= n: _snake_case : Union[str, Any] = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def lowercase ( ) -> List[str]: _snake_case : Tuple = 1 _snake_case : Dict = 1 while True: i += 1 t_num += i if count_divisors(__A ) > 500: break return t_num if __name__ == "__main__": print(solution())
317
'''simple docstring''' from collections import defaultdict from math import gcd def SCREAMING_SNAKE_CASE__ ( __A = 1_500_000 ) -> int: _snake_case = defaultdict(__A ) _snake_case = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , __A , 2 ): if gcd(__A , __A ) > 1: continue _snake_case = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(__A , limit + 1 , __A ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
42
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : int = { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json" # See all FNet models at https://huggingface.co/models?filter=fnet } class _SCREAMING_SNAKE_CASE ( snake_case__ ): snake_case__ : Tuple = """fnet""" def __init__( self : Tuple , __lowerCamelCase : str=32_000 , __lowerCamelCase : List[str]=768 , __lowerCamelCase : List[str]=12 , __lowerCamelCase : str=3_072 , __lowerCamelCase : List[str]="gelu_new" , __lowerCamelCase : str=0.1 , __lowerCamelCase : Optional[Any]=512 , __lowerCamelCase : Any=4 , __lowerCamelCase : str=0.02 , __lowerCamelCase : List[Any]=1E-12 , __lowerCamelCase : int=False , __lowerCamelCase : Tuple=512 , __lowerCamelCase : int=3 , __lowerCamelCase : Dict=1 , __lowerCamelCase : List[Any]=2 , **__lowerCamelCase : Tuple , ): super().__init__(pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) UpperCamelCase :Optional[Any] = vocab_size UpperCamelCase :List[str] = max_position_embeddings UpperCamelCase :List[Any] = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :Tuple = initializer_range UpperCamelCase :Union[str, Any] = type_vocab_size UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Optional[Any] = use_tpu_fourier_optimizations UpperCamelCase :List[Any] = tpu_short_seq_length
365
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] ) -> Any: """simple docstring""" return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : dict[int, list[int]] ) -> list[tuple[int, int]]: """simple docstring""" UpperCamelCase :Any = 0 UpperCamelCase :int = len(__magic_name__ ) # No of vertices in graph UpperCamelCase :int = [0] * n UpperCamelCase :Union[str, Any] = [False] * n def dfs(__magic_name__ : str , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] ): UpperCamelCase :Any = True UpperCamelCase :str = id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(__magic_name__ , __magic_name__ , __magic_name__ , id_ ) UpperCamelCase :Dict = min(low[at] , low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge UpperCamelCase :int = min(low[at] , low[to] ) UpperCamelCase :list[tuple[int, int]] = [] for i in range(__magic_name__ ): if not visited[i]: dfs(__magic_name__ , -1 , __magic_name__ , id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
62
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 = logging.get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = SwinConfig( embed_dim=1_92 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['''stage2''', '''stage3''', '''stage4'''] , ) lowercase__ = DetaConfig( backbone_config=SCREAMING_SNAKE_CASE , num_queries=9_00 , encoder_ffn_dim=20_48 , decoder_ffn_dim=20_48 , num_feature_levels=5 , assign_first_stage=SCREAMING_SNAKE_CASE , with_box_refine=SCREAMING_SNAKE_CASE , two_stage=SCREAMING_SNAKE_CASE , ) # set labels lowercase__ = '''huggingface/label-files''' if "o365" in model_name: lowercase__ = 3_66 lowercase__ = '''object365-id2label.json''' else: lowercase__ = 91 lowercase__ = '''coco-detection-id2label.json''' lowercase__ = num_labels lowercase__ = json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='''dataset''' ) ) , '''r''' ) ) lowercase__ = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} lowercase__ = idalabel lowercase__ = {v: k for k, v in idalabel.items()} return config def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [] # 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 _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = dct.pop(SCREAMING_SNAKE_CASE ) lowercase__ = val def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): lowercase__ = 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) lowercase__ = state_dict.pop(f'backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight' ) lowercase__ = 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 lowercase__ = in_proj_weight[:dim, :] lowercase__ = in_proj_bias[: dim] lowercase__ = in_proj_weight[ dim : dim * 2, : ] lowercase__ = in_proj_bias[ dim : dim * 2 ] lowercase__ = in_proj_weight[ -dim :, : ] lowercase__ = in_proj_bias[-dim :] # fmt: on def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention lowercase__ = state_dict.pop(f'transformer.decoder.layers.{i}.self_attn.in_proj_weight' ) lowercase__ = 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 lowercase__ = in_proj_weight[:hidden_size, :] lowercase__ = in_proj_bias[:hidden_size] lowercase__ = in_proj_weight[ hidden_size : hidden_size * 2, : ] lowercase__ = in_proj_bias[hidden_size : hidden_size * 2] lowercase__ = in_proj_weight[-hidden_size:, :] lowercase__ = in_proj_bias[-hidden_size:] def _a ( ): """simple docstring""" lowercase__ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = get_deta_config(SCREAMING_SNAKE_CASE ) # load original state dict if model_name == "deta-swin-large": lowercase__ = hf_hub_download(repo_id='''nielsr/deta-checkpoints''' , filename='''adet_swin_ft.pth''' ) elif model_name == "deta-swin-large-o365": lowercase__ = 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' ) lowercase__ = torch.load(SCREAMING_SNAKE_CASE , map_location='''cpu''' )['''model'''] # original state dict for name, param in state_dict.items(): print(SCREAMING_SNAKE_CASE , param.shape ) # rename keys lowercase__ = create_rename_keys(SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) read_in_swin_q_k_v(SCREAMING_SNAKE_CASE , config.backbone_config ) read_in_decoder_q_k_v(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: lowercase__ = state_dict.pop(SCREAMING_SNAKE_CASE ) lowercase__ = val if "input_proj" in key: lowercase__ = state_dict.pop(SCREAMING_SNAKE_CASE ) lowercase__ = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: lowercase__ = state_dict.pop(SCREAMING_SNAKE_CASE ) lowercase__ = val # finally, create HuggingFace model and load state dict lowercase__ = DetaForObjectDetection(SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) model.eval() lowercase__ = '''cuda''' if torch.cuda.is_available() else '''cpu''' model.to(SCREAMING_SNAKE_CASE ) # load image processor lowercase__ = DetaImageProcessor(format='''coco_detection''' ) # verify our conversion on image lowercase__ = prepare_img() lowercase__ = processor(images=SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) lowercase__ = encoding['''pixel_values'''] lowercase__ = model(pixel_values.to(SCREAMING_SNAKE_CASE ) ) # verify logits print('''Logits:''' , outputs.logits[0, :3, :3] ) print('''Boxes:''' , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": lowercase__ = torch.tensor( [[-7.6_308, -2.8_485, -5.3_737], [-7.2_037, -4.5_505, -4.8_027], [-7.2_943, -4.2_611, -4.6_617]] ) lowercase__ = torch.tensor([[0.4_987, 0.4_969, 0.9_999], [0.2_549, 0.5_498, 0.4_805], [0.5_498, 0.2_757, 0.0_569]] ) elif model_name == "deta-swin-large-o365": lowercase__ = torch.tensor( [[-8.0_122, -3.5_720, -4.9_717], [-8.1_547, -3.6_886, -4.6_389], [-7.6_610, -3.6_194, -5.0_134]] ) lowercase__ = torch.tensor([[0.2_523, 0.5_549, 0.4_881], [0.7_715, 0.4_149, 0.4_601], [0.5_503, 0.2_753, 0.0_575]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(SCREAMING_SNAKE_CASE ) , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(SCREAMING_SNAKE_CASE ) , 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(SCREAMING_SNAKE_CASE ).mkdir(exist_ok=SCREAMING_SNAKE_CASE ) model.save_pretrained(SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) # 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 = 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 = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
110
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __snake_case( _lowerCAmelCase ) -> List[Any]: snake_case__ : Dict = SwinConfig() snake_case__ : Optional[Any] = swin_name.split("""_""" ) snake_case__ : Any = name_split[1] snake_case__ : List[Any] = int(name_split[4] ) snake_case__ : int = int(name_split[3][-1] ) if model_size == "tiny": snake_case__ : List[Any] = 96 snake_case__ : int = (2, 2, 6, 2) snake_case__ : int = (3, 6, 12, 24) elif model_size == "small": snake_case__ : Union[str, Any] = 96 snake_case__ : Optional[Any] = (2, 2, 18, 2) snake_case__ : str = (3, 6, 12, 24) elif model_size == "base": snake_case__ : Dict = 128 snake_case__ : str = (2, 2, 18, 2) snake_case__ : Dict = (4, 8, 16, 32) else: snake_case__ : List[str] = 192 snake_case__ : str = (2, 2, 18, 2) snake_case__ : List[Any] = (6, 12, 24, 48) if "in22k" in swin_name: snake_case__ : str = 21_841 else: snake_case__ : List[str] = 1_000 snake_case__ : int = """huggingface/label-files""" snake_case__ : Any = """imagenet-1k-id2label.json""" snake_case__ : List[Any] = json.load(open(hf_hub_download(_lowerCAmelCase , _lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : Dict = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} snake_case__ : Optional[int] = idalabel snake_case__ : List[Any] = {v: k for k, v in idalabel.items()} snake_case__ : List[Any] = img_size snake_case__ : Dict = num_classes snake_case__ : Dict = embed_dim snake_case__ : Optional[int] = depths snake_case__ : int = num_heads snake_case__ : Optional[int] = window_size return config def __snake_case( _lowerCAmelCase ) -> Dict: if "patch_embed.proj" in name: snake_case__ : List[str] = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: snake_case__ : int = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: snake_case__ : str = """encoder.""" + name if "attn.proj" in name: snake_case__ : List[str] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: snake_case__ : Tuple = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: snake_case__ : List[str] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: snake_case__ : Optional[Any] = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: snake_case__ : Union[str, Any] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: snake_case__ : Dict = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": snake_case__ : Tuple = """layernorm.weight""" if name == "norm.bias": snake_case__ : Union[str, Any] = """layernorm.bias""" if "head" in name: snake_case__ : Optional[int] = name.replace("""head""" , """classifier""" ) else: snake_case__ : List[str] = """swin.""" + name return name def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: for key in orig_state_dict.copy().keys(): snake_case__ : Optional[int] = orig_state_dict.pop(_lowerCAmelCase ) if "mask" in key: continue elif "qkv" in key: snake_case__ : Dict = key.split(""".""" ) snake_case__ : Optional[int] = int(key_split[1] ) snake_case__ : Union[str, Any] = int(key_split[3] ) snake_case__ : List[Any] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case__ : Optional[Any] = val[:dim, :] snake_case__ : Tuple = val[ dim : dim * 2, : ] snake_case__ : Dict = val[-dim:, :] else: snake_case__ : Tuple = val[ :dim ] snake_case__ : int = val[ dim : dim * 2 ] snake_case__ : int = val[ -dim: ] else: snake_case__ : Union[str, Any] = val return orig_state_dict def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> int: snake_case__ : Optional[int] = timm.create_model(_lowerCAmelCase , pretrained=_lowerCAmelCase ) timm_model.eval() snake_case__ : Optional[int] = get_swin_config(_lowerCAmelCase ) snake_case__ : Optional[Any] = SwinForImageClassification(_lowerCAmelCase ) model.eval() snake_case__ : str = convert_state_dict(timm_model.state_dict() , _lowerCAmelCase ) model.load_state_dict(_lowerCAmelCase ) snake_case__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Dict = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) snake_case__ : Dict = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ) snake_case__ : Optional[int] = image_processor(images=_lowerCAmelCase , return_tensors="""pt""" ) snake_case__ : Optional[Any] = timm_model(inputs["""pixel_values"""] ) snake_case__ : str = model(**_lowerCAmelCase ).logits assert torch.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=1e-3 ) print(f"Saving model {swin_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_lowerCAmelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swin_name", default="swin_tiny_patch4_window7_224", type=str, help="Name of the Swin 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." ) __a = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
35
0
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html A__ : Any = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class lowercase__ : _UpperCAmelCase :int = PegasusConfig _UpperCAmelCase :Optional[Any] = {} _UpperCAmelCase :Tuple = "gelu" def __init__( self : Optional[int] , snake_case__ : Optional[int] , snake_case__ : Any=13 , snake_case__ : int=7 , snake_case__ : Optional[Any]=True , snake_case__ : str=False , snake_case__ : Dict=99 , snake_case__ : Union[str, Any]=32 , snake_case__ : List[Any]=5 , snake_case__ : Optional[Any]=4 , snake_case__ : Optional[int]=37 , snake_case__ : Optional[int]=0.1 , snake_case__ : List[Any]=0.1 , snake_case__ : Union[str, Any]=20 , snake_case__ : Tuple=2 , snake_case__ : Union[str, Any]=1 , snake_case__ : Any=0 , ): lowerCamelCase_ : Optional[int] =parent lowerCamelCase_ : Any =batch_size lowerCamelCase_ : Dict =seq_length lowerCamelCase_ : Dict =is_training lowerCamelCase_ : int =use_labels lowerCamelCase_ : Optional[int] =vocab_size lowerCamelCase_ : Dict =hidden_size lowerCamelCase_ : Optional[Any] =num_hidden_layers lowerCamelCase_ : Dict =num_attention_heads lowerCamelCase_ : Optional[Any] =intermediate_size lowerCamelCase_ : str =hidden_dropout_prob lowerCamelCase_ : int =attention_probs_dropout_prob lowerCamelCase_ : Tuple =max_position_embeddings lowerCamelCase_ : List[str] =eos_token_id lowerCamelCase_ : str =pad_token_id lowerCamelCase_ : List[str] =bos_token_id def UpperCAmelCase__ ( self : Optional[int] ): lowerCamelCase_ : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) lowerCamelCase_ : str =np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) lowerCamelCase_ : str =np.concatenate([input_ids, eos_tensor] , axis=1 ) lowerCamelCase_ : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ : List[str] =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 , ) lowerCamelCase_ : Optional[int] =prepare_pegasus_inputs_dict(snake_case__ , snake_case__ , snake_case__ ) return config, inputs_dict def UpperCAmelCase__ ( self : List[str] , snake_case__ : List[Any] , snake_case__ : Tuple , snake_case__ : int ): lowerCamelCase_ : Dict =20 lowerCamelCase_ : Optional[Any] =model_class_name(snake_case__ ) lowerCamelCase_ : Optional[Any] =model.encode(inputs_dict["input_ids"] ) lowerCamelCase_ , lowerCamelCase_ : Optional[Any] =( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) lowerCamelCase_ : List[str] =model.init_cache(decoder_input_ids.shape[0] , snake_case__ , snake_case__ ) lowerCamelCase_ : Optional[int] =jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) lowerCamelCase_ : Any =jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowerCamelCase_ : List[str] =model.decode( decoder_input_ids[:, :-1] , snake_case__ , decoder_attention_mask=snake_case__ , past_key_values=snake_case__ , decoder_position_ids=snake_case__ , ) lowerCamelCase_ : Union[str, Any] =jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) lowerCamelCase_ : str =model.decode( decoder_input_ids[:, -1:] , snake_case__ , decoder_attention_mask=snake_case__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=snake_case__ , ) lowerCamelCase_ : Tuple =model.decode(snake_case__ , snake_case__ ) lowerCamelCase_ : List[Any] =np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ ( self : List[Any] , snake_case__ : str , snake_case__ : int , snake_case__ : Optional[int] ): lowerCamelCase_ : str =20 lowerCamelCase_ : str =model_class_name(snake_case__ ) lowerCamelCase_ : Optional[int] =model.encode(inputs_dict["input_ids"] ) lowerCamelCase_ , lowerCamelCase_ : Optional[Any] =( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) lowerCamelCase_ : List[str] =jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) lowerCamelCase_ : str =model.init_cache(decoder_input_ids.shape[0] , snake_case__ , snake_case__ ) lowerCamelCase_ : List[str] =jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowerCamelCase_ : List[Any] =model.decode( decoder_input_ids[:, :-1] , snake_case__ , decoder_attention_mask=snake_case__ , past_key_values=snake_case__ , decoder_position_ids=snake_case__ , ) lowerCamelCase_ : Union[str, Any] =jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) lowerCamelCase_ : Dict =model.decode( decoder_input_ids[:, -1:] , snake_case__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=snake_case__ , decoder_position_ids=snake_case__ , ) lowerCamelCase_ : str =model.decode(snake_case__ , snake_case__ , decoder_attention_mask=snake_case__ ) lowerCamelCase_ : Union[str, Any] =np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def _snake_case ( lowerCamelCase__ : Tuple , lowerCamelCase__ : List[str] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[str]=None , lowerCamelCase__ : List[str]=None , ) -> Union[str, Any]: if attention_mask is None: lowerCamelCase_ : int =np.not_equal(lowerCamelCase__ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: lowerCamelCase_ : Optional[Any] =np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class lowercase__ ( snake_case__, unittest.TestCase ): _UpperCAmelCase :Any = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) _UpperCAmelCase :Optional[Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () _UpperCAmelCase :Tuple = True _UpperCAmelCase :List[Any] = False _UpperCAmelCase :List[str] = False _UpperCAmelCase :int = False def UpperCAmelCase__ ( self : List[Any] ): lowerCamelCase_ : List[str] =FlaxPegasusModelTester(self ) lowerCamelCase_ : int =ConfigTester(self , config_class=snake_case__ ) def UpperCAmelCase__ ( self : Optional[int] ): self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Tuple ): lowerCamelCase_ , lowerCamelCase_ : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase__ ( self : List[Any] ): lowerCamelCase_ , lowerCamelCase_ : Dict =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase__ ( self : Any ): lowerCamelCase_ , lowerCamelCase_ : Any =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCamelCase_ : Any =self._prepare_for_class(snake_case__ , snake_case__ ) lowerCamelCase_ : List[Any] =model_class(snake_case__ ) @jax.jit def encode_jitted(snake_case__ : Any , snake_case__ : Any=None , **snake_case__ : int ): return model.encode(input_ids=snake_case__ , attention_mask=snake_case__ ) with self.subTest("JIT Enabled" ): lowerCamelCase_ : Any =encode_jitted(**snake_case__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowerCamelCase_ : List[Any] =encode_jitted(**snake_case__ ).to_tuple() self.assertEqual(len(snake_case__ ) , len(snake_case__ ) ) for jitted_output, output in zip(snake_case__ , snake_case__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase__ ( self : Optional[int] ): lowerCamelCase_ , lowerCamelCase_ : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCamelCase_ : List[str] =model_class(snake_case__ ) lowerCamelCase_ : Union[str, Any] =model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) lowerCamelCase_ : List[str] ={ "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(snake_case__ : Optional[int] , snake_case__ : str , snake_case__ : Any ): return model.decode( decoder_input_ids=snake_case__ , decoder_attention_mask=snake_case__ , encoder_outputs=snake_case__ , ) with self.subTest("JIT Enabled" ): lowerCamelCase_ : Any =decode_jitted(**snake_case__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowerCamelCase_ : Any =decode_jitted(**snake_case__ ).to_tuple() self.assertEqual(len(snake_case__ ) , len(snake_case__ ) ) for jitted_output, output in zip(snake_case__ , snake_case__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase__ ( self : str ): for model_class_name in self.all_model_classes: lowerCamelCase_ : List[Any] =model_class_name.from_pretrained("google/pegasus-large" , from_pt=snake_case__ ) lowerCamelCase_ : List[str] =np.ones((1, 1) ) lowerCamelCase_ : List[Any] =model(snake_case__ ) self.assertIsNotNone(snake_case__ ) @slow def UpperCAmelCase__ ( self : Optional[int] ): lowerCamelCase_ : Any =FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) lowerCamelCase_ : Any =PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) lowerCamelCase_ : int =[ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] lowerCamelCase_ : int =[ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] lowerCamelCase_ : List[str] =tokenizer(snake_case__ , return_tensors="np" , truncation=snake_case__ , max_length=512 , padding=snake_case__ ) lowerCamelCase_ : Optional[Any] =model.generate(**snake_case__ , num_beams=2 ).sequences lowerCamelCase_ : Union[str, Any] =tokenizer.batch_decode(snake_case__ , skip_special_tokens=snake_case__ ) assert tgt_text == decoded
209
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def _snake_case ( lowerCamelCase__ : int=None ) -> Union[str, Any]: if subparsers is not None: lowerCamelCase_ : List[Any] =subparsers.add_parser("test" ) else: lowerCamelCase_ : List[str] =argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=lowerCamelCase__ , 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'." ) , ) if subparsers is not None: parser.set_defaults(func=lowerCamelCase__ ) return parser def _snake_case ( lowerCamelCase__ : List[Any] ) -> Any: lowerCamelCase_ : Optional[Any] =os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: lowerCamelCase_ : List[Any] =script_name else: lowerCamelCase_ : Union[str, Any] =F"""--config_file={args.config_file} {script_name}""" lowerCamelCase_ : List[str] =["accelerate-launch"] + test_args.split() lowerCamelCase_ : Tuple =execute_subprocess_async(lowerCamelCase__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def _snake_case ( ) -> Tuple: lowerCamelCase_ : Any =test_command_parser() lowerCamelCase_ : List[Any] =parser.parse_args() test_command(lowerCamelCase__ ) if __name__ == "__main__": main()
209
1
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _a ( SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = filter(lambda SCREAMING_SNAKE_CASE_ : p.requires_grad , model.parameters() ) __lowerCAmelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCamelCase__ = logging.getLogger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): if metric == "rouge2": __lowerCAmelCase = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": __lowerCAmelCase = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": __lowerCAmelCase = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this""" " function." ) __lowerCAmelCase = ModelCheckpoint( dirpath=SCREAMING_SNAKE_CASE_ , filename=SCREAMING_SNAKE_CASE_ , monitor=F"""val_{metric}""" , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return EarlyStopping( monitor=F"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , ) class a__ ( pl.Callback ): def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = {f"""lr_group_{i}""": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A=True ): """simple docstring""" logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __lowerCAmelCase = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results __lowerCAmelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCAmelCase = od / "test_results.txt" __lowerCAmelCase = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __lowerCAmelCase = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" __lowerCAmelCase = od / f"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=_A ) generations_file.parent.mkdir(exist_ok=_A ) with open(_A , "a+" ) as writer: for key in sorted(_A ): if key in ["log", "progress_bar", "preds"]: continue __lowerCAmelCase = metrics[key] if isinstance(_A , torch.Tensor ): __lowerCAmelCase = val.item() __lowerCAmelCase = f"""{key}: {val:.6f}\n""" writer.write(_A ) if not save_generations: return if "preds" in metrics: __lowerCAmelCase = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: __lowerCAmelCase = pl_module.model.model.num_parameters() except AttributeError: __lowerCAmelCase = pl_module.model.num_parameters() __lowerCAmelCase = count_trainable_parameters(_A ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1E6, "grad_mp": n_trainable_pars / 1E6} ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_A , _A , "test" ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
92
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") UpperCamelCase__ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : int = CamembertTokenizer _a : Dict = CamembertTokenizerFast _a : Tuple = True _a : List[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>NOTUSED" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(_A ) , 1_0_0_4 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) __lowerCAmelCase = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.tokenize(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 9, 6]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. __lowerCAmelCase = [ "Le transformeur est un modèle d'apprentissage profond introduit en 2017, " "utilisé principalement dans le domaine du traitement automatique des langues (TAL).", "À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus " "pour gérer des données séquentielles, telles que le langage naturel, pour des tâches " "telles que la traduction et la synthèse de texte.", ] self.tokenizer_integration_test_util( expected_encoding=_A , model_name="camembert-base" , revision="3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf" , sequences=_A , )
92
1
import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger('transformers.models.encodec') __UpperCAmelCase = { 'quantizer.vq.layers.*._codebook.inited': 'quantizer.layers.*.codebook.inited', 'quantizer.vq.layers.*._codebook.cluster_size': 'quantizer.layers.*.codebook.cluster_size', 'quantizer.vq.layers.*._codebook.embed': 'quantizer.layers.*.codebook.embed', 'quantizer.vq.layers.*._codebook.embed_avg': 'quantizer.layers.*.codebook.embed_avg', } __UpperCAmelCase = { 'encoder.model.0.conv.conv': 'encoder.layers.0.conv', 'encoder.model.1.block.1.conv.conv': 'encoder.layers.1.block.1.conv', 'encoder.model.1.block.3.conv.conv': 'encoder.layers.1.block.3.conv', 'encoder.model.1.shortcut.conv.conv': 'encoder.layers.1.shortcut.conv', 'encoder.model.3.conv.conv': 'encoder.layers.3.conv', 'encoder.model.4.block.1.conv.conv': 'encoder.layers.4.block.1.conv', 'encoder.model.4.block.3.conv.conv': 'encoder.layers.4.block.3.conv', 'encoder.model.4.shortcut.conv.conv': 'encoder.layers.4.shortcut.conv', 'encoder.model.6.conv.conv': 'encoder.layers.6.conv', 'encoder.model.7.block.1.conv.conv': 'encoder.layers.7.block.1.conv', 'encoder.model.7.block.3.conv.conv': 'encoder.layers.7.block.3.conv', 'encoder.model.7.shortcut.conv.conv': 'encoder.layers.7.shortcut.conv', 'encoder.model.9.conv.conv': 'encoder.layers.9.conv', 'encoder.model.10.block.1.conv.conv': 'encoder.layers.10.block.1.conv', 'encoder.model.10.block.3.conv.conv': 'encoder.layers.10.block.3.conv', 'encoder.model.10.shortcut.conv.conv': 'encoder.layers.10.shortcut.conv', 'encoder.model.12.conv.conv': 'encoder.layers.12.conv', 'encoder.model.13.lstm': 'encoder.layers.13.lstm', 'encoder.model.15.conv.conv': 'encoder.layers.15.conv', } __UpperCAmelCase = { 'encoder.model.0.conv.norm': 'encoder.layers.0.norm', 'encoder.model.1.block.1.conv.norm': 'encoder.layers.1.block.1.norm', 'encoder.model.1.block.3.conv.norm': 'encoder.layers.1.block.3.norm', 'encoder.model.1.shortcut.conv.norm': 'encoder.layers.1.shortcut.norm', 'encoder.model.3.conv.norm': 'encoder.layers.3.norm', 'encoder.model.4.block.1.conv.norm': 'encoder.layers.4.block.1.norm', 'encoder.model.4.block.3.conv.norm': 'encoder.layers.4.block.3.norm', 'encoder.model.4.shortcut.conv.norm': 'encoder.layers.4.shortcut.norm', 'encoder.model.6.conv.norm': 'encoder.layers.6.norm', 'encoder.model.7.block.1.conv.norm': 'encoder.layers.7.block.1.norm', 'encoder.model.7.block.3.conv.norm': 'encoder.layers.7.block.3.norm', 'encoder.model.7.shortcut.conv.norm': 'encoder.layers.7.shortcut.norm', 'encoder.model.9.conv.norm': 'encoder.layers.9.norm', 'encoder.model.10.block.1.conv.norm': 'encoder.layers.10.block.1.norm', 'encoder.model.10.block.3.conv.norm': 'encoder.layers.10.block.3.norm', 'encoder.model.10.shortcut.conv.norm': 'encoder.layers.10.shortcut.norm', 'encoder.model.12.conv.norm': 'encoder.layers.12.norm', 'encoder.model.15.conv.norm': 'encoder.layers.15.norm', } __UpperCAmelCase = { 'decoder.model.0.conv.conv': 'decoder.layers.0.conv', 'decoder.model.1.lstm': 'decoder.layers.1.lstm', 'decoder.model.3.convtr.convtr': 'decoder.layers.3.conv', 'decoder.model.4.block.1.conv.conv': 'decoder.layers.4.block.1.conv', 'decoder.model.4.block.3.conv.conv': 'decoder.layers.4.block.3.conv', 'decoder.model.4.shortcut.conv.conv': 'decoder.layers.4.shortcut.conv', 'decoder.model.6.convtr.convtr': 'decoder.layers.6.conv', 'decoder.model.7.block.1.conv.conv': 'decoder.layers.7.block.1.conv', 'decoder.model.7.block.3.conv.conv': 'decoder.layers.7.block.3.conv', 'decoder.model.7.shortcut.conv.conv': 'decoder.layers.7.shortcut.conv', 'decoder.model.9.convtr.convtr': 'decoder.layers.9.conv', 'decoder.model.10.block.1.conv.conv': 'decoder.layers.10.block.1.conv', 'decoder.model.10.block.3.conv.conv': 'decoder.layers.10.block.3.conv', 'decoder.model.10.shortcut.conv.conv': 'decoder.layers.10.shortcut.conv', 'decoder.model.12.convtr.convtr': 'decoder.layers.12.conv', 'decoder.model.13.block.1.conv.conv': 'decoder.layers.13.block.1.conv', 'decoder.model.13.block.3.conv.conv': 'decoder.layers.13.block.3.conv', 'decoder.model.13.shortcut.conv.conv': 'decoder.layers.13.shortcut.conv', 'decoder.model.15.conv.conv': 'decoder.layers.15.conv', } __UpperCAmelCase = { 'decoder.model.0.conv.norm': 'decoder.layers.0.norm', 'decoder.model.3.convtr.norm': 'decoder.layers.3.norm', 'decoder.model.4.block.1.conv.norm': 'decoder.layers.4.block.1.norm', 'decoder.model.4.block.3.conv.norm': 'decoder.layers.4.block.3.norm', 'decoder.model.4.shortcut.conv.norm': 'decoder.layers.4.shortcut.norm', 'decoder.model.6.convtr.norm': 'decoder.layers.6.norm', 'decoder.model.7.block.1.conv.norm': 'decoder.layers.7.block.1.norm', 'decoder.model.7.block.3.conv.norm': 'decoder.layers.7.block.3.norm', 'decoder.model.7.shortcut.conv.norm': 'decoder.layers.7.shortcut.norm', 'decoder.model.9.convtr.norm': 'decoder.layers.9.norm', 'decoder.model.10.block.1.conv.norm': 'decoder.layers.10.block.1.norm', 'decoder.model.10.block.3.conv.norm': 'decoder.layers.10.block.3.norm', 'decoder.model.10.shortcut.conv.norm': 'decoder.layers.10.shortcut.norm', 'decoder.model.12.convtr.norm': 'decoder.layers.12.norm', 'decoder.model.13.block.1.conv.norm': 'decoder.layers.13.block.1.norm', 'decoder.model.13.block.3.conv.norm': 'decoder.layers.13.block.3.norm', 'decoder.model.13.shortcut.conv.norm': 'decoder.layers.13.shortcut.norm', 'decoder.model.15.conv.norm': 'decoder.layers.15.norm', } __UpperCAmelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } __UpperCAmelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } __UpperCAmelCase = [] __UpperCAmelCase = [] def __UpperCamelCase ( lowercase__ : Optional[Any] , lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : List[str] , lowercase__ : int ) -> List[Any]: '''simple docstring''' for attribute in key.split(""".""" ): lowerCAmelCase_ : Optional[Any] = getattr(lowercase__ , lowercase__ ) if weight_type is not None: lowerCAmelCase_ : Tuple = getattr(lowercase__ , lowercase__ ).shape else: lowerCAmelCase_ : List[Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": lowerCAmelCase_ : Union[str, Any] = value elif weight_type == "weight_g": lowerCAmelCase_ : Any = value elif weight_type == "weight_v": lowerCAmelCase_ : str = value elif weight_type == "bias": lowerCAmelCase_ : Any = value elif weight_type == "running_mean": lowerCAmelCase_ : List[str] = value elif weight_type == "running_var": lowerCAmelCase_ : Optional[int] = value elif weight_type == "num_batches_tracked": lowerCAmelCase_ : List[Any] = value elif weight_type == "weight_ih_l0": lowerCAmelCase_ : Optional[int] = value elif weight_type == "weight_hh_l0": lowerCAmelCase_ : Tuple = value elif weight_type == "bias_ih_l0": lowerCAmelCase_ : int = value elif weight_type == "bias_hh_l0": lowerCAmelCase_ : Tuple = value elif weight_type == "weight_ih_l1": lowerCAmelCase_ : List[str] = value elif weight_type == "weight_hh_l1": lowerCAmelCase_ : int = value elif weight_type == "bias_ih_l1": lowerCAmelCase_ : int = value elif weight_type == "bias_hh_l1": lowerCAmelCase_ : Optional[int] = value else: lowerCAmelCase_ : Any = value logger.info(f'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' ) def __UpperCamelCase ( lowercase__ : Optional[Any] , lowercase__ : Dict ) -> Tuple: '''simple docstring''' for key in ignore_keys: if key.endswith(""".*""" ): if name.startswith(key[:-1] ): return True elif ".*." in key: lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = key.split(""".*.""" ) if prefix in name and suffix in name: return True elif key in name: return True return False def __UpperCamelCase ( lowercase__ : List[str] , lowercase__ : Optional[Any] , lowercase__ : Optional[int] ) -> Dict: '''simple docstring''' lowerCAmelCase_ : int = [] if model_name == "encodec_24khz" or "encodec_32khz": lowerCAmelCase_ : Optional[int] = MAPPING_24K elif model_name == "encodec_48khz": lowerCAmelCase_ : List[Any] = MAPPING_48K else: raise ValueError(f'Unsupported model: {model_name}' ) for name, value in orig_dict.items(): if should_ignore(lowercase__ , lowercase__ ): logger.info(f'{name} was ignored' ) continue lowerCAmelCase_ : str = False for key, mapped_key in MAPPING.items(): if "*" in key: lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = key.split(""".*.""" ) if prefix in name and suffix in name: lowerCAmelCase_ : Tuple = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith("""embed""" ) and name.endswith("""embed_avg""" ): continue lowerCAmelCase_ : str = True if "*" in mapped_key: lowerCAmelCase_ : Optional[Any] = name.split(lowercase__ )[0].split(""".""" )[-2] lowerCAmelCase_ : Optional[Any] = mapped_key.replace("""*""" , lowercase__ ) if "weight_g" in name: lowerCAmelCase_ : List[str] = """weight_g""" elif "weight_v" in name: lowerCAmelCase_ : Optional[int] = """weight_v""" elif "weight_ih_l0" in name: lowerCAmelCase_ : Dict = """weight_ih_l0""" elif "weight_hh_l0" in name: lowerCAmelCase_ : List[Any] = """weight_hh_l0""" elif "bias_ih_l0" in name: lowerCAmelCase_ : int = """bias_ih_l0""" elif "bias_hh_l0" in name: lowerCAmelCase_ : Optional[int] = """bias_hh_l0""" elif "weight_ih_l1" in name: lowerCAmelCase_ : Union[str, Any] = """weight_ih_l1""" elif "weight_hh_l1" in name: lowerCAmelCase_ : Any = """weight_hh_l1""" elif "bias_ih_l1" in name: lowerCAmelCase_ : Dict = """bias_ih_l1""" elif "bias_hh_l1" in name: lowerCAmelCase_ : List[str] = """bias_hh_l1""" elif "bias" in name: lowerCAmelCase_ : Tuple = """bias""" elif "weight" in name: lowerCAmelCase_ : List[str] = """weight""" elif "running_mean" in name: lowerCAmelCase_ : Optional[Any] = """running_mean""" elif "running_var" in name: lowerCAmelCase_ : int = """running_var""" elif "num_batches_tracked" in name: lowerCAmelCase_ : Tuple = """num_batches_tracked""" else: lowerCAmelCase_ : Any = None set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) continue if not is_used: unused_weights.append(lowercase__ ) logger.warning(f'Unused weights: {unused_weights}' ) @torch.no_grad() def __UpperCamelCase ( lowercase__ : Dict , lowercase__ : List[str] , lowercase__ : Union[str, Any] , lowercase__ : Tuple=None , lowercase__ : str=None , ) -> Optional[int]: '''simple docstring''' if config_path is not None: lowerCAmelCase_ : List[str] = EncodecConfig.from_pretrained(lowercase__ ) else: lowerCAmelCase_ : Any = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": lowerCAmelCase_ : List[str] = [8, 5, 4, 4] lowerCAmelCase_ : int = [2.2] lowerCAmelCase_ : List[str] = 64 lowerCAmelCase_ : Optional[int] = 32000 lowerCAmelCase_ : Tuple = 2048 lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Any = False lowerCAmelCase_ : int = False elif model_name == "encodec_48khz": lowerCAmelCase_ : Optional[int] = [8, 5, 4, 2] lowerCAmelCase_ : Optional[Any] = [3.0, 6.0, 12.0, 24.0] lowerCAmelCase_ : Optional[int] = 48000 lowerCAmelCase_ : str = 2 lowerCAmelCase_ : List[str] = False lowerCAmelCase_ : str = """time_group_norm""" lowerCAmelCase_ : int = True lowerCAmelCase_ : Optional[Any] = 1.0 lowerCAmelCase_ : Optional[Any] = 0.01 else: raise ValueError(f'Unknown model name: {model_name}' ) lowerCAmelCase_ : Dict = EncodecModel(lowercase__ ) lowerCAmelCase_ : Tuple = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(lowercase__ ) lowerCAmelCase_ : int = torch.load(lowercase__ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights lowerCAmelCase_ : Optional[Any] = original_checkpoint["""best_state"""] recursively_load_weights(lowercase__ , lowercase__ , lowercase__ ) model.save_pretrained(lowercase__ ) if repo_id: print("""Pushing to the hub...""" ) feature_extractor.push_to_hub(lowercase__ ) model.push_to_hub(lowercase__ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( '--model', default='encodec_24khz', type=str, help='The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.', ) parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) __UpperCAmelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
28
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger('transformers.models.speecht5') def __UpperCamelCase ( lowercase__ : Optional[Any] , lowercase__ : Optional[Any] , lowercase__ : str ) -> List[str]: '''simple docstring''' hf_model.apply_weight_norm() lowerCAmelCase_ : Dict = checkpoint["""input_conv.weight_g"""] lowerCAmelCase_ : Any = checkpoint["""input_conv.weight_v"""] lowerCAmelCase_ : Any = checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): lowerCAmelCase_ : Tuple = checkpoint[f'upsamples.{i}.1.weight_g'] lowerCAmelCase_ : Any = checkpoint[f'upsamples.{i}.1.weight_v'] lowerCAmelCase_ : int = checkpoint[f'upsamples.{i}.1.bias'] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): lowerCAmelCase_ : Dict = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_g'] lowerCAmelCase_ : Dict = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_v'] lowerCAmelCase_ : Tuple = checkpoint[f'blocks.{i}.convs1.{j}.1.bias'] lowerCAmelCase_ : str = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_g'] lowerCAmelCase_ : Optional[Any] = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_v'] lowerCAmelCase_ : str = checkpoint[f'blocks.{i}.convs2.{j}.1.bias'] lowerCAmelCase_ : str = checkpoint["""output_conv.1.weight_g"""] lowerCAmelCase_ : Dict = checkpoint["""output_conv.1.weight_v"""] lowerCAmelCase_ : Optional[int] = checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def __UpperCamelCase ( lowercase__ : str , lowercase__ : Tuple , lowercase__ : Dict , lowercase__ : List[Any]=None , lowercase__ : Union[str, Any]=None , ) -> List[Any]: '''simple docstring''' if config_path is not None: lowerCAmelCase_ : Optional[Any] = SpeechTaHifiGanConfig.from_pretrained(lowercase__ ) else: lowerCAmelCase_ : Any = SpeechTaHifiGanConfig() lowerCAmelCase_ : str = SpeechTaHifiGan(lowercase__ ) lowerCAmelCase_ : Tuple = torch.load(lowercase__ ) load_weights(orig_checkpoint["""model"""]["""generator"""] , lowercase__ , lowercase__ ) lowerCAmelCase_ : Optional[int] = np.load(lowercase__ ) lowerCAmelCase_ : Any = stats[0].reshape(-1 ) lowerCAmelCase_ : List[str] = stats[1].reshape(-1 ) lowerCAmelCase_ : Optional[int] = torch.from_numpy(lowercase__ ).float() lowerCAmelCase_ : Any = torch.from_numpy(lowercase__ ).float() model.save_pretrained(lowercase__ ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(lowercase__ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) __UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
28
1
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __UpperCamelCase : int = 0 __UpperCamelCase : int = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __UpperCamelCase : List[str] = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __UpperCamelCase : Optional[Any] = tuple[int, int] class lowercase__ : def __init__( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : Node | None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = pos_x SCREAMING_SNAKE_CASE : Optional[Any] = pos_y SCREAMING_SNAKE_CASE : Dict = (pos_y, pos_x) SCREAMING_SNAKE_CASE : Tuple = goal_x SCREAMING_SNAKE_CASE : Optional[int] = goal_y SCREAMING_SNAKE_CASE : Dict = g_cost SCREAMING_SNAKE_CASE : Dict = parent SCREAMING_SNAKE_CASE : List[str] = self.calculate_heuristic() SCREAMING_SNAKE_CASE : Union[str, Any] = self.g_cost + self.h_cost def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.pos_x - self.goal_x SCREAMING_SNAKE_CASE : Dict = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(UpperCamelCase__ ) + abs(UpperCamelCase__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : Optional[int] , UpperCamelCase__ : Node ): '''simple docstring''' return self.f_cost < other.f_cost class lowercase__ : def __init__( self : Optional[Any] , UpperCamelCase__ : TPosition , UpperCamelCase__ : TPosition ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9999 , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = [self.start] SCREAMING_SNAKE_CASE : list[Node] = [] SCREAMING_SNAKE_CASE : Tuple = False def __A ( self : Tuple ): '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() SCREAMING_SNAKE_CASE : Union[str, Any] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(UpperCamelCase__ ) self.closed_nodes.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = self.get_successors(UpperCamelCase__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(UpperCamelCase__ ) else: # retrieve the best current path SCREAMING_SNAKE_CASE : int = self.open_nodes.pop(self.open_nodes.index(UpperCamelCase__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(UpperCamelCase__ ) else: self.open_nodes.append(UpperCamelCase__ ) return [self.start.pos] def __A ( self : List[Any] , UpperCamelCase__ : Node ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] for action in delta: SCREAMING_SNAKE_CASE : Union[str, Any] = parent.pos_x + action[1] SCREAMING_SNAKE_CASE : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCamelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( UpperCamelCase__ , UpperCamelCase__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCamelCase__ , ) ) return successors def __A ( self : str , UpperCamelCase__ : Node | None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = node SCREAMING_SNAKE_CASE : Any = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) SCREAMING_SNAKE_CASE : Optional[int] = current_node.parent path.reverse() return path class lowercase__ : def __init__( self : List[Any] , UpperCamelCase__ : TPosition , UpperCamelCase__ : TPosition ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = AStar(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = AStar(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = False def __A ( self : Any ): '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() SCREAMING_SNAKE_CASE : Tuple = self.fwd_astar.open_nodes.pop(0 ) SCREAMING_SNAKE_CASE : int = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( UpperCamelCase__ , UpperCamelCase__ ) self.fwd_astar.closed_nodes.append(UpperCamelCase__ ) self.bwd_astar.closed_nodes.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = current_bwd_node SCREAMING_SNAKE_CASE : Union[str, Any] = current_fwd_node SCREAMING_SNAKE_CASE : Optional[Any] = { self.fwd_astar: self.fwd_astar.get_successors(UpperCamelCase__ ), self.bwd_astar: self.bwd_astar.get_successors(UpperCamelCase__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(UpperCamelCase__ ) else: # retrieve the best current path SCREAMING_SNAKE_CASE : List[str] = astar.open_nodes.pop( astar.open_nodes.index(UpperCamelCase__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(UpperCamelCase__ ) else: astar.open_nodes.append(UpperCamelCase__ ) return [self.fwd_astar.start.pos] def __A ( self : Union[str, Any] , UpperCamelCase__ : Node , UpperCamelCase__ : Node ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.fwd_astar.retrace_path(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.bwd_astar.retrace_path(UpperCamelCase__ ) bwd_path.pop() bwd_path.reverse() SCREAMING_SNAKE_CASE : Any = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __UpperCamelCase : int = (0, 0) __UpperCamelCase : Dict = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __UpperCamelCase : Tuple = time.time() __UpperCamelCase : Dict = AStar(init, goal) __UpperCamelCase : Tuple = a_star.search() __UpperCamelCase : str = time.time() - start_time print(f"""AStar execution time = {end_time:f} seconds""") __UpperCamelCase : str = time.time() __UpperCamelCase : Dict = BidirectionalAStar(init, goal) __UpperCamelCase : Dict = time.time() - bd_start_time print(f"""BidirectionalAStar execution time = {bd_end_time:f} seconds""")
182
import itertools import string from collections.abc import Generator, Iterable def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = iter(_lowercase ) while True: SCREAMING_SNAKE_CASE : Optional[Any] = tuple(itertools.islice(_lowercase , _lowercase ) ) if not chunk: return yield chunk def A ( _lowercase ): SCREAMING_SNAKE_CASE : int = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] ) SCREAMING_SNAKE_CASE : List[str] = '''''' if len(_lowercase ) < 2: return dirty for i in range(len(_lowercase ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(_lowercase ) & 1: clean += "X" return clean def A ( _lowercase ): # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) SCREAMING_SNAKE_CASE : Optional[Any] = '''ABCDEFGHIKLMNOPQRSTUVWXYZ''' # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler SCREAMING_SNAKE_CASE : List[Any] = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(_lowercase ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(_lowercase ) return table def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Any = generate_table(_lowercase ) SCREAMING_SNAKE_CASE : Any = prepare_input(_lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(_lowercase , 2 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = divmod(table.index(_lowercase ) , 5 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = divmod(table.index(_lowercase ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Any = generate_table(_lowercase ) SCREAMING_SNAKE_CASE : List[Any] = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(_lowercase , 2 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = divmod(table.index(_lowercase ) , 5 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = divmod(table.index(_lowercase ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
182
1
import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser lowerCAmelCase__ = re.compile(r'\s+') def __lowerCamelCase ( lowerCAmelCase__ ): return {"hash": hashlib.mda(re.sub(lowerCAmelCase__ , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def __lowerCamelCase ( lowerCAmelCase__ ): lowerCAmelCase__ = [len(lowerCAmelCase__ ) for line in example['content'].splitlines()] return {"line_mean": np.mean(lowerCAmelCase__ ), "line_max": max(lowerCAmelCase__ )} def __lowerCamelCase ( lowerCAmelCase__ ): lowerCAmelCase__ = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=5 ): lowerCAmelCase__ = ['auto-generated', 'autogenerated', 'automatically generated'] lowerCAmelCase__ = example['content'].splitlines() for _, line in zip(range(lowerCAmelCase__ ) , lowerCAmelCase__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=5 , lowerCAmelCase__=0.0_5 ): lowerCAmelCase__ = ['unit tests', 'test file', 'configuration file'] lowerCAmelCase__ = example['content'].splitlines() lowerCAmelCase__ = 0 lowerCAmelCase__ = 0 # first test for _, line in zip(range(lowerCAmelCase__ ) , lowerCAmelCase__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test lowerCAmelCase__ = example['content'].count('\n' ) lowerCAmelCase__ = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def __lowerCamelCase ( lowerCAmelCase__ ): lowerCAmelCase__ = ['def ', 'class ', 'for ', 'while '] lowerCAmelCase__ = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=4 ): lowerCAmelCase__ = example['content'].splitlines() lowerCAmelCase__ = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def __lowerCamelCase ( lowerCAmelCase__ ): lowerCAmelCase__ = tokenizer(example['content'] , truncation=lowerCAmelCase__ )['input_ids'] lowerCAmelCase__ = len(example['content'] ) / len(lowerCAmelCase__ ) return {"ratio": ratio} def __lowerCamelCase ( lowerCAmelCase__ ): lowerCAmelCase__ = {} results.update(get_hash(lowerCAmelCase__ ) ) results.update(line_stats(lowerCAmelCase__ ) ) results.update(alpha_stats(lowerCAmelCase__ ) ) results.update(char_token_ratio(lowerCAmelCase__ ) ) results.update(is_autogenerated(lowerCAmelCase__ ) ) results.update(is_config_or_test(lowerCAmelCase__ ) ) results.update(has_no_keywords(lowerCAmelCase__ ) ) results.update(has_few_assignments(lowerCAmelCase__ ) ) return results def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): if not check_uniques(lowerCAmelCase__ , lowerCAmelCase__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def __lowerCamelCase ( lowerCAmelCase__ ): with open(lowerCAmelCase__ , 'rb' ) as f_in: with gzip.open(str(lowerCAmelCase__ ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(lowerCAmelCase__ , lowerCAmelCase__ ) os.unlink(lowerCAmelCase__ ) # Settings lowerCAmelCase__ = HfArgumentParser(PreprocessingArguments) lowerCAmelCase__ = parser.parse_args() if args.num_workers is None: lowerCAmelCase__ = multiprocessing.cpu_count() lowerCAmelCase__ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset lowerCAmelCase__ = time.time() lowerCAmelCase__ = load_dataset(args.dataset_name, split='train') print(F'Time to load dataset: {time.time()-t_start:.2f}') # Run preprocessing lowerCAmelCase__ = time.time() lowerCAmelCase__ = ds.map(preprocess, num_proc=args.num_workers) print(F'Time to preprocess dataset: {time.time()-t_start:.2f}') # Deduplicate hashes lowerCAmelCase__ = set(ds.unique('hash')) lowerCAmelCase__ = len(uniques) / len(ds) print(F'Fraction of duplicates: {1-frac:.2%}') # Deduplicate data and apply heuristics lowerCAmelCase__ = time.time() lowerCAmelCase__ = ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args}) print(F'Time to filter dataset: {time.time()-t_start:.2f}') print(F'Size of filtered dataset: {len(ds_filter)}') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: lowerCAmelCase__ = time.time() lowerCAmelCase__ , lowerCAmelCase__ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'Time to deduplicate dataset: {time.time()-t_start:.2f}') print(F'Size of deduplicate dataset: {len(ds_filter)}') # Save data in batches of samples_per_file lowerCAmelCase__ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / 'duplicate_clusters.json', 'w') as f: json.dump(duplicate_clusters, f) lowerCAmelCase__ = output_dir / 'data' data_dir.mkdir(exist_ok=True) lowerCAmelCase__ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): lowerCAmelCase__ = str(data_dir / F'file-{file_number+1:012}.json') lowerCAmelCase__ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'Time to save dataset: {time.time()-t_start:.2f}')
360
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) class a_ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCAmelCase_ = ['pixel_values'] def __init__( self : Tuple , lowercase__ : bool = True , lowercase__ : Dict[str, int] = None , lowercase__ : PILImageResampling = PILImageResampling.BICUBIC , lowercase__ : bool = True , lowercase__ : Union[int, float] = 1 / 255 , lowercase__ : bool = True , lowercase__ : Optional[Union[float, List[float]]] = None , lowercase__ : Optional[Union[float, List[float]]] = None , lowercase__ : bool = True , **lowercase__ : List[Any] , ): '''simple docstring''' super().__init__(**lowercase__) lowerCAmelCase__ = size if size is not None else {'height': 384, 'width': 384} lowerCAmelCase__ = get_size_dict(lowercase__ , default_to_square=lowercase__) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCAmelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD lowerCAmelCase__ = do_convert_rgb def __snake_case ( self : List[str] , lowercase__ : np.ndarray , lowercase__ : Dict[str, int] , lowercase__ : PILImageResampling = PILImageResampling.BICUBIC , lowercase__ : Optional[Union[str, ChannelDimension]] = None , **lowercase__ : Dict , ): '''simple docstring''' lowerCAmelCase__ = get_size_dict(lowercase__ , default_to_square=lowercase__) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""") lowerCAmelCase__ = (size['height'], size['width']) return resize(lowercase__ , size=lowercase__ , resample=lowercase__ , data_format=lowercase__ , **lowercase__) def __snake_case ( self : List[str] , lowercase__ : np.ndarray , lowercase__ : Union[int, float] , lowercase__ : Optional[Union[str, ChannelDimension]] = None , **lowercase__ : Union[str, Any] , ): '''simple docstring''' return rescale(lowercase__ , scale=lowercase__ , data_format=lowercase__ , **lowercase__) def __snake_case ( self : Optional[Any] , lowercase__ : np.ndarray , lowercase__ : Union[float, List[float]] , lowercase__ : Union[float, List[float]] , lowercase__ : Optional[Union[str, ChannelDimension]] = None , **lowercase__ : Any , ): '''simple docstring''' return normalize(lowercase__ , mean=lowercase__ , std=lowercase__ , data_format=lowercase__ , **lowercase__) def __snake_case ( self : Any , lowercase__ : ImageInput , lowercase__ : Optional[bool] = None , lowercase__ : Optional[Dict[str, int]] = None , lowercase__ : PILImageResampling = None , lowercase__ : Optional[bool] = None , lowercase__ : Optional[float] = None , lowercase__ : Optional[bool] = None , lowercase__ : Optional[Union[float, List[float]]] = None , lowercase__ : Optional[Union[float, List[float]]] = None , lowercase__ : Optional[Union[str, TensorType]] = None , lowercase__ : bool = None , lowercase__ : ChannelDimension = ChannelDimension.FIRST , **lowercase__ : Dict , ): '''simple docstring''' lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(lowercase__ , default_to_square=lowercase__) lowerCAmelCase__ = make_list_of_images(lowercase__) if not valid_images(lowercase__): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # PIL RGBA images are converted to RGB if do_convert_rgb: lowerCAmelCase__ = [convert_to_rgb(lowercase__) for image in images] # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(lowercase__) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=lowercase__ , size=lowercase__ , resample=lowercase__) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=lowercase__ , scale=lowercase__) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=lowercase__ , mean=lowercase__ , std=lowercase__) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(lowercase__ , lowercase__) for image in images] lowerCAmelCase__ = BatchFeature(data={'pixel_values': images} , tensor_type=lowercase__) return encoded_outputs
119
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __UpperCAmelCase = logging.get_logger(__name__) class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCAmelCase_ =["pixel_values"] def __init__( self , _A = True , _A = None , _A = PILImageResampling.BICUBIC , _A = True , _A = True , _A = 1 / 255 , _A = None , _A = True , _A = None , _A = None , **_A , ) -> None: super().__init__(**_A ) SCREAMING_SNAKE_CASE_ = size if size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ = get_size_dict(_A ) SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ = get_size_dict(_A , default_to_square=_A , param_name='''crop_size''' ) SCREAMING_SNAKE_CASE_ = do_resize SCREAMING_SNAKE_CASE_ = do_rescale SCREAMING_SNAKE_CASE_ = do_normalize SCREAMING_SNAKE_CASE_ = do_center_crop SCREAMING_SNAKE_CASE_ = crop_size SCREAMING_SNAKE_CASE_ = size SCREAMING_SNAKE_CASE_ = resample SCREAMING_SNAKE_CASE_ = rescale_factor SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else IMAGENET_DEFAULT_STD def _UpperCamelCase ( self , _A , _A , _A = PILImageResampling.BILINEAR , _A = None , **_A , ) -> np.ndarray: SCREAMING_SNAKE_CASE_ = get_size_dict(_A ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ = get_resize_output_image_size(_A , size=size['''shortest_edge'''] , default_to_square=_A ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ = (size['''height'''], size['''width''']) else: raise ValueError(F'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}''' ) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def _UpperCamelCase ( self , _A , _A , _A = None , **_A , ) -> np.ndarray: SCREAMING_SNAKE_CASE_ = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(_A , size=(size['''height'''], size['''width''']) , data_format=_A , **_A ) def _UpperCamelCase ( self , _A , _A , _A = None , **_A ) -> np.ndarray: return rescale(_A , scale=_A , data_format=_A , **_A ) def _UpperCamelCase ( self , _A , _A , _A , _A = None , **_A , ) -> np.ndarray: return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def _UpperCamelCase ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ) -> BatchFeature: SCREAMING_SNAKE_CASE_ = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ = get_size_dict(_A , param_name='''crop_size''' , default_to_square=_A ) SCREAMING_SNAKE_CASE_ = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ = size if size is not None else self.size SCREAMING_SNAKE_CASE_ = get_size_dict(_A ) if not is_batched(_A ): SCREAMING_SNAKE_CASE_ = [images] if not valid_images(_A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ = [to_numpy_array(_A ) for image in images] if do_resize: SCREAMING_SNAKE_CASE_ = [self.resize(image=_A , size=_A , resample=_A ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE_ = [self.center_crop(image=_A , size=_A ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE_ = [self.rescale(image=_A , scale=_A ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_ = [self.normalize(image=_A , mean=_A , std=_A ) for image in images] SCREAMING_SNAKE_CASE_ = [to_channel_dimension_format(_A , _A ) for image in images] SCREAMING_SNAKE_CASE_ = {'''pixel_values''': images} return BatchFeature(data=_A , tensor_type=_A )
299
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=3 , _A=32 , _A=3 , _A=10 , _A=[10, 20, 30, 40] , _A=[1, 1, 2, 1] , _A=True , _A=True , _A="relu" , _A=3 , _A=None , ) -> Tuple: SCREAMING_SNAKE_CASE_ = parent SCREAMING_SNAKE_CASE_ = batch_size SCREAMING_SNAKE_CASE_ = image_size SCREAMING_SNAKE_CASE_ = num_channels SCREAMING_SNAKE_CASE_ = embeddings_size SCREAMING_SNAKE_CASE_ = hidden_sizes SCREAMING_SNAKE_CASE_ = depths SCREAMING_SNAKE_CASE_ = is_training SCREAMING_SNAKE_CASE_ = use_labels SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = num_labels SCREAMING_SNAKE_CASE_ = scope SCREAMING_SNAKE_CASE_ = len(_A ) def _UpperCamelCase ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ = self.get_config() return config, pixel_values def _UpperCamelCase ( self ) -> Optional[Any]: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _UpperCamelCase ( self , _A , _A ) -> int: SCREAMING_SNAKE_CASE_ = FlaxRegNetModel(config=_A ) SCREAMING_SNAKE_CASE_ = model(_A ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _UpperCamelCase ( self , _A , _A ) -> Any: SCREAMING_SNAKE_CASE_ = self.num_labels SCREAMING_SNAKE_CASE_ = FlaxRegNetForImageClassification(config=_A ) SCREAMING_SNAKE_CASE_ = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self ) -> Any: SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = config_and_inputs SCREAMING_SNAKE_CASE_ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ =(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () UpperCAmelCase_ =False UpperCAmelCase_ =False UpperCAmelCase_ =False def _UpperCamelCase ( self ) -> None: SCREAMING_SNAKE_CASE_ = FlaxRegNetModelTester(self ) SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A , has_text_modality=_A ) def _UpperCamelCase ( self ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _UpperCamelCase ( self ) -> str: return def _UpperCamelCase ( self ) -> List[str]: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def _UpperCamelCase ( self ) -> str: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def _UpperCamelCase ( self ) -> int: pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def _UpperCamelCase ( self ) -> Dict: pass def _UpperCamelCase ( self ) -> List[Any]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ = model_class(_A ) SCREAMING_SNAKE_CASE_ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _A ) def _UpperCamelCase ( self ) -> Any: def check_hidden_states_output(_A , _A , _A ): SCREAMING_SNAKE_CASE_ = model_class(_A ) SCREAMING_SNAKE_CASE_ = model(**self._prepare_for_class(_A , _A ) ) SCREAMING_SNAKE_CASE_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE_ = self.model_tester.num_stages self.assertEqual(len(_A ) , expected_num_stages + 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ = True check_hidden_states_output(_A , _A , _A ) def _UpperCamelCase ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE_ = self._prepare_for_class(_A , _A ) SCREAMING_SNAKE_CASE_ = model_class(_A ) @jax.jit def model_jitted(_A , **_A ): return model(pixel_values=_A , **_A ) with self.subTest('''JIT Enabled''' ): SCREAMING_SNAKE_CASE_ = model_jitted(**_A ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): SCREAMING_SNAKE_CASE_ = model_jitted(**_A ).to_tuple() self.assertEqual(len(_A ) , len(_A ) ) for jitted_output, output in zip(_A , _A ): self.assertEqual(jitted_output.shape , output.shape ) def A__ ( ): SCREAMING_SNAKE_CASE_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase ( self ) -> Optional[int]: return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def _UpperCamelCase ( self ) -> int: SCREAMING_SNAKE_CASE_ = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) SCREAMING_SNAKE_CASE_ = self.default_image_processor SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = image_processor(images=_A , return_tensors='''np''' ) SCREAMING_SNAKE_CASE_ = model(**_A ) # verify the logits SCREAMING_SNAKE_CASE_ = (1, 1000) self.assertEqual(outputs.logits.shape , _A ) SCREAMING_SNAKE_CASE_ = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) )
299
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, is_vision_available, ) UpperCAmelCase = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ['''OwlViTFeatureExtractor'''] UpperCAmelCase = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
172
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class __magic_name__ ( __UpperCAmelCase ): __A : Tuple = "layoutlmv3" def __init__( self : int , snake_case__ : Any=5_0_2_6_5 , snake_case__ : int=7_6_8 , snake_case__ : Dict=1_2 , snake_case__ : Optional[Any]=1_2 , snake_case__ : Union[str, Any]=3_0_7_2 , snake_case__ : Tuple="gelu" , snake_case__ : List[str]=0.1 , snake_case__ : List[str]=0.1 , snake_case__ : int=5_1_2 , snake_case__ : int=2 , snake_case__ : Optional[int]=0.02 , snake_case__ : Union[str, Any]=1e-5 , snake_case__ : Optional[int]=1 , snake_case__ : Any=0 , snake_case__ : Optional[int]=2 , snake_case__ : int=1_0_2_4 , snake_case__ : str=1_2_8 , snake_case__ : Tuple=1_2_8 , snake_case__ : Optional[Any]=True , snake_case__ : Union[str, Any]=3_2 , snake_case__ : Any=1_2_8 , snake_case__ : List[Any]=6_4 , snake_case__ : List[Any]=2_5_6 , snake_case__ : Any=True , snake_case__ : Optional[Any]=True , snake_case__ : Tuple=True , snake_case__ : List[Any]=2_2_4 , snake_case__ : Optional[int]=3 , snake_case__ : Union[str, Any]=1_6 , snake_case__ : str=None , **snake_case__ : List[str] , ): '''simple docstring''' super().__init__( vocab_size=snake_case__ , hidden_size=snake_case__ , num_hidden_layers=snake_case__ , num_attention_heads=snake_case__ , intermediate_size=snake_case__ , hidden_act=snake_case__ , hidden_dropout_prob=snake_case__ , attention_probs_dropout_prob=snake_case__ , max_position_embeddings=snake_case__ , type_vocab_size=snake_case__ , initializer_range=snake_case__ , layer_norm_eps=snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ , ) lowercase :Optional[int] = max_ad_position_embeddings lowercase :Tuple = coordinate_size lowercase :Any = shape_size lowercase :Union[str, Any] = has_relative_attention_bias lowercase :Optional[Any] = rel_pos_bins lowercase :Tuple = max_rel_pos lowercase :Any = has_spatial_attention_bias lowercase :Any = rel_ad_pos_bins lowercase :str = max_rel_ad_pos lowercase :int = text_embed lowercase :Optional[int] = visual_embed lowercase :str = input_size lowercase :List[str] = num_channels lowercase :str = patch_size lowercase :Any = classifier_dropout class __magic_name__ ( __UpperCAmelCase ): __A : Tuple = version.parse("1.12" ) @property def __snake_case ( self : Any ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __snake_case ( self : int ): '''simple docstring''' return 1e-5 @property def __snake_case ( self : Union[str, Any] ): '''simple docstring''' return 1_2 def __snake_case ( self : str , snake_case__ : "ProcessorMixin" , snake_case__ : int = -1 , snake_case__ : int = -1 , snake_case__ : bool = False , snake_case__ : Optional["TensorType"] = None , snake_case__ : int = 3 , snake_case__ : int = 4_0 , snake_case__ : int = 4_0 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , snake_case__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowercase :Dict = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX lowercase :Union[str, Any] = processor.tokenizer.num_special_tokens_to_add(snake_case__ ) lowercase :List[str] = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case__ ) # Generate dummy inputs according to compute batch and sequence lowercase :Tuple = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes lowercase :List[str] = [[[4_8, 8_4, 7_3, 1_2_8]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) lowercase :List[Any] = self._generate_dummy_images(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) lowercase :Dict = dict( processor( snake_case__ , text=snake_case__ , boxes=snake_case__ , return_tensors=snake_case__ , ) ) return inputs
172
1
"""simple docstring""" def A__ ( UpperCamelCase = 100 ): A = n * (n + 1) * (2 * n + 1) / 6 A = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
292
"""simple docstring""" import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class _UpperCAmelCase : UpperCamelCase = None def lowerCamelCase ( self :List[Any] ): A = self.feature_extraction_class(**self.feat_extract_dict ) A = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __UpperCamelCase ) def lowerCamelCase ( self :Dict ): A = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(__UpperCamelCase , "feat_extract.json" ) feat_extract_first.to_json_file(__UpperCamelCase ) A = self.feature_extraction_class.from_json_file(__UpperCamelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase ( self :Dict ): A = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = feat_extract_first.save_pretrained(__UpperCamelCase )[0] check_json_file_has_correct_format(__UpperCamelCase ) A = self.feature_extraction_class.from_pretrained(__UpperCamelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase ( self :Tuple ): A = self.feature_extraction_class() self.assertIsNotNone(__UpperCamelCase )
292
1
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def a_ ( _lowercase , _lowercase , _lowercase , _lowercase ): if isinstance(__lowerCAmelCase , __lowerCAmelCase ): _UpperCamelCase : Any = np.full((len(__lowerCAmelCase ), sequence_length, 2) , __lowerCAmelCase ) else: _UpperCamelCase : Optional[int] = np.full((len(__lowerCAmelCase ), sequence_length) , __lowerCAmelCase ) for i, tensor in enumerate(__lowerCAmelCase ): if padding_side == "right": if isinstance(__lowerCAmelCase , __lowerCAmelCase ): _UpperCamelCase : Tuple = tensor[:sequence_length] else: _UpperCamelCase : Any = tensor[:sequence_length] else: if isinstance(__lowerCAmelCase , __lowerCAmelCase ): _UpperCamelCase : List[Any] = tensor[:sequence_length] else: _UpperCamelCase : List[Any] = tensor[:sequence_length] return out_tensor.tolist() def a_ ( _lowercase ): _UpperCamelCase : Any = ord(__lowerCAmelCase ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True _UpperCamelCase : List[Any] = unicodedata.category(__lowerCAmelCase ) if cat.startswith('''P''' ): return True return False @dataclass class _a ( UpperCamelCase_ ): UpperCamelCase = 42 UpperCamelCase = True UpperCamelCase = None UpperCamelCase = None UpperCamelCase = -100 UpperCamelCase = "pt" def snake_case ( self : Tuple, lowerCAmelCase__ : Any ) -> int: '''simple docstring''' import torch _UpperCamelCase : Tuple = """label""" if """label""" in features[0].keys() else """labels""" _UpperCamelCase : int = [feature[label_name] for feature in features] if label_name in features[0].keys() else None _UpperCamelCase : List[str] = self.tokenizer.pad( _a, padding=self.padding, max_length=self.max_length, pad_to_multiple_of=self.pad_to_multiple_of, return_tensors='''pt''' if labels is None else None, ) if labels is None: return batch _UpperCamelCase : List[Any] = torch.tensor(batch['''entity_ids'''] ).shape[1] _UpperCamelCase : Dict = self.tokenizer.padding_side if padding_side == "right": _UpperCamelCase : Any = [ list(_a ) + [self.label_pad_token_id] * (sequence_length - len(_a )) for label in labels ] else: _UpperCamelCase : List[str] = [ [self.label_pad_token_id] * (sequence_length - len(_a )) + list(_a ) for label in labels ] _UpperCamelCase : List[str] = [feature["""ner_tags"""] for feature in features] _UpperCamelCase : List[str] = padding_tensor(_a, -1, _a, _a ) _UpperCamelCase : Tuple = [feature["""original_entity_spans"""] for feature in features] _UpperCamelCase : Tuple = padding_tensor(_a, (-1, -1), _a, _a ) _UpperCamelCase : Optional[Any] = {k: torch.tensor(_a, dtype=torch.intaa ) for k, v in batch.items()} return batch
362
"""simple docstring""" def a_ ( _lowercase , _lowercase ): if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot be empty''' ) _UpperCamelCase : Optional[int] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_lowercase ) ) return round(_lowercase , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
128
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig class UpperCAmelCase (_UpperCAmelCase ): """simple docstring""" _UpperCAmelCase :List[Any] = "bert-generation" def __init__( self , _UpperCAmelCase=50358 , _UpperCAmelCase=1024 , _UpperCAmelCase=24 , _UpperCAmelCase=16 , _UpperCAmelCase=4096 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=512 , _UpperCAmelCase=0.02 , _UpperCAmelCase=1e-1_2 , _UpperCAmelCase=0 , _UpperCAmelCase=2 , _UpperCAmelCase=1 , _UpperCAmelCase="absolute" , _UpperCAmelCase=True , **_UpperCAmelCase , ): super().__init__(pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) lowercase__: str = vocab_size lowercase__: Optional[Any] = hidden_size lowercase__: Union[str, Any] = num_hidden_layers lowercase__: Dict = num_attention_heads lowercase__: Any = hidden_act lowercase__: Optional[Any] = intermediate_size lowercase__: Any = hidden_dropout_prob lowercase__: Optional[int] = attention_probs_dropout_prob lowercase__: Optional[int] = max_position_embeddings lowercase__: List[str] = initializer_range lowercase__: List[str] = layer_norm_eps lowercase__: Any = position_embedding_type lowercase__: Optional[Any] = use_cache
177
"""simple docstring""" import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: # Initialise PyTorch model lowercase__: Optional[Any] = FunnelConfig.from_json_file(__UpperCAmelCase ) print(F"""Building PyTorch model from configuration: {config}""" ) lowercase__: List[Any] = FunnelBaseModel(__UpperCAmelCase ) if base_model else FunnelModel(__UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_funnel(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __UpperCAmelCase ) if __name__ == "__main__": __A = 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( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not." ) __A = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
177
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : int = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : str = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
356
"""simple docstring""" import math def __UpperCAmelCase ( __lowerCamelCase ) -> str: lowercase__ : Tuple = 0 lowercase__ : Tuple = 0 while num > 0: lowercase__ : int = num % 8 lowercase__ : Tuple = octal + (remainder * math.floor(math.pow(10 , __lowerCamelCase ) )) counter += 1 lowercase__ : Optional[Any] = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"""0o{int(__lowerCamelCase )}""" def __UpperCAmelCase ( ) -> None: print('''\n2 in octal is:''' ) print(decimal_to_octal(2 ) ) # = 2 print('''\n8 in octal is:''' ) print(decimal_to_octal(8 ) ) # = 10 print('''\n65 in octal is:''' ) print(decimal_to_octal(65 ) ) # = 101 print('''\n216 in octal is:''' ) print(decimal_to_octal(2_16 ) ) # = 330 print('''\n512 in octal is:''' ) print(decimal_to_octal(5_12 ) ) # = 1000 print('''\n''' ) if __name__ == "__main__": main()
302
0
'''simple docstring''' import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() __lowercase : Dict = logging.get_logger(__name__) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any ): __a : List[str] = original_name.split('.' )[0] __a : Tuple = key.split('.' ) __a : Any = int(key_list[key_list.index(_SCREAMING_SNAKE_CASE ) - 2] ) __a : Union[str, Any] = int(key_list[key_list.index(_SCREAMING_SNAKE_CASE ) - 1] ) __a : List[Any] = orig_block_num - offset __a : List[Any] = key.replace(F"""{orig_block_num}.{layer_num}.{original_name}""" , F"""block.{new_block_num}.{layer_num}.{new_name}""" ) return key def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : Optional[int] = OrderedDict() __a , __a : Union[str, Any] = 0, 0 for key, value in state_dict.items(): if key.startswith('network' ): __a : Optional[int] = key.replace('network' , 'poolformer.encoder' ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith('bias' ) and "patch_embed" not in key: patch_emb_offset += 1 __a : Dict = key[: key.find('proj' )] __a : Union[str, Any] = key.replace(_SCREAMING_SNAKE_CASE , F"""patch_embeddings.{total_embed_found}.""" ) __a : List[str] = key.replace('proj' , 'projection' ) if key.endswith('bias' ): total_embed_found += 1 if "patch_embeddings" in key: __a : str = 'poolformer.encoder.' + key if "mlp.fc1" in key: __a : Any = replace_key_with_offset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'mlp.fc1' , 'output.conv1' ) if "mlp.fc2" in key: __a : str = replace_key_with_offset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'mlp.fc2' , 'output.conv2' ) if "norm1" in key: __a : Tuple = replace_key_with_offset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'norm1' , 'before_norm' ) if "norm2" in key: __a : str = replace_key_with_offset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'norm2' , 'after_norm' ) if "layer_scale_1" in key: __a : Any = replace_key_with_offset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'layer_scale_1' , 'layer_scale_1' ) if "layer_scale_2" in key: __a : Tuple = replace_key_with_offset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'layer_scale_2' , 'layer_scale_2' ) if "head" in key: __a : List[str] = key.replace('head' , 'classifier' ) __a : int = value return new_state_dict def lowerCamelCase (): __a : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __a : Optional[int] = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return image @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Tuple = PoolFormerConfig() # set attributes based on model_name __a : str = 'huggingface/label-files' __a : str = model_name[-3:] __a : Optional[int] = 1_000 __a : Optional[int] = 'imagenet-1k-id2label.json' __a : Any = (1, 1_000) # set config attributes __a : Optional[int] = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) __a : Optional[Any] = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a : Optional[Any] = idalabel __a : Optional[Any] = {v: k for k, v in idalabel.items()} if size == "s12": __a : int = [2, 2, 6, 2] __a : str = [64, 128, 320, 512] __a : Tuple = 4.0 __a : List[Any] = 0.9 elif size == "s24": __a : Union[str, Any] = [4, 4, 12, 4] __a : str = [64, 128, 320, 512] __a : Optional[Any] = 4.0 __a : Tuple = 0.9 elif size == "s36": __a : str = [6, 6, 18, 6] __a : str = [64, 128, 320, 512] __a : str = 4.0 __a : Any = 1e-6 __a : int = 0.9 elif size == "m36": __a : Any = [6, 6, 18, 6] __a : str = [96, 192, 384, 768] __a : Dict = 4.0 __a : Optional[Any] = 1e-6 __a : List[str] = 0.9_5 elif size == "m48": __a : Union[str, Any] = [8, 8, 24, 8] __a : List[str] = [96, 192, 384, 768] __a : Tuple = 4.0 __a : List[Any] = 1e-6 __a : int = 0.9_5 else: raise ValueError(F"""Size {size} not supported""" ) # load image processor __a : List[Any] = PoolFormerImageProcessor(crop_pct=_SCREAMING_SNAKE_CASE ) # Prepare image __a : Dict = prepare_img() __a : Dict = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values logger.info(F"""Converting model {model_name}...""" ) # load original state dict __a : Optional[int] = torch.load(_SCREAMING_SNAKE_CASE , map_location=torch.device('cpu' ) ) # rename keys __a : Optional[int] = rename_keys(_SCREAMING_SNAKE_CASE ) # create HuggingFace model and load state dict __a : Any = PoolFormerForImageClassification(_SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) model.eval() # Define image processor __a : Tuple = PoolFormerImageProcessor(crop_pct=_SCREAMING_SNAKE_CASE ) __a : Tuple = image_processor(images=prepare_img() , return_tensors='pt' ).pixel_values # forward pass __a : int = model(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = outputs.logits # define expected logit slices for different models if size == "s12": __a : str = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": __a : Tuple = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": __a : List[Any] = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": __a : Any = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": __a : Dict = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(F"""Size {size} not supported""" ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-2 ) # finally, save model and image processor logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Tuple = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, 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 folder to output PyTorch model.' ) __lowercase : Dict = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
27
import math import sys def lowerCAmelCase_ ( _lowercase : str) -> str: """simple docstring""" a__ : str = """""" try: with open(_lowercase , """rb""") as binary_file: a__ : Any = binary_file.read() for dat in data: a__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""") sys.exit() def lowerCAmelCase_ ( _lowercase : str) -> str: """simple docstring""" a__ : Optional[Any] = {"""0""": """0""", """1""": """1"""} a__ , a__ : Optional[int] = """""", """""" a__ : int = len(_lowercase) for i in range(len(_lowercase)): curr_string += data_bits[i] if curr_string not in lexicon: continue a__ : List[str] = lexicon[curr_string] result += last_match_id a__ : Any = last_match_id + """0""" if math.loga(_lowercase).is_integer(): a__ : Union[str, Any] = {} for curr_key in list(_lowercase): a__ : Optional[Any] = lexicon.pop(_lowercase) a__ : Union[str, Any] = new_lex a__ : str = last_match_id + """1""" index += 1 a__ : List[Any] = """""" return result def lowerCAmelCase_ ( _lowercase : str , _lowercase : str) -> None: """simple docstring""" a__ : List[Any] = 8 try: with open(_lowercase , """wb""") as opened_file: a__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(_lowercase) , _lowercase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("""10000000""") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(_lowercase , 2).to_bytes(1 , byteorder="""big""")) except OSError: print("""File not accessible""") sys.exit() def lowerCAmelCase_ ( _lowercase : str) -> str: """simple docstring""" a__ : Any = 0 for letter in data_bits: if letter == "1": break counter += 1 a__ : Optional[Any] = data_bits[counter:] a__ : Tuple = data_bits[counter + 1 :] return data_bits def lowerCAmelCase_ ( _lowercase : str , _lowercase : str) -> None: """simple docstring""" a__ : Dict = read_file_binary(_lowercase) a__ : str = remove_prefix(_lowercase) a__ : List[str] = decompress_data(_lowercase) write_file_binary(_lowercase , _lowercase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
170
0
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class _SCREAMING_SNAKE_CASE ( snake_case_ ): snake_case__ : Any = 4_2 snake_case__ : List[Any] = 4_2 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.26.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('''>=''', '''0.0.12''') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class _SCREAMING_SNAKE_CASE ( snake_case_ ): snake_case__ : Tuple = 4_2 snake_case__ : List[Any] = 4_2 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
353
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] ) -> str: """simple docstring""" if "model" in orig_key: UpperCamelCase :Union[str, Any] = orig_key.replace("""model.""" , """""" ) if "norm1" in orig_key: UpperCamelCase :Optional[int] = orig_key.replace("""norm1""" , """attention.output.LayerNorm""" ) if "norm2" in orig_key: UpperCamelCase :Optional[int] = orig_key.replace("""norm2""" , """output.LayerNorm""" ) if "norm" in orig_key: UpperCamelCase :Optional[int] = orig_key.replace("""norm""" , """LayerNorm""" ) if "transformer" in orig_key: UpperCamelCase :Any = orig_key.split(""".""" )[0].split("""_""" )[-1] UpperCamelCase :List[str] = orig_key.replace(f"""transformer_{layer_num}""" , f"""encoder.layer.{layer_num}""" ) if "mha.attn" in orig_key: UpperCamelCase :str = orig_key.replace("""mha.attn""" , """attention.self""" ) if "mha" in orig_key: UpperCamelCase :List[str] = orig_key.replace("""mha""" , """attention""" ) if "W_q" in orig_key: UpperCamelCase :Optional[Any] = orig_key.replace("""W_q""" , """self.query""" ) if "W_k" in orig_key: UpperCamelCase :Optional[Any] = orig_key.replace("""W_k""" , """self.key""" ) if "W_v" in orig_key: UpperCamelCase :List[Any] = orig_key.replace("""W_v""" , """self.value""" ) if "ff1" in orig_key: UpperCamelCase :Dict = orig_key.replace("""ff1""" , """intermediate.dense""" ) if "ff2" in orig_key: UpperCamelCase :List[Any] = orig_key.replace("""ff2""" , """output.dense""" ) if "ff" in orig_key: UpperCamelCase :Optional[int] = orig_key.replace("""ff""" , """output.dense""" ) if "mlm_class" in orig_key: UpperCamelCase :Dict = orig_key.replace("""mlm.mlm_class""" , """cls.predictions.decoder""" ) if "mlm" in orig_key: UpperCamelCase :Tuple = orig_key.replace("""mlm""" , """cls.predictions.transform""" ) if "cls" not in orig_key: UpperCamelCase :Any = """yoso.""" + orig_key return orig_key def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ) -> Any: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase :Any = orig_state_dict.pop(__magic_name__ ) if ("pooler" in key) or ("sen_class" in key): continue else: UpperCamelCase :Tuple = val UpperCamelCase :Dict = orig_state_dict["""cls.predictions.decoder.bias"""] UpperCamelCase :Union[str, Any] = torch.arange(__magic_name__ ).expand((1, -1) ) + 2 return orig_state_dict def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :Optional[Any] = torch.load(__magic_name__ , map_location="""cpu""" )["""model_state_dict"""] UpperCamelCase :int = YosoConfig.from_json_file(__magic_name__ ) UpperCamelCase :Optional[Any] = YosoForMaskedLM(__magic_name__ ) UpperCamelCase :int = convert_checkpoint_helper(config.max_position_embeddings , __magic_name__ ) print(model.load_state_dict(__magic_name__ ) ) model.eval() model.save_pretrained(__magic_name__ ) print(f"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--pytorch_model_path''', default=None, type=str, required=True, help='''Path to YOSO pytorch checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The json file for YOSO model config.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase_ : Dict = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
62
0
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowercase_ = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n" class __A ( unittest.TestCase , A ): '''simple docstring''' def a__ (self ) -> Union[str, Any]: """simple docstring""" _a = load_tool('''text-question-answering''' ) self.tool.setup() _a = load_tool('''text-question-answering''' , remote=A ) def a__ (self ) -> Any: """simple docstring""" _a = self.tool(A , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(A , '''launched the BigScience Research Workshop''' ) def a__ (self ) -> Tuple: """simple docstring""" _a = self.remote_tool(A , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(A , '''launched the BigScience Research Workshop''' ) def a__ (self ) -> int: """simple docstring""" _a = self.tool(text=A , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(A , '''launched the BigScience Research Workshop''' ) def a__ (self ) -> str: """simple docstring""" _a = self.remote_tool(text=A , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(A , '''launched the BigScience Research Workshop''' )
211
'''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_ = logging.get_logger(__name__) lowercase_ = "▁" lowercase_ = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } lowercase_ = { "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_ = { "facebook/m2m100_418M": 1_024, } # fmt: off lowercase_ = { "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 __A ( A ): '''simple docstring''' __lowerCamelCase : Union[str, Any] = VOCAB_FILES_NAMES __lowerCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : Dict = ['input_ids', 'attention_mask'] __lowerCamelCase : List[int] = [] __lowerCamelCase : List[int] = [] def __init__(self , A , A , A=None , A=None , A="<s>" , A="</s>" , A="</s>" , A="<pad>" , A="<unk>" , A="m2m100" , A = None , A=8 , **A , ) -> None: """simple docstring""" _a = {} if sp_model_kwargs is None else sp_model_kwargs _a = language_codes _a = FAIRSEQ_LANGUAGE_CODES[language_codes] _a = {lang_code: f'''__{lang_code}__''' for lang_code in fairseq_language_code} _a = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(A ) for lang_code in fairseq_language_code if self.get_lang_token(A ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=A , tgt_lang=A , bos_token=A , eos_token=A , sep_token=A , unk_token=A , pad_token=A , language_codes=A , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=A , **A , ) _a = vocab_file _a = load_json(A ) _a = {v: k for k, v in self.encoder.items()} _a = spm_file _a = load_spm(A , self.sp_model_kwargs ) _a = len(self.encoder ) _a = { self.get_lang_token(A ): self.encoder_size + i for i, lang_code in enumerate(A ) } _a = {lang_code: self.encoder_size + i for i, lang_code in enumerate(A )} _a = {v: k for k, v in self.lang_token_to_id.items()} _a = src_lang if src_lang is not None else '''en''' _a = tgt_lang _a = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) _a = num_madeup_words @property def a__ (self ) -> int: """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def a__ (self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def a__ (self , A ) -> None: """simple docstring""" _a = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def a__ (self , A ) -> List[str]: """simple docstring""" return self.sp_model.encode(A , out_type=A ) def a__ (self , A ) -> Union[str, Any]: """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(A , self.encoder[self.unk_token] ) def a__ (self , A ) -> str: """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(A , self.unk_token ) def a__ (self , A ) -> Dict: """simple docstring""" _a = [] _a = '''''' 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(A ) + token _a = [] else: current_sub_tokens.append(A ) out_string += self.sp_model.decode(A ) return out_string.strip() def a__ (self , A , A = None , A = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A , token_ids_a=A , already_has_special_tokens=A ) _a = [1] * len(self.prefix_tokens ) _a = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(A )) + suffix_ones return prefix_ones + ([0] * len(A )) + ([0] * len(A )) + suffix_ones def a__ (self , A , A = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def a__ (self ) -> Dict: """simple docstring""" _a = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__(self ) -> Dict: """simple docstring""" _a = self.__dict__.copy() _a = None return state def __setstate__(self , A ) -> None: """simple docstring""" _a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _a = {} _a = load_spm(self.spm_file , self.sp_model_kwargs ) def a__ (self , A , A = None ) -> Tuple[str]: """simple docstring""" _a = Path(A ) if not save_dir.is_dir(): raise OSError(f'''{save_directory} should be a directory''' ) _a = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) _a = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , A ) if os.path.abspath(self.spm_file ) != os.path.abspath(A ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , A ) elif not os.path.isfile(self.spm_file ): with open(A , '''wb''' ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(A ) return (str(A ), str(A )) def a__ (self , A , A = "en" , A = None , A = "ro" , **A , ) -> BatchEncoding: """simple docstring""" _a = src_lang _a = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(A , A , **A ) def a__ (self , A , A , A , **A ) -> Union[str, Any]: """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''' ) _a = src_lang _a = self(A , add_special_tokens=A , **A ) _a = self.get_lang_id(A ) _a = tgt_lang_id return inputs def a__ (self ) -> Optional[Any]: """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def a__ (self ) -> Tuple: """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def a__ (self , A ) -> None: """simple docstring""" _a = self.get_lang_token(A ) _a = self.lang_token_to_id[lang_token] _a = [self.cur_lang_id] _a = [self.eos_token_id] def a__ (self , A ) -> None: """simple docstring""" _a = self.get_lang_token(A ) _a = self.lang_token_to_id[lang_token] _a = [self.cur_lang_id] _a = [self.eos_token_id] def a__ (self , A ) -> str: """simple docstring""" return self.lang_code_to_token[lang] def a__ (self , A ) -> int: """simple docstring""" _a = self.get_lang_token(A ) return self.lang_token_to_id[lang_token] def lowerCAmelCase (__A , __A): """simple docstring""" _a = sentencepiece.SentencePieceProcessor(**__A) spm.Load(str(__A)) return spm def lowerCAmelCase (__A): """simple docstring""" with open(__A , '''r''') as f: return json.load(__A) def lowerCAmelCase (__A , __A): """simple docstring""" with open(__A , '''w''') as f: json.dump(__A , __A , indent=2)
211
1
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list , __lowerCAmelCase : int | None = None , __lowerCAmelCase : int | None = None ) -> None: if start is None: __lowerCamelCase = 0 if end is None: __lowerCamelCase = len(__lowerCAmelCase ) - 1 if start >= end: return __lowerCamelCase = (start + end) // 2 slowsort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) slowsort(__lowerCAmelCase , mid + 1 , __lowerCAmelCase ) if sequence[end] < sequence[mid]: __lowerCamelCase , __lowerCamelCase = sequence[mid], sequence[end] slowsort(__lowerCAmelCase , __lowerCAmelCase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
339
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Any = TypeVar("KEY") SCREAMING_SNAKE_CASE__ : Dict = TypeVar("VAL") @dataclass(frozen=__lowercase , slots=__lowercase ) class lowerCAmelCase__ ( Generic[KEY, VAL] ): a__ : KEY a__ : VAL class lowerCAmelCase__ ( _Item ): def __init__( self : str ) -> None: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __bool__( self : Tuple ) -> bool: return False SCREAMING_SNAKE_CASE__ : List[Any] = _DeletedItem() class lowerCAmelCase__ ( MutableMapping[KEY, VAL] ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.75 ) -> None: __lowerCamelCase = initial_block_size __lowerCamelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __lowerCamelCase = capacity_factor __lowerCamelCase = 0 def __A ( self : Any , SCREAMING_SNAKE_CASE__ : KEY ) -> int: return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: return (ind + 1) % len(self._buckets ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> bool: __lowerCamelCase = self._buckets[ind] if not stored: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self._len += 1 return True elif stored.key == key: __lowerCamelCase = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return True else: return False def __A ( self : Any ) -> bool: __lowerCamelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False __lowerCamelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __A ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> None: __lowerCamelCase = self._buckets __lowerCamelCase = [None] * new_size __lowerCamelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __A ( self : str ) -> None: self._resize(len(self._buckets ) * 2 ) def __A ( self : Dict ) -> None: self._resize(len(self._buckets ) // 2 ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY ) -> Iterator[int]: __lowerCamelCase = self._get_bucket_index(SCREAMING_SNAKE_CASE__ ) for _ in range(len(self._buckets ) ): yield ind __lowerCamelCase = self._get_next_ind(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): break def __setitem__( self : Tuple , SCREAMING_SNAKE_CASE__ : KEY , SCREAMING_SNAKE_CASE__ : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __delitem__( self : List[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> None: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: raise KeyError(SCREAMING_SNAKE_CASE__ ) if item is _deleted: continue if item.key == key: __lowerCamelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : KEY ) -> VAL: for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(SCREAMING_SNAKE_CASE__ ) def __len__( self : int ) -> int: return self._len def __iter__( self : Tuple ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[Any] ) -> str: __lowerCamelCase = ''' ,'''.join( f'''{item.key}: {item.val}''' for item in self._buckets if item ) return f'''HashMap({val_string})'''
339
1
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json UpperCAmelCase__ : List[Any] = "sshleifer/mar_enro_6_3_student" class a__ ( A__ ): """simple docstring""" def _lowercase ( self : Tuple ) ->Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE : List[Any] = cached_path( """https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz""" , extract_compressed_file=_a , ) SCREAMING_SNAKE_CASE : Optional[int] = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def _lowercase ( self : List[Any] ) ->str: """simple docstring""" MarianMTModel.from_pretrained(_a ) @slow @require_torch_gpu def _lowercase ( self : int ) ->Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = { """$MAX_LEN""": 6_4, """$BS""": 6_4, """$GAS""": 1, """$ENRO_DIR""": self.data_dir, """facebook/mbart-large-cc25""": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", """--learning_rate=3e-5""": """--learning_rate 3e-4""", """--num_train_epochs 6""": """--num_train_epochs 1""", } # Clean up bash script SCREAMING_SNAKE_CASE : Any = (self.test_file_dir / """train_mbart_cc25_enro.sh""").open().read().split("""finetune.py""" )[1].strip() SCREAMING_SNAKE_CASE : List[Any] = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE : List[Any] = bash_script.replace(_a , str(_a ) ) SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE : Optional[Any] = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE : Optional[Any] = ["""finetune.py"""] + bash_script.split() + args with patch.object(_a , """argv""" , _a ): SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() SCREAMING_SNAKE_CASE : Union[str, Any] = pl.Trainer.add_argparse_args(_a ) SCREAMING_SNAKE_CASE : Tuple = SummarizationModule.add_model_specific_args(_a , os.getcwd() ) SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE : List[Any] = main(_a ) # Check metrics SCREAMING_SNAKE_CASE : List[str] = load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE : Tuple = metrics["""val"""][0] SCREAMING_SNAKE_CASE : int = metrics["""val"""][-1] self.assertEqual(len(metrics["""val"""] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , _a ) self.assertGreater(last_step_stats["""val_avg_gen_time"""] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["""val_avg_gen_time"""] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["""val_avg_bleu"""] - first_step_stats["""val_avg_bleu"""] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["""val_avg_bleu"""] , 1_7 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["""val"""][-1]["""val_avg_bleu"""] - metrics["""test"""][-1]["""test_avg_bleu"""] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE : Dict = os.listdir(_a ) SCREAMING_SNAKE_CASE : Dict = [x for x in contents if x.endswith(""".ckpt""" )][0] SCREAMING_SNAKE_CASE : Dict = os.path.join(args.output_dir , _a ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.load(_a , map_location="""cpu""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE : Optional[int] = {os.path.basename(_a ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1 class a__ ( A__ ): """simple docstring""" @timeout_decorator.timeout(6_0_0 ) @slow @require_torch_gpu def _lowercase ( self : List[str] ) ->List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : str = f"{self.test_file_dir_str}/test_data/wmt_en_ro" SCREAMING_SNAKE_CASE : Optional[Any] = { """--fp16_opt_level=O1""": """""", """$MAX_LEN""": 1_2_8, """$BS""": 1_6, """$GAS""": 1, """$ENRO_DIR""": data_dir, """$m""": """sshleifer/student_marian_en_ro_6_1""", """val_check_interval=0.25""": """val_check_interval=1.0""", } # Clean up bash script SCREAMING_SNAKE_CASE : str = ( (self.test_file_dir / """distil_marian_no_teacher.sh""").open().read().split("""distillation.py""" )[1].strip() ) SCREAMING_SNAKE_CASE : Optional[int] = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) SCREAMING_SNAKE_CASE : List[str] = bash_script.replace("""--fp16 """ , """ """ ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE : Optional[int] = bash_script.replace(_a , str(_a ) ) SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = bash_script.replace("""--fp16""" , """""" ) SCREAMING_SNAKE_CASE : Any = 6 SCREAMING_SNAKE_CASE : Optional[int] = ( ["""distillation.py"""] + bash_script.split() + [ f"--output_dir={output_dir}", """--gpus=1""", """--learning_rate=1e-3""", f"--num_train_epochs={epochs}", """--warmup_steps=10""", """--val_check_interval=1.0""", """--do_predict""", ] ) with patch.object(_a , """argv""" , _a ): SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser() SCREAMING_SNAKE_CASE : Any = pl.Trainer.add_argparse_args(_a ) SCREAMING_SNAKE_CASE : Dict = SummarizationDistiller.add_model_specific_args(_a , os.getcwd() ) SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE : int = distill_main(_a ) # Check metrics SCREAMING_SNAKE_CASE : Optional[int] = load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE : Dict = metrics["""val"""][0] SCREAMING_SNAKE_CASE : Optional[Any] = metrics["""val"""][-1] assert len(metrics["""val"""] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , _a ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE : List[str] = os.listdir(_a ) SCREAMING_SNAKE_CASE : int = [x for x in contents if x.endswith(""".ckpt""" )][0] SCREAMING_SNAKE_CASE : List[Any] = os.path.join(args.output_dir , _a ) SCREAMING_SNAKE_CASE : List[Any] = torch.load(_a , map_location="""cpu""" ) SCREAMING_SNAKE_CASE : Tuple = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE : int = {os.path.basename(_a ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1
245
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Any=False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =OmegaConf.load(_UpperCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_UpperCamelCase ) ) ) return config def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Union[str, Any]=None ) -> Optional[Any]: """simple docstring""" if conf_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.yaml' _SCREAMING_SNAKE_CASE =load_config(_UpperCamelCase , display=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VQModel(**config.model.params ) if ckpt_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.pt' _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) if ".ckpt" in ckpt_path: _SCREAMING_SNAKE_CASE =sd['state_dict'] model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.to(_UpperCamelCase ) del sd return model def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : int ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encode(_UpperCamelCase ) print(f"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) _SCREAMING_SNAKE_CASE =model.decode(_UpperCamelCase ) return xrec def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str]=False ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =string.rsplit('.' , 1 ) if reload: _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) importlib.reload(_UpperCamelCase ) return getattr(importlib.import_module(_UpperCamelCase , package=_UpperCamelCase ) , cls ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> List[str]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =instantiate_from_config(_UpperCamelCase ) if sd is not None: model.load_state_dict(_UpperCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if ckpt: _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =pl_sd['global_step'] print(f"loaded model from global step {global_step}." ) else: _SCREAMING_SNAKE_CASE ={'state_dict': None} _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =load_model_from_config(config.model , pl_sd['state_dict'] , gpu=_UpperCamelCase , eval_mode=_UpperCamelCase )['model'] return model, global_step
47
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase_ : int = { '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: UpperCAmelCase_ : List[Any] = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] UpperCAmelCase_ : str = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] UpperCAmelCase_ : List[Any] = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): UpperCAmelCase_ : str = [ '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 UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
353
def SCREAMING_SNAKE_CASE_ ( __A : int ) -> int: """simple docstring""" if n == 1 or not isinstance(__A , __A ): return 0 elif n == 2: return 1 else: a_ : int = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def SCREAMING_SNAKE_CASE_ ( __A : int ) -> int: """simple docstring""" a_ : Any = 0 a_ : Optional[Any] = 2 while digits < n: index += 1 a_ : List[Any] = len(str(fibonacci(__A ) ) ) return index def SCREAMING_SNAKE_CASE_ ( __A : int = 10_00 ) -> int: """simple docstring""" return fibonacci_digits_index(__A ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
120
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor _A : Any = logging.get_logger(__name__) class _lowercase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> None: warnings.warn( """The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use GLPNImageProcessor instead.""" , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
229
'''simple docstring''' def UpperCamelCase_ ( snake_case_ : list[int] , snake_case_ : list[int] ) -> tuple[float, float]: '''simple docstring''' if not len(snake_case_ ) == len(snake_case_ ) == 3: raise ValueError("""Please enter a valid equation.""" ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError("""Both a & b of two equations can't be zero.""" ) # Extract the coefficients __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = equationa __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = equationa # Calculate the determinants of the matrices __lowerCAmelCase = aa * ba - aa * ba __lowerCAmelCase = ca * ba - ca * ba __lowerCAmelCase = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("""Infinite solutions. (Consistent system)""" ) else: raise ValueError("""No solution. (Inconsistent system)""" ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __lowerCAmelCase = determinant_x / determinant __lowerCAmelCase = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
229
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase : Tuple = { """configuration_pegasus_x""": ["""PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PegasusXConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : Union[str, Any] = [ """PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST""", """PegasusXForConditionalGeneration""", """PegasusXModel""", """PegasusXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys UpperCamelCase : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
345
'''simple docstring''' def SCREAMING_SNAKE_CASE__ ( snake_case : int , snake_case : int ) -> bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
345
1
def snake_case_ ( snake_case , snake_case ) -> str: lowercase__: int = '' for i in table: res += inp[i - 1] return res def snake_case_ ( snake_case ) -> List[str]: return data[1:] + data[0] def snake_case_ ( snake_case , snake_case ) -> List[Any]: lowercase__: List[str] = '' for i in range(len(snake_case ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def snake_case_ ( snake_case , snake_case ) -> Tuple: lowercase__: List[str] = int('0b' + data[0] + data[-1] , 2 ) lowercase__: List[str] = int('0b' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def snake_case_ ( snake_case , snake_case , snake_case , snake_case , snake_case ) -> List[str]: lowercase__: Any = message[:4] lowercase__: Optional[Any] = message[4:] lowercase__: Dict = apply_table(snake_case , snake_case ) lowercase__: Optional[int] = xor(snake_case , snake_case ) lowercase__: Optional[int] = apply_sbox(snake_case , temp[:4] ) # noqa: E741 lowercase__: Optional[int] = apply_sbox(snake_case , temp[4:] ) lowercase__: Tuple = '0' * (2 - len(snake_case )) + l # noqa: E741 lowercase__: int = '0' * (2 - len(snake_case )) + r lowercase__: Optional[Any] = apply_table(l + r , snake_case ) lowercase__: Optional[Any] = xor(snake_case , snake_case ) return temp + right if __name__ == "__main__": __lowerCAmelCase = input('''Enter 10 bit key: ''') __lowerCAmelCase = input('''Enter 8 bit message: ''') __lowerCAmelCase = [6, 3, 7, 4, 8, 5, 10, 9] __lowerCAmelCase = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] __lowerCAmelCase = [2, 4, 3, 1] __lowerCAmelCase = [2, 6, 3, 1, 4, 8, 5, 7] __lowerCAmelCase = [4, 1, 3, 5, 7, 2, 8, 6] __lowerCAmelCase = [4, 1, 2, 3, 2, 3, 4, 1] __lowerCAmelCase = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] __lowerCAmelCase = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation __lowerCAmelCase = apply_table(key, paa_table) __lowerCAmelCase = temp[:5] __lowerCAmelCase = temp[5:] __lowerCAmelCase = left_shift(left) __lowerCAmelCase = left_shift(right) __lowerCAmelCase = apply_table(left + right, pa_table) __lowerCAmelCase = left_shift(left) __lowerCAmelCase = left_shift(right) __lowerCAmelCase = left_shift(left) __lowerCAmelCase = left_shift(right) __lowerCAmelCase = apply_table(left + right, pa_table) # encryption __lowerCAmelCase = apply_table(message, IP) __lowerCAmelCase = function(expansion, sa, sa, keya, temp) __lowerCAmelCase = temp[4:] + temp[:4] __lowerCAmelCase = function(expansion, sa, sa, keya, temp) __lowerCAmelCase = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption __lowerCAmelCase = apply_table(CT, IP) __lowerCAmelCase = function(expansion, sa, sa, keya, temp) __lowerCAmelCase = temp[4:] + temp[:4] __lowerCAmelCase = function(expansion, sa, sa, keya, temp) __lowerCAmelCase = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
196
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __lowerCAmelCase = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''') @require_sentencepiece @require_tokenizers class __a ( __UpperCamelCase , unittest.TestCase ): __lowercase : int = PegasusTokenizer __lowercase : Any = PegasusTokenizerFast __lowercase : Optional[int] = True __lowercase : Tuple = True def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowercase__: List[str] = PegasusTokenizer(lowerCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def SCREAMING_SNAKE_CASE__ ( self , **lowerCAmelCase__ ) -> PegasusTokenizer: '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' lowercase__: Optional[Any] = '</s>' lowercase__: Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ) , lowerCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ) , lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' lowercase__: Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(lowerCAmelCase__ ) , 1_103 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_103 ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' lowercase__: Dict = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) lowercase__: Optional[int] = self.tokenizer_class.from_pretrained(self.tmpdirname ) lowercase__: Optional[Any] = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) lowercase__: Dict = rust_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0] lowercase__: Tuple = py_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0] self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' lowercase__: int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word lowercase__: Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' lowercase__: Union[str, Any] = [2, 413, 615, 114, 3, 1_971, 113, 1_679, 10_710, 107, 1] lowercase__: int = tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ ).input_ids[0] self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' lowercase__: Optional[int] = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 96_103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_024 lowercase__: int = 'To ensure a smooth flow of bank resolutions.' lowercase__: Any = [413, 615, 114, 2_291, 1_971, 113, 1_679, 10_710, 107, 1] lowercase__: str = tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ ).input_ids[0] self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' lowercase__: Any = ['This is going to be way too long.' * 150, 'short example'] lowercase__: Tuple = ['not super long but more than 5 tokens', 'tiny'] lowercase__: Dict = self._large_tokenizer(lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' ) lowercase__: Any = self._large_tokenizer( text_target=lowerCAmelCase__ , max_length=5 , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1_024) assert batch.attention_mask.shape == (2, 1_024) assert targets["input_ids"].shape == (2, 5) assert len(lowerCAmelCase__ ) == 2 # input_ids, attention_mask. @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' # fmt: off lowercase__: List[str] = {'input_ids': [[38_979, 143, 18_485, 606, 130, 26_669, 87_686, 121, 54_189, 1_129, 111, 26_669, 87_686, 121, 9_114, 14_787, 121, 13_249, 158, 592, 956, 121, 14_621, 31_576, 143, 62_613, 108, 9_688, 930, 43_430, 11_562, 62_613, 304, 108, 11_443, 897, 108, 9_314, 17_415, 63_399, 108, 11_443, 7_614, 18_316, 118, 4_284, 7_148, 12_430, 143, 1_400, 25_703, 158, 111, 4_284, 7_148, 11_772, 143, 21_297, 1_064, 158, 122, 204, 3_506, 1_754, 1_133, 14_787, 1_581, 115, 33_224, 4_482, 111, 1_355, 110, 29_173, 317, 50_833, 108, 20_147, 94_665, 111, 77_198, 107, 1], [110, 62_613, 117, 638, 112, 1_133, 121, 20_098, 1_355, 79_050, 13_872, 135, 1_596, 53_541, 1_352, 141, 13_039, 5_542, 124, 302, 518, 111, 268, 2_956, 115, 149, 4_427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1_235, 2_799, 18_289, 17_780, 204, 109, 9_474, 1_296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase__ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class __a ( __UpperCamelCase , unittest.TestCase ): __lowercase : int = PegasusTokenizer __lowercase : Any = PegasusTokenizerFast __lowercase : Any = True __lowercase : Dict = True def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowercase__: Union[str, Any] = PegasusTokenizer(lowerCAmelCase__ , offset=0 , mask_token_sent=lowerCAmelCase__ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def SCREAMING_SNAKE_CASE__ ( self , **lowerCAmelCase__ ) -> PegasusTokenizer: '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' lowercase__: str = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) lowercase__: str = self.tokenizer_class.from_pretrained(self.tmpdirname ) lowercase__: Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) lowercase__: List[Any] = rust_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0] lowercase__: Any = py_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0] self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' lowercase__: List[Any] = ['This is going to be way too long.' * 1_000, 'short example'] lowercase__: str = ['not super long but more than 5 tokens', 'tiny'] lowercase__: Tuple = self._large_tokenizer(lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' ) lowercase__: Dict = self._large_tokenizer( text_target=lowerCAmelCase__ , max_length=5 , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4_096) assert batch.attention_mask.shape == (2, 4_096) assert targets["input_ids"].shape == (2, 5) assert len(lowerCAmelCase__ ) == 2 # input_ids, attention_mask. def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' lowercase__: str = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) lowercase__: Optional[int] = self._large_tokenizer(lowerCAmelCase__ ).input_ids self.assertListEqual( lowerCAmelCase__ , [182, 117, 142, 587, 4_211, 120, 117, 263, 112, 804, 109, 856, 25_016, 3_137, 464, 109, 26_955, 3_137, 1] , )
196
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import 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 ( __a ): '''simple docstring''' _A : Tuple = '''microsoft/speecht5_tts''' _A : List[str] = ( '''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.''' ) _A : Optional[int] = '''text_reader''' _A : List[Any] = SpeechTaProcessor _A : List[Any] = SpeechTaForTextToSpeech _A : Union[str, Any] = SpeechTaHifiGan _A : Tuple = ['''text'''] _A : Union[str, Any] = ['''audio'''] def lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" if self.post_processor is None: __lowercase : List[str] = """microsoft/speecht5_hifigan""" super().setup() def lowerCAmelCase ( self : Any , __a : Optional[int] , __a : int=None ) -> Any: """simple docstring""" __lowercase : Optional[Any] = self.pre_processor(text=__a , return_tensors="""pt""" , truncation=__a ) if speaker_embeddings is None: if not is_datasets_available(): raise ImportError("""Datasets needs to be installed if not passing speaker embeddings.""" ) __lowercase : Union[str, Any] = load_dataset("""Matthijs/cmu-arctic-xvectors""" , split="""validation""" ) __lowercase : Any = torch.tensor(embeddings_dataset[7305]["""xvector"""] ).unsqueeze(0 ) return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings} def lowerCAmelCase ( self : Tuple , __a : Any ) -> Any: """simple docstring""" with torch.no_grad(): return self.model.generate_speech(**__a ) def lowerCAmelCase ( self : int , __a : Union[str, Any] ) -> int: """simple docstring""" with torch.no_grad(): return self.post_processor(__a ).cpu().detach()
370
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate lowerCamelCase : str = trt.Logger(trt.Logger.WARNING) lowerCamelCase : Any = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) lowerCamelCase : Optional[Any] = logging.getLogger(__name__) lowerCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) lowerCamelCase : Dict = parser.parse_args() if args.tokenizer_name: lowerCamelCase : str = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) 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.''' ) logger.info('''Training/evaluation parameters %s''', args) lowerCamelCase : List[str] = args.per_device_eval_batch_size lowerCamelCase : Any = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties lowerCamelCase : List[str] = True lowerCamelCase : List[Any] = '''temp_engine/bert-fp32.engine''' if args.fpaa: lowerCamelCase : Optional[Any] = '''temp_engine/bert-fp16.engine''' if args.inta: lowerCamelCase : int = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') lowerCamelCase : int = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network lowerCamelCase : Union[str, Any] = [network.get_input(i) for i in range(network.num_inputs)] lowerCamelCase : Dict = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: lowerCamelCase : List[str] = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) lowerCamelCase : Optional[int] = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) lowerCamelCase : Optional[Any] = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def snake_case_ ( lowerCAmelCase_ : Any , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Tuple ): __lowercase : List[str] = np.asarray(inputs["""input_ids"""] , dtype=np.intaa ) __lowercase : Union[str, Any] = np.asarray(inputs["""attention_mask"""] , dtype=np.intaa ) __lowercase : int = np.asarray(inputs["""token_type_ids"""] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowerCAmelCase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowerCAmelCase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowerCAmelCase_ ) # start time __lowercase : Optional[Any] = time.time() # Run inference context.execute_async( bindings=[int(lowerCAmelCase_ ) for d_inp in d_inputs] + [int(lowerCAmelCase_ ), int(lowerCAmelCase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) cuda.memcpy_dtoh_async(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Synchronize the stream and take time stream.synchronize() # end time __lowercase : int = time.time() __lowercase : Union[str, Any] = end_time - start_time __lowercase : Any = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. lowerCamelCase : Tuple = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(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). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowerCamelCase : List[Any] = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # 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. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. lowerCamelCase : Optional[Any] = raw_datasets['''validation'''].column_names lowerCamelCase : Union[str, Any] = '''question''' if '''question''' in column_names else column_names[0] lowerCamelCase : str = '''context''' if '''context''' in column_names else column_names[1] lowerCamelCase : Dict = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). lowerCamelCase : Dict = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'''The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the''' f'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' ) lowerCamelCase : Tuple = min(args.max_seq_length, tokenizer.model_max_length) def snake_case_ ( lowerCAmelCase_ : int ): # Some of the questions have lots of whitespace on the left, which is not useful and will make the # truncation of the context fail (the tokenized question will take a lots of space). So we remove that # left whitespace __lowercase : str = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __lowercase : List[str] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation="""only_second""" if pad_on_right else """only_first""" , max_length=lowerCAmelCase_ , stride=args.doc_stride , return_overflowing_tokens=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , padding="""max_length""" , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __lowercase : List[str] = tokenized_examples.pop("""overflow_to_sample_mapping""" ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __lowercase : Any = [] for i in range(len(tokenized_examples["""input_ids"""] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __lowercase : Dict = tokenized_examples.sequence_ids(lowerCAmelCase_ ) __lowercase : List[Any] = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __lowercase : List[str] = sample_mapping[i] tokenized_examples["example_id"].append(examples["""id"""][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __lowercase : Dict = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples["""offset_mapping"""][i] ) ] return tokenized_examples lowerCamelCase : Tuple = raw_datasets['''validation'''] # Validation Feature Creation lowerCamelCase : Optional[int] = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) lowerCamelCase : Union[str, Any] = default_data_collator lowerCamelCase : Optional[Any] = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) lowerCamelCase : List[str] = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def snake_case_ ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Dict="eval" ): # Post-processing: we match the start logits and end logits to answers in the original context. __lowercase : int = postprocess_qa_predictions( examples=lowerCAmelCase_ , features=lowerCAmelCase_ , predictions=lowerCAmelCase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowerCAmelCase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __lowercase : Optional[int] = [ {"""id""": k, """prediction_text""": v, """no_answer_probability""": 0.0} for k, v in predictions.items() ] else: __lowercase : List[Any] = [{"""id""": k, """prediction_text""": v} for k, v in predictions.items()] __lowercase : Optional[int] = [{"""id""": ex["""id"""], """answers""": ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowerCAmelCase_ , label_ids=lowerCAmelCase_ ) lowerCamelCase : Dict = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def snake_case_ ( lowerCAmelCase_ : str ): return trt.volume(engine.get_binding_shape(lowerCAmelCase_ ) ) * engine.get_binding_dtype(lowerCAmelCase_ ).itemsize # Allocate device memory for inputs and outputs. lowerCamelCase : int = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer lowerCamelCase : Dict = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) lowerCamelCase : str = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) lowerCamelCase : Dict = cuda.mem_alloc(h_outputa.nbytes) lowerCamelCase : Optional[Any] = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. lowerCamelCase : Optional[int] = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f''' Num examples = {len(eval_dataset)}''') logger.info(f''' Batch size = {args.per_device_eval_batch_size}''') lowerCamelCase : int = 0.0 lowerCamelCase : List[str] = 0 lowerCamelCase : List[str] = timeit.default_timer() lowerCamelCase : List[Any] = None for step, batch in enumerate(eval_dataloader): lowerCamelCase ,lowerCamelCase : str = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 lowerCamelCase ,lowerCamelCase : Union[str, Any] = outputs lowerCamelCase : Optional[Any] = torch.tensor(start_logits) lowerCamelCase : List[str] = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered lowerCamelCase : Optional[int] = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) lowerCamelCase : Dict = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) lowerCamelCase : List[Any] = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) lowerCamelCase : Dict = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: lowerCamelCase : Tuple = nested_truncate(all_preds, len(eval_dataset)) lowerCamelCase : Dict = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) lowerCamelCase : str = post_processing_function(eval_examples, eval_dataset, all_preds) lowerCamelCase : Optional[Any] = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'''Evaluation metrics: {eval_metric}''')
306
0
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _lowercase ( __snake_case ) -> Union[str, Any]: if is_torch_version("<" ,"2.0.0" ) or not hasattr(__snake_case ,"_dynamo" ): return False return isinstance(__snake_case ,torch._dynamo.eval_frame.OptimizedModule ) def _lowercase ( __snake_case ,__snake_case = True ) -> Union[str, Any]: __lowerCAmelCase : Dict = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __lowerCAmelCase : Optional[int] = is_compiled_module(__snake_case ) if is_compiled: __lowerCAmelCase : str = model __lowerCAmelCase : Any = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__snake_case ,__snake_case ): __lowerCAmelCase : Any = model.module if not keep_fpaa_wrapper: __lowerCAmelCase : Dict = getattr(__snake_case ,"forward" ) __lowerCAmelCase : Dict = model.__dict__.pop("_original_forward" ,__snake_case ) if original_forward is not None: while hasattr(__snake_case ,"__wrapped__" ): __lowerCAmelCase : List[str] = forward.__wrapped__ if forward == original_forward: break __lowerCAmelCase : Optional[int] = forward if getattr(__snake_case ,"_converted_to_transformer_engine" ,__snake_case ): convert_model(__snake_case ,to_transformer_engine=__snake_case ) if is_compiled: __lowerCAmelCase : Dict = model __lowerCAmelCase : Optional[Any] = compiled_model return model def _lowercase ( ) -> List[str]: PartialState().wait_for_everyone() def _lowercase ( __snake_case ,__snake_case ) -> List[str]: if PartialState().distributed_type == DistributedType.TPU: xm.save(__snake_case ,__snake_case ) elif PartialState().local_process_index == 0: torch.save(__snake_case ,__snake_case ) @contextmanager def _lowercase ( **__snake_case ) -> Optional[int]: for key, value in kwargs.items(): __lowerCAmelCase : List[Any] = str(__snake_case ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _lowercase ( __snake_case ) -> Tuple: if not hasattr(__snake_case ,"__qualname__" ) and not hasattr(__snake_case ,"__name__" ): __lowerCAmelCase : Union[str, Any] = getattr(__snake_case ,"__class__" ,__snake_case ) if hasattr(__snake_case ,"__qualname__" ): return obj.__qualname__ if hasattr(__snake_case ,"__name__" ): return obj.__name__ return str(__snake_case ) def _lowercase ( __snake_case ,__snake_case ) -> Dict: for key, value in source.items(): if isinstance(__snake_case ,__snake_case ): __lowerCAmelCase : Tuple = destination.setdefault(__snake_case ,{} ) merge_dicts(__snake_case ,__snake_case ) else: __lowerCAmelCase : List[Any] = value return destination def _lowercase ( __snake_case = None ) -> bool: if port is None: __lowerCAmelCase : str = 29_500 with socket.socket(socket.AF_INET ,socket.SOCK_STREAM ) as s: return s.connect_ex(("localhost", port) ) == 0
269
"""simple docstring""" from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def _lowercase ( __snake_case = "laptop" ) -> DataFrame: __lowerCAmelCase : str = F"""https://www.amazon.in/laptop/s?k={product}""" __lowerCAmelCase : Union[str, Any] = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } __lowerCAmelCase : List[str] = BeautifulSoup(requests.get(__snake_case ,headers=__snake_case ).text ) # Initialize a Pandas dataframe with the column titles __lowerCAmelCase : Dict = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div" ,attrs={"class": "s-result-item", "data-component-type": "s-search-result"} ,) ,soup.find_all("div" ,attrs={"class": "a-row a-size-base a-color-base"} ) ,): try: __lowerCAmelCase : Any = item.ha.text __lowerCAmelCase : Union[str, Any] = "https://www.amazon.in/" + item.ha.a["href"] __lowerCAmelCase : Any = item.find("span" ,attrs={"class": "a-offscreen"} ).text try: __lowerCAmelCase : Union[str, Any] = item.find("span" ,attrs={"class": "a-icon-alt"} ).text except AttributeError: __lowerCAmelCase : Optional[Any] = "Not available" try: __lowerCAmelCase : Union[str, Any] = ( "₹" + item.find( "span" ,attrs={"class": "a-price a-text-price"} ).text.split("₹" )[1] ) except AttributeError: __lowerCAmelCase : Dict = "" try: __lowerCAmelCase : str = float( ( ( float(product_mrp.strip("₹" ).replace("," ,"" ) ) - float(product_price.strip("₹" ).replace("," ,"" ) ) ) / float(product_mrp.strip("₹" ).replace("," ,"" ) ) ) * 100 ) except ValueError: __lowerCAmelCase : List[str] = float("nan" ) except AttributeError: pass __lowerCAmelCase : int = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __lowerCAmelCase : Union[str, Any] = " " __lowerCAmelCase : Union[str, Any] = " " data_frame.index += 1 return data_frame if __name__ == "__main__": __snake_case : Any = 'headphones' get_amazon_product_data(product).to_csv(F"""Amazon Product Data for {product}.csv""")
269
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _lowerCAmelCase :int = logging.get_logger(__name__) if is_vision_available(): import PIL class _UpperCAmelCase ( a ): '''simple docstring''' a__ =['''pixel_values'''] def __init__( self , A = True , A = None , A = PILImageResampling.BICUBIC , A = True , A = None , A = True , A = 1 / 2_5_5 , A = True , A = None , A = None , A = True , **A , ) -> None: super().__init__(**A ) _UpperCAmelCase : Optional[int] = size if size is not None else {'''shortest_edge''': 2_2_4} _UpperCAmelCase : Tuple = get_size_dict(A , default_to_square=A ) _UpperCAmelCase : Tuple = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} _UpperCAmelCase : List[str] = get_size_dict(A , default_to_square=A , param_name='''crop_size''' ) _UpperCAmelCase : int = do_resize _UpperCAmelCase : Optional[Any] = size _UpperCAmelCase : int = resample _UpperCAmelCase : Union[str, Any] = do_center_crop _UpperCAmelCase : Dict = crop_size _UpperCAmelCase : Optional[int] = do_rescale _UpperCAmelCase : Tuple = rescale_factor _UpperCAmelCase : List[str] = do_normalize _UpperCAmelCase : Optional[int] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _UpperCAmelCase : Optional[int] = image_std if image_std is not None else OPENAI_CLIP_STD _UpperCAmelCase : Any = do_convert_rgb def __lowerCAmelCase ( self , A , A , A = PILImageResampling.BICUBIC , A = None , **A , ) -> np.ndarray: _UpperCAmelCase : List[Any] = get_size_dict(A , default_to_square=A ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) _UpperCAmelCase : Dict = get_resize_output_image_size(A , size=size['''shortest_edge'''] , default_to_square=A ) return resize(A , size=A , resample=A , data_format=A , **A ) def __lowerCAmelCase ( self , A , A , A = None , **A , ) -> np.ndarray: _UpperCAmelCase : Any = get_size_dict(A ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A , size=(size['''height'''], size['''width''']) , data_format=A , **A ) def __lowerCAmelCase ( self , A , A , A = None , **A , ) -> Optional[int]: return rescale(A , scale=A , data_format=A , **A ) def __lowerCAmelCase ( self , A , A , A , A = None , **A , ) -> np.ndarray: return normalize(A , mean=A , std=A , data_format=A , **A ) def __lowerCAmelCase ( self , A , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = ChannelDimension.FIRST , **A , ) -> PIL.Image.Image: _UpperCAmelCase : List[Any] = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase : Any = size if size is not None else self.size _UpperCAmelCase : Dict = get_size_dict(A , param_name='''size''' , default_to_square=A ) _UpperCAmelCase : List[Any] = resample if resample is not None else self.resample _UpperCAmelCase : int = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCAmelCase : Tuple = crop_size if crop_size is not None else self.crop_size _UpperCAmelCase : str = get_size_dict(A , param_name='''crop_size''' , default_to_square=A ) _UpperCAmelCase : List[str] = do_rescale if do_rescale is not None else self.do_rescale _UpperCAmelCase : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCAmelCase : Any = do_normalize if do_normalize is not None else self.do_normalize _UpperCAmelCase : Tuple = image_mean if image_mean is not None else self.image_mean _UpperCAmelCase : int = image_std if image_std is not None else self.image_std _UpperCAmelCase : Tuple = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _UpperCAmelCase : int = make_list_of_images(A ) if not valid_images(A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: _UpperCAmelCase : Optional[int] = [convert_to_rgb(A ) for image in images] # All transformations expect numpy arrays. _UpperCAmelCase : Tuple = [to_numpy_array(A ) for image in images] if do_resize: _UpperCAmelCase : List[str] = [self.resize(image=A , size=A , resample=A ) for image in images] if do_center_crop: _UpperCAmelCase : Optional[int] = [self.center_crop(image=A , size=A ) for image in images] if do_rescale: _UpperCAmelCase : Union[str, Any] = [self.rescale(image=A , scale=A ) for image in images] if do_normalize: _UpperCAmelCase : str = [self.normalize(image=A , mean=A , std=A ) for image in images] _UpperCAmelCase : Dict = [to_channel_dimension_format(A , A ) for image in images] _UpperCAmelCase : str = {'''pixel_values''': images} return BatchFeature(data=A , tensor_type=A )
68
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase :int = logging.get_logger(__name__) _lowerCAmelCase :Union[str, Any] = { 'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json', 'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json', 'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json', 'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json', 'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json', 'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json', 'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json', 'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json', 'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json', 'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json', } class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''xlm''' a__ ={ '''hidden_size''': '''emb_dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', '''n_words''': '''vocab_size''', # For backward compatibility } def __init__( self , A=3_0_1_4_5 , A=2_0_4_8 , A=1_2 , A=1_6 , A=0.1 , A=0.1 , A=True , A=False , A=False , A=False , A=1 , A=True , A=5_1_2 , A=2_0_4_8**-0.5 , A=1E-12 , A=0.02 , A=0 , A=1 , A=2 , A=3 , A=5 , A=True , A="first" , A=True , A=None , A=True , A=0.1 , A=5 , A=5 , A=0 , A=0 , A=2 , A=0 , **A , ) -> Tuple: _UpperCAmelCase : Dict = vocab_size _UpperCAmelCase : Tuple = emb_dim _UpperCAmelCase : Optional[Any] = n_layers _UpperCAmelCase : Optional[Any] = n_heads _UpperCAmelCase : Dict = dropout _UpperCAmelCase : int = attention_dropout _UpperCAmelCase : Optional[Any] = gelu_activation _UpperCAmelCase : str = sinusoidal_embeddings _UpperCAmelCase : Any = causal _UpperCAmelCase : Optional[int] = asm _UpperCAmelCase : List[str] = n_langs _UpperCAmelCase : int = use_lang_emb _UpperCAmelCase : Any = layer_norm_eps _UpperCAmelCase : Any = bos_index _UpperCAmelCase : Optional[Any] = eos_index _UpperCAmelCase : List[str] = pad_index _UpperCAmelCase : Optional[int] = unk_index _UpperCAmelCase : Dict = mask_index _UpperCAmelCase : Any = is_encoder _UpperCAmelCase : Optional[Any] = max_position_embeddings _UpperCAmelCase : List[Any] = embed_init_std _UpperCAmelCase : Union[str, Any] = init_std _UpperCAmelCase : List[str] = summary_type _UpperCAmelCase : Dict = summary_use_proj _UpperCAmelCase : str = summary_activation _UpperCAmelCase : Union[str, Any] = summary_proj_to_labels _UpperCAmelCase : Tuple = summary_first_dropout _UpperCAmelCase : List[str] = start_n_top _UpperCAmelCase : Tuple = end_n_top _UpperCAmelCase : List[str] = mask_token_id _UpperCAmelCase : Optional[int] = lang_id if "n_words" in kwargs: _UpperCAmelCase : Tuple = kwargs['''n_words'''] super().__init__(pad_token_id=A , bos_token_id=A , **A ) class _UpperCAmelCase ( a ): '''simple docstring''' @property def __lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCAmelCase : Tuple = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _UpperCAmelCase : Dict = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
68
1
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 UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> str: __UpperCamelCase =tempfile.mkdtemp() # fmt: off __UpperCamelCase =['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 __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) __UpperCamelCase ={ 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4814_5466, 0.457_8275, 0.4082_1073], 'image_std': [0.2686_2954, 0.2613_0258, 0.2757_7711], } __UpperCamelCase =os.path.join(self.tmpdirname , A_ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(A_ , A_ ) def _a ( self , **A_ ) -> List[Any]: return CLIPTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Any: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **A_ ) def _a ( self ) -> Any: shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Tuple: __UpperCamelCase =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __UpperCamelCase =[Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase =self.get_image_processor() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) processor_slow.save_pretrained(self.tmpdirname ) __UpperCamelCase =CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=A_ ) __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) processor_fast.save_pretrained(self.tmpdirname ) __UpperCamelCase =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 , A_ ) self.assertIsInstance(processor_fast.tokenizer , A_ ) 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 , A_ ) self.assertIsInstance(processor_fast.image_processor , A_ ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __UpperCamelCase =self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __UpperCamelCase =self.get_image_processor(do_normalize=A_ , padding_value=1.0 ) __UpperCamelCase =CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=A_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , A_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def _a ( self ) -> Tuple: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =image_processor(A_ , return_tensors='np' ) __UpperCamelCase =processor(images=A_ , 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 _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase ='lower newer' __UpperCamelCase =processor(text=A_ ) __UpperCamelCase =tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self ) -> List[Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase ='lower newer' __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(A_ ): processor() def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __UpperCamelCase =processor.batch_decode(A_ ) __UpperCamelCase =tokenizer.batch_decode(A_ ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase ='lower newer' __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
62
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values UpperCAmelCase : str = argparse.ArgumentParser() parser.add_argument("--user", type=str, default="ubuntu") parser.add_argument("--host", type=str, default="localhost") parser.add_argument("--key_path", type=str, default=None) parser.add_argument("--instance", type=str, default="V100:1") parser.add_argument("--provider", type=str, default="cheapest") parser.add_argument("--use_spot", type=bool, default=False) parser.add_argument("--example", type=str, default="pytorch/text-generation/run_generation.py") UpperCAmelCase, UpperCAmelCase : Optional[Any] = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("Cannot specify both BYO and on-demand cluster args") UpperCAmelCase : Dict = rh.cluster( name="rh-cluster", ips=[args.host], ssh_creds={"ssh_user": args.user, "ssh_private_key": args.key_path} ) else: UpperCAmelCase : str = rh.cluster( name="rh-cluster", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) UpperCAmelCase : str = args.example.rsplit("/", 1)[0] # Set up remote environment cluster.install_packages(["pip:./"]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
252
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch __snake_case = logging.get_logger(__name__) @dataclass class lowercase__ : def __init__( self : List[str] , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Dict=6.0 , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Union[str, Any]="fp4" , UpperCAmelCase_ : List[str]=False , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE__ = load_in_abit SCREAMING_SNAKE_CASE__ = load_in_abit SCREAMING_SNAKE_CASE__ = llm_inta_threshold SCREAMING_SNAKE_CASE__ = llm_inta_skip_modules SCREAMING_SNAKE_CASE__ = llm_inta_enable_fpaa_cpu_offload SCREAMING_SNAKE_CASE__ = llm_inta_has_fpaa_weight SCREAMING_SNAKE_CASE__ = bnb_abit_quant_type SCREAMING_SNAKE_CASE__ = bnb_abit_use_double_quant if bnb_abit_compute_dtype is None: SCREAMING_SNAKE_CASE__ = torch.floataa elif isinstance(__lowercase , __lowercase ): SCREAMING_SNAKE_CASE__ = getattr(__lowercase , __lowercase ) elif isinstance(__lowercase , torch.dtype ): SCREAMING_SNAKE_CASE__ = bnb_abit_compute_dtype else: raise ValueError('bnb_4bit_compute_dtype must be a string or a torch.dtype' ) self.post_init() def A_ ( self : str ): if not isinstance(self.llm_inta_threshold , __lowercase ): raise ValueError('llm_int8_threshold must be a float' ) if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , __lowercase ): raise ValueError('llm_int8_skip_modules must be a list of strings' ) if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , __lowercase ): raise ValueError('llm_int8_enable_fp32_cpu_offload must be a boolean' ) if not isinstance(self.llm_inta_has_fpaa_weight , __lowercase ): raise ValueError('llm_int8_has_fp16_weight must be a boolean' ) if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ): raise ValueError('bnb_4bit_compute_dtype must be torch.dtype' ) if not isinstance(self.bnb_abit_quant_type , __lowercase ): raise ValueError('bnb_4bit_quant_type must be a string' ) if not isinstance(self.bnb_abit_use_double_quant , __lowercase ): raise ValueError('bnb_4bit_use_double_quant must be a boolean' ) if self.load_in_abit and not version.parse(importlib.metadata.version('bitsandbytes' ) ) >= version.parse( '0.39.0' ): raise ValueError( '4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version' ) def A_ ( self : Optional[int] ): return self.load_in_abit or self.load_in_abit def A_ ( self : Dict ): if self.load_in_abit: return "llm_int8" elif self.load_in_abit and self.bnb_abit_quant_type == "fp4": return "fp4" elif self.load_in_abit and self.bnb_abit_quant_type == "nf4": return "nf4" else: return None @classmethod def A_ ( cls : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE__ = cls(**__lowercase ) SCREAMING_SNAKE_CASE__ = [] for key, value in kwargs.items(): if hasattr(__lowercase , __lowercase ): setattr(__lowercase , __lowercase , __lowercase ) to_remove.append(__lowercase ) for key in to_remove: kwargs.pop(__lowercase , __lowercase ) if return_unused_kwargs: return config, kwargs else: return config def A_ ( self : Union[str, Any] , UpperCAmelCase_ : Dict ): with open(__lowercase , 'w' , encoding='utf-8' ) as writer: SCREAMING_SNAKE_CASE__ = self.to_dict() SCREAMING_SNAKE_CASE__ = json.dumps(__lowercase , indent=2 , sort_keys=__lowercase ) + '''\n''' writer.write(__lowercase ) def A_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = str(output['bnb_4bit_compute_dtype'] ).split('.' )[1] return output def __repr__( self : Dict ): return F'{self.__class__.__name__} {self.to_json_string()}' def A_ ( self : str , UpperCAmelCase_ : Tuple = True ): if use_diff is True: SCREAMING_SNAKE_CASE__ = self.to_diff_dict() else: SCREAMING_SNAKE_CASE__ = self.to_dict() return json.dumps(__lowercase , indent=2 , sort_keys=__lowercase ) + "\n" def A_ ( self : Dict ): SCREAMING_SNAKE_CASE__ = self.to_dict() # get the default config dict SCREAMING_SNAKE_CASE__ = BitsAndBytesConfig().to_dict() SCREAMING_SNAKE_CASE__ = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: SCREAMING_SNAKE_CASE__ = value return serializable_config_dict
367
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowercase__ ( _UpperCAmelCase , unittest.TestCase ): A__ : Tuple =FlaxAutoencoderKL @property def A_ ( self : Any ): SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = (32, 32) SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ = jax.random.uniform(UpperCAmelCase_ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def A_ ( self : Tuple ): SCREAMING_SNAKE_CASE__ = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } SCREAMING_SNAKE_CASE__ = self.dummy_input return init_dict, inputs_dict
169
0
"""simple docstring""" def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase = False ): if not isinstance(__lowerCamelCase , __lowerCamelCase ): __lowercase : List[Any] = f"""Expected string as input, found {type(__lowerCamelCase )}""" raise ValueError(__lowerCamelCase ) if not isinstance(__lowerCamelCase , __lowerCamelCase ): __lowercase : Tuple = f"""Expected boolean as use_pascal parameter, found {type(__lowerCamelCase )}""" raise ValueError(__lowerCamelCase ) __lowercase : Optional[int] = input_str.split('''_''' ) __lowercase : Dict = 0 if use_pascal else 1 __lowercase : Tuple = words[start_index:] __lowercase : List[Any] = [word[0].upper() + word[1:] for word in words_to_capitalize] __lowercase : List[Any] = '''''' if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
249
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' _a = ['image_processor', 'tokenizer'] _a = 'BlipImageProcessor' _a = 'AutoTokenizer' def __init__( self : Tuple, lowerCamelCase : List[str], lowerCamelCase : Dict )-> str: lowerCamelCase__ : Any =False super().__init__(lowerCamelCase, lowerCamelCase ) lowerCamelCase__ : List[str] =self.image_processor def __call__( self : Union[str, Any], lowerCamelCase : ImageInput = None, lowerCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, lowerCamelCase : bool = True, lowerCamelCase : Union[bool, str, PaddingStrategy] = False, lowerCamelCase : Union[bool, str, TruncationStrategy] = None, lowerCamelCase : Optional[int] = None, lowerCamelCase : int = 0, lowerCamelCase : Optional[int] = None, lowerCamelCase : Optional[bool] = None, lowerCamelCase : bool = False, lowerCamelCase : bool = False, lowerCamelCase : bool = False, lowerCamelCase : bool = False, lowerCamelCase : bool = False, lowerCamelCase : bool = True, lowerCamelCase : Optional[Union[str, TensorType]] = None, **lowerCamelCase : List[str], )-> BatchEncoding: if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: lowerCamelCase__ : str =self.tokenizer lowerCamelCase__ : str =self.tokenizer( text=lowerCamelCase, add_special_tokens=lowerCamelCase, padding=lowerCamelCase, truncation=lowerCamelCase, max_length=lowerCamelCase, stride=lowerCamelCase, pad_to_multiple_of=lowerCamelCase, return_attention_mask=lowerCamelCase, return_overflowing_tokens=lowerCamelCase, return_special_tokens_mask=lowerCamelCase, return_offsets_mapping=lowerCamelCase, return_token_type_ids=lowerCamelCase, return_length=lowerCamelCase, verbose=lowerCamelCase, return_tensors=lowerCamelCase, **lowerCamelCase, ) return text_encoding # add pixel_values lowerCamelCase__ : Optional[int] =self.image_processor(lowerCamelCase, return_tensors=lowerCamelCase ) if text is not None: lowerCamelCase__ : Union[str, Any] =self.tokenizer( text=lowerCamelCase, add_special_tokens=lowerCamelCase, padding=lowerCamelCase, truncation=lowerCamelCase, max_length=lowerCamelCase, stride=lowerCamelCase, pad_to_multiple_of=lowerCamelCase, return_attention_mask=lowerCamelCase, return_overflowing_tokens=lowerCamelCase, return_special_tokens_mask=lowerCamelCase, return_offsets_mapping=lowerCamelCase, return_token_type_ids=lowerCamelCase, return_length=lowerCamelCase, verbose=lowerCamelCase, return_tensors=lowerCamelCase, **lowerCamelCase, ) else: lowerCamelCase__ : Optional[Any] =None if text_encoding is not None: encoding_image_processor.update(lowerCamelCase ) return encoding_image_processor def snake_case ( self : str, *lowerCamelCase : Any, **lowerCamelCase : List[str] )-> Union[str, Any]: return self.tokenizer.batch_decode(*lowerCamelCase, **lowerCamelCase ) def snake_case ( self : Dict, *lowerCamelCase : str, **lowerCamelCase : str )-> Union[str, Any]: return self.tokenizer.decode(*lowerCamelCase, **lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def snake_case ( self : List[str] )-> List[str]: lowerCamelCase__ : Union[str, Any] =self.tokenizer.model_input_names lowerCamelCase__ : List[str] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
238
0
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig lowerCamelCase_ = logging.get_logger(__name__) # General docstring lowerCamelCase_ = '''PoolFormerConfig''' # Base docstring lowerCamelCase_ = '''sail/poolformer_s12''' lowerCamelCase_ = [1, 512, 7, 7] # Image classification docstring lowerCamelCase_ = '''sail/poolformer_s12''' lowerCamelCase_ = '''tabby, tabby cat''' lowerCamelCase_ = [ '''sail/poolformer_s12''', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def UpperCamelCase( lowercase_ , lowercase_ = 0.0 , lowercase_ = False ) -> List[str]: '''simple docstring''' if drop_prob == 0.0 or not training: return input snake_case_ = 1 - drop_prob snake_case_ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets snake_case_ = keep_prob + torch.rand(lowercase_ , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize snake_case_ = input.div(lowercase_ ) * random_tensor return output class __lowerCamelCase ( nn.Module ): def __init__( self , lowerCamelCase = None ) -> None: super().__init__() snake_case_ = drop_prob def lowerCAmelCase_ ( self , lowerCamelCase ) -> torch.Tensor: return drop_path(lowerCamelCase , self.drop_prob , self.training ) def lowerCAmelCase_ ( self ) -> str: return "p={}".format(self.drop_prob ) class __lowerCamelCase ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None ) -> Union[str, Any]: super().__init__() snake_case_ = patch_size if isinstance(lowerCamelCase , collections.abc.Iterable ) else (patch_size, patch_size) snake_case_ = stride if isinstance(lowerCamelCase , collections.abc.Iterable ) else (stride, stride) snake_case_ = padding if isinstance(lowerCamelCase , collections.abc.Iterable ) else (padding, padding) snake_case_ = nn.Convad(lowerCamelCase , lowerCamelCase , kernel_size=lowerCamelCase , stride=lowerCamelCase , padding=lowerCamelCase ) snake_case_ = norm_layer(lowerCamelCase ) if norm_layer else nn.Identity() def lowerCAmelCase_ ( self , lowerCamelCase ) -> Any: snake_case_ = self.projection(lowerCamelCase ) snake_case_ = self.norm(lowerCamelCase ) return embeddings class __lowerCamelCase ( nn.GroupNorm ): def __init__( self , lowerCamelCase , **lowerCamelCase ) -> Optional[Any]: super().__init__(1 , lowerCamelCase , **lowerCamelCase ) class __lowerCamelCase ( nn.Module ): def __init__( self , lowerCamelCase ) -> Any: super().__init__() snake_case_ = nn.AvgPoolad(lowerCamelCase , stride=1 , padding=pool_size // 2 , count_include_pad=lowerCamelCase ) def lowerCAmelCase_ ( self , lowerCamelCase ) -> int: return self.pool(lowerCamelCase ) - hidden_states class __lowerCamelCase ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> Union[str, Any]: super().__init__() snake_case_ = nn.Convad(lowerCamelCase , lowerCamelCase , 1 ) snake_case_ = nn.Convad(lowerCamelCase , lowerCamelCase , 1 ) snake_case_ = PoolFormerDropPath(lowerCamelCase ) if isinstance(config.hidden_act , lowerCamelCase ): snake_case_ = ACTaFN[config.hidden_act] else: snake_case_ = config.hidden_act def lowerCAmelCase_ ( self , lowerCamelCase ) -> List[str]: snake_case_ = self.conva(lowerCamelCase ) snake_case_ = self.act_fn(lowerCamelCase ) snake_case_ = self.drop(lowerCamelCase ) snake_case_ = self.conva(lowerCamelCase ) snake_case_ = self.drop(lowerCamelCase ) return hidden_states class __lowerCamelCase ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> Union[str, Any]: super().__init__() snake_case_ = PoolFormerPooling(lowerCamelCase ) snake_case_ = PoolFormerOutput(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) snake_case_ = PoolFormerGroupNorm(lowerCamelCase ) snake_case_ = PoolFormerGroupNorm(lowerCamelCase ) # Useful for training neural nets snake_case_ = PoolFormerDropPath(lowerCamelCase ) if drop_path > 0.0 else nn.Identity() snake_case_ = config.use_layer_scale if config.use_layer_scale: snake_case_ = nn.Parameter( config.layer_scale_init_value * torch.ones((lowerCamelCase) ) , requires_grad=lowerCamelCase ) snake_case_ = nn.Parameter( config.layer_scale_init_value * torch.ones((lowerCamelCase) ) , requires_grad=lowerCamelCase ) def lowerCAmelCase_ ( self , lowerCamelCase ) -> Optional[int]: if self.use_layer_scale: snake_case_ = self.pooling(self.before_norm(lowerCamelCase ) ) snake_case_ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection snake_case_ = hidden_states + self.drop_path(lowerCamelCase ) snake_case_ = () snake_case_ = self.output(self.after_norm(lowerCamelCase ) ) snake_case_ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection snake_case_ = hidden_states + self.drop_path(lowerCamelCase ) snake_case_ = (output,) + outputs return outputs else: snake_case_ = self.drop_path(self.pooling(self.before_norm(lowerCamelCase ) ) ) # First residual connection snake_case_ = pooling_output + hidden_states snake_case_ = () # Second residual connection inside the PoolFormerOutput block snake_case_ = self.drop_path(self.output(self.after_norm(lowerCamelCase ) ) ) snake_case_ = hidden_states + layer_output snake_case_ = (output,) + outputs return outputs class __lowerCamelCase ( nn.Module ): def __init__( self , lowerCamelCase ) -> Optional[Any]: super().__init__() snake_case_ = config # stochastic depth decay rule snake_case_ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings snake_case_ = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) snake_case_ = nn.ModuleList(lowerCamelCase ) # Transformer blocks snake_case_ = [] snake_case_ = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers snake_case_ = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( lowerCamelCase , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(lowerCamelCase ) ) snake_case_ = nn.ModuleList(lowerCamelCase ) def lowerCAmelCase_ ( self , lowerCamelCase , lowerCamelCase=False , lowerCamelCase=True ) -> Union[str, Any]: snake_case_ = () if output_hidden_states else None snake_case_ = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): snake_case_ , snake_case_ = layers # Get patch embeddings from hidden_states snake_case_ = embedding_layer(lowerCamelCase ) # Send the embeddings through the blocks for _, blk in enumerate(lowerCamelCase ): snake_case_ = blk(lowerCamelCase ) snake_case_ = layer_outputs[0] if output_hidden_states: snake_case_ = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=lowerCamelCase , hidden_states=lowerCamelCase ) class __lowerCamelCase ( __snake_case ): lowerCamelCase_ : Optional[Any] = PoolFormerConfig lowerCamelCase_ : Any = 'poolformer' lowerCamelCase_ : Tuple = 'pixel_values' lowerCamelCase_ : str = True def lowerCAmelCase_ ( self , lowerCamelCase ) -> List[str]: if isinstance(lowerCamelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(lowerCamelCase , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def lowerCAmelCase_ ( self , lowerCamelCase , lowerCamelCase=False ) -> Any: if isinstance(lowerCamelCase , lowerCamelCase ): snake_case_ = value lowerCamelCase_ = R''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' lowerCamelCase_ = R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. ''' @add_start_docstrings( 'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.' , __snake_case , ) class __lowerCamelCase ( __snake_case ): def __init__( self , lowerCamelCase ) -> int: super().__init__(lowerCamelCase ) snake_case_ = config snake_case_ = PoolFormerEncoder(lowerCamelCase ) # Initialize weights and apply final processing self.post_init() def lowerCAmelCase_ ( self ) -> List[str]: return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowerCAmelCase_ ( self , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: snake_case_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) snake_case_ = self.encoder( lowerCamelCase , output_hidden_states=lowerCamelCase , return_dict=lowerCamelCase , ) snake_case_ = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=lowerCamelCase , hidden_states=encoder_outputs.hidden_states , ) class __lowerCamelCase ( nn.Module ): def __init__( self , lowerCamelCase ) -> Optional[int]: super().__init__() snake_case_ = nn.Linear(config.hidden_size , config.hidden_size ) def lowerCAmelCase_ ( self , lowerCamelCase ) -> Tuple: snake_case_ = self.dense(lowerCamelCase ) return output @add_start_docstrings( '\n PoolFormer Model transformer with an image classification head on top\n ' , __snake_case , ) class __lowerCamelCase ( __snake_case ): def __init__( self , lowerCamelCase ) -> Optional[Any]: super().__init__(lowerCamelCase ) snake_case_ = config.num_labels snake_case_ = PoolFormerModel(lowerCamelCase ) # Final norm snake_case_ = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head snake_case_ = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowerCAmelCase_ ( self , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ = self.poolformer( lowerCamelCase , output_hidden_states=lowerCamelCase , return_dict=lowerCamelCase , ) snake_case_ = outputs[0] snake_case_ = self.classifier(self.norm(lowerCamelCase ).mean([-2, -1] ) ) snake_case_ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case_ = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case_ = """single_label_classification""" else: snake_case_ = """multi_label_classification""" if self.config.problem_type == "regression": snake_case_ = MSELoss() if self.num_labels == 1: snake_case_ = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case_ = loss_fct(lowerCamelCase , lowerCamelCase ) elif self.config.problem_type == "single_label_classification": snake_case_ = CrossEntropyLoss() snake_case_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case_ = BCEWithLogitsLoss() snake_case_ = loss_fct(lowerCamelCase , lowerCamelCase ) if not return_dict: snake_case_ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowerCamelCase , logits=lowerCamelCase , hidden_states=outputs.hidden_states )
34
from __future__ import annotations def UpperCamelCase( lowercase_ , lowercase_ , lowercase_ ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
34
1
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable __A : Tuple = {'''configuration_dpt''': ['''DPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DPTConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['''DPTFeatureExtractor'''] __A : Any = ['''DPTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ '''DPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DPTForDepthEstimation''', '''DPTForSemanticSegmentation''', '''DPTModel''', '''DPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys __A : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
33
"""simple docstring""" import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask __snake_case = logging.getLogger(__name__) class _lowerCAmelCase ( snake_case_ ): __UpperCAmelCase : Optional[int] = '''token-classification''' def __init__( self , UpperCamelCase__ ) -> List[Any]: '''simple docstring''' if type(UpperCamelCase__ ) == dict: snake_case : Optional[int] = Namespace(**UpperCamelCase__ ) snake_case : Optional[int] = import_module("tasks" ) try: snake_case : Optional[int] = getattr(UpperCamelCase__ , hparams.task_type ) snake_case : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) snake_case : str = self.token_classification_task.get_labels(hparams.labels ) snake_case : Union[str, Any] = CrossEntropyLoss().ignore_index super().__init__(UpperCamelCase__ , len(self.labels ) , self.mode ) def lowerCamelCase ( self , **UpperCamelCase__ ) -> Any: '''simple docstring''' return self.model(**UpperCamelCase__ ) def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: '''simple docstring''' snake_case : Optional[Any] = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": snake_case : Optional[int] = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids snake_case : List[Any] = self(**UpperCamelCase__ ) snake_case : Union[str, Any] = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def lowerCamelCase ( self ) -> Optional[int]: '''simple docstring''' snake_case : Optional[Any] = self.hparams for mode in ["train", "dev", "test"]: snake_case : Optional[Any] = self._feature_file(UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , UpperCamelCase__ ) snake_case : List[str] = torch.load(UpperCamelCase__ ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) snake_case : Optional[Any] = self.token_classification_task.read_examples_from_file(args.data_dir , UpperCamelCase__ ) snake_case : Dict = self.token_classification_task.convert_examples_to_features( UpperCamelCase__ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["xlnet"] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["xlnet"] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=UpperCamelCase__ , pad_on_left=bool(self.config.model_type in ["xlnet"] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("Saving features into cached file %s" , UpperCamelCase__ ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False ) -> DataLoader: '''simple docstring''' snake_case : Optional[Any] = self._feature_file(UpperCamelCase__ ) logger.info("Loading features from cached file %s" , UpperCamelCase__ ) snake_case : Any = torch.load(UpperCamelCase__ ) snake_case : Tuple = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) snake_case : List[str] = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: snake_case : Tuple = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: snake_case : Union[str, Any] = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) snake_case : Optional[int] = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , batch_size=UpperCamelCase__ ) def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: '''simple docstring''' """Compute validation""" "" snake_case : Any = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": snake_case : Optional[int] = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids snake_case : Optional[int] = self(**UpperCamelCase__ ) snake_case ,snake_case : str = outputs[:2] snake_case : Optional[int] = logits.detach().cpu().numpy() snake_case : str = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def lowerCamelCase ( self , UpperCamelCase__ ) -> Any: '''simple docstring''' snake_case : Dict = torch.stack([x["val_loss"] for x in outputs] ).mean() snake_case : List[str] = np.concatenate([x["pred"] for x in outputs] , axis=0 ) snake_case : Any = np.argmax(UpperCamelCase__ , axis=2 ) snake_case : Dict = np.concatenate([x["target"] for x in outputs] , axis=0 ) snake_case : Tuple = dict(enumerate(self.labels ) ) snake_case : str = [[] for _ in range(out_label_ids.shape[0] )] snake_case : List[Any] = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) snake_case : Union[str, Any] = { "val_loss": val_loss_mean, "accuracy_score": accuracy_score(UpperCamelCase__ , UpperCamelCase__ ), "precision": precision_score(UpperCamelCase__ , UpperCamelCase__ ), "recall": recall_score(UpperCamelCase__ , UpperCamelCase__ ), "f1": fa_score(UpperCamelCase__ , UpperCamelCase__ ), } snake_case : int = dict(results.items() ) snake_case : Union[str, Any] = results return ret, preds_list, out_label_list def lowerCamelCase ( self , UpperCamelCase__ ) -> List[str]: '''simple docstring''' snake_case ,snake_case ,snake_case : Optional[Any] = self._eval_end(UpperCamelCase__ ) snake_case : Tuple = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def lowerCamelCase ( self , UpperCamelCase__ ) -> Any: '''simple docstring''' snake_case ,snake_case ,snake_case : List[Any] = self._eval_end(UpperCamelCase__ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 snake_case : Optional[Any] = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> str: '''simple docstring''' BaseTransformer.add_model_specific_args(UpperCamelCase__ , UpperCamelCase__ ) parser.add_argument( "--task_type" , default="NER" , type=UpperCamelCase__ , help="Task type to fine tune in training (e.g. NER, POS, etc)" ) parser.add_argument( "--max_seq_length" , default=128 , type=UpperCamelCase__ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--labels" , default="" , type=UpperCamelCase__ , help="Path to a file containing all labels. If not specified, CoNLL-2003 labels are used." , ) parser.add_argument( "--gpus" , default=0 , type=UpperCamelCase__ , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser if __name__ == "__main__": __snake_case = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) __snake_case = NERTransformer.add_model_specific_args(parser, os.getcwd()) __snake_case = parser.parse_args() __snake_case = NERTransformer(args) __snake_case = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 __snake_case = sorted(glob.glob(os.path.join(args.output_dir, """checkpoint-epoch=*.ckpt"""), recursive=True)) __snake_case = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
203
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __UpperCamelCase : Optional[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class __magic_name__ ( __lowerCAmelCase , unittest.TestCase): A: Tuple = XLMRobertaTokenizer A: Union[str, Any] = XLMRobertaTokenizerFast A: List[Any] = True A: Optional[int] = True def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase__ : List[Any] = XLMRobertaTokenizer(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : int ) -> int: '''simple docstring''' UpperCamelCase__ : Optional[int] = '''<pad>''' UpperCamelCase__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase__ ) , lowerCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase__ ) , lowerCamelCase__ ) def UpperCAmelCase__ ( self : int ) -> List[Any]: '''simple docstring''' UpperCamelCase__ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(lowerCamelCase__ ) , 1002 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1002 ) def UpperCAmelCase__ ( self : Any ) -> Dict: '''simple docstring''' UpperCamelCase__ : List[str] = XLMRobertaTokenizer(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) UpperCamelCase__ : List[Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCamelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCamelCase__ : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCamelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) UpperCamelCase__ : Dict = tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) self.assertListEqual( lowerCamelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) UpperCamelCase__ : Tuple = tokenizer.convert_ids_to_tokens(lowerCamelCase__ ) self.assertListEqual( lowerCamelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return UpperCamelCase__ : Optional[Any] = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-xlm-roberta''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ : List[str] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ ) UpperCamelCase__ : Union[str, Any] = self.tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = tempfile.mkdtemp() UpperCamelCase__ : Optional[Any] = tokenizer_r.save_pretrained(lowerCamelCase__ ) UpperCamelCase__ : Union[str, Any] = tokenizer_p.save_pretrained(lowerCamelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) UpperCamelCase__ : Optional[Any] = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(lowerCamelCase__ , lowerCamelCase__ ) # Checks everything loads correctly in the same way UpperCamelCase__ : Any = tokenizer_r.from_pretrained(lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = tokenizer_p.from_pretrained(lowerCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCamelCase__ , lowerCamelCase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowerCamelCase__ ) # Save tokenizer rust, legacy_format=True UpperCamelCase__ : List[str] = tempfile.mkdtemp() UpperCamelCase__ : Optional[Any] = tokenizer_r.save_pretrained(lowerCamelCase__ , legacy_format=lowerCamelCase__ ) UpperCamelCase__ : Dict = tokenizer_p.save_pretrained(lowerCamelCase__ ) # Checks it save with the same files self.assertSequenceEqual(lowerCamelCase__ , lowerCamelCase__ ) # Checks everything loads correctly in the same way UpperCamelCase__ : List[str] = tokenizer_r.from_pretrained(lowerCamelCase__ ) UpperCamelCase__ : int = tokenizer_p.from_pretrained(lowerCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCamelCase__ , lowerCamelCase__ ) ) shutil.rmtree(lowerCamelCase__ ) # Save tokenizer rust, legacy_format=False UpperCamelCase__ : Union[str, Any] = tempfile.mkdtemp() UpperCamelCase__ : int = tokenizer_r.save_pretrained(lowerCamelCase__ , legacy_format=lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = tokenizer_p.save_pretrained(lowerCamelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCamelCase__ : List[Any] = tokenizer_r.from_pretrained(lowerCamelCase__ ) UpperCamelCase__ : Tuple = tokenizer_p.from_pretrained(lowerCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCamelCase__ , lowerCamelCase__ ) ) shutil.rmtree(lowerCamelCase__ ) @cached_property def UpperCAmelCase__ ( self : List[str] ) -> str: '''simple docstring''' return XLMRobertaTokenizer.from_pretrained('''xlm-roberta-base''' ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCamelCase__ , f.name ) UpperCamelCase__ : Any = XLMRobertaTokenizer(f.name , keep_accents=lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = pickle.dumps(lowerCamelCase__ ) pickle.loads(lowerCamelCase__ ) def UpperCAmelCase__ ( self : int ) -> Tuple: '''simple docstring''' if not self.test_rust_tokenizer: return UpperCamelCase__ : Tuple = self.get_tokenizer() UpperCamelCase__ : List[str] = self.get_rust_tokenizer() UpperCamelCase__ : Optional[int] = '''I was born in 92000, and this is falsé.''' UpperCamelCase__ : Optional[int] = tokenizer.tokenize(lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : str = tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : str = self.get_rust_tokenizer() UpperCamelCase__ : List[Any] = tokenizer.encode(lowerCamelCase__ ) UpperCamelCase__ : List[Any] = rust_tokenizer.encode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' UpperCamelCase__ : Dict = '''Hello World!''' UpperCamelCase__ : int = [0, 35378, 6661, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(lowerCamelCase__ , self.big_tokenizer.encode(lowerCamelCase__ ) ) @slow def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ : Optional[int] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) UpperCamelCase__ : str = [ 0, 3293, 83, 10, 4552, 4989, 7986, 678, 10, 5915, 111, 179459, 124850, 4, 6044, 237, 12, 6, 5, 6, 4, 6780, 705, 15, 1388, 44, 378, 10114, 711, 152, 20, 6, 5, 22376, 642, 1221, 15190, 34153, 450, 5608, 959, 1119, 57702, 136, 186, 47, 1098, 29367, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 6044, 237, 6284, 50901, 528, 31, 90, 34, 927, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(lowerCamelCase__ , self.big_tokenizer.encode(lowerCamelCase__ ) ) @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: '''simple docstring''' UpperCamelCase__ : int = {'''input_ids''': [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 5428, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 12399, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 122009, 115774, 23, 805, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase__ , model_name='''xlm-roberta-base''' , revision='''d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3''' , )
351
import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __magic_name__ ( __lowerCAmelCase): A: Optional[int] = ["image_processor", "tokenizer"] A: int = "FlavaImageProcessor" A: List[str] = ("BertTokenizer", "BertTokenizerFast") def __init__( self : int , lowerCamelCase__ : Dict=None , lowerCamelCase__ : Union[str, Any]=None , **lowerCamelCase__ : int ) -> int: '''simple docstring''' UpperCamelCase__ : Optional[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.''' , lowerCamelCase__ , ) UpperCamelCase__ : Union[str, Any] = kwargs.pop('''feature_extractor''' ) UpperCamelCase__ : str = 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__(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : List[str] = self.image_processor def __call__( self : int , lowerCamelCase__ : Optional[ImageInput] = None , lowerCamelCase__ : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , lowerCamelCase__ : bool = True , lowerCamelCase__ : Union[bool, str, PaddingStrategy] = False , lowerCamelCase__ : Union[bool, str, TruncationStrategy] = False , lowerCamelCase__ : Optional[int] = None , lowerCamelCase__ : int = 0 , lowerCamelCase__ : Optional[int] = None , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : bool = False , lowerCamelCase__ : bool = False , lowerCamelCase__ : bool = False , lowerCamelCase__ : bool = False , lowerCamelCase__ : bool = True , lowerCamelCase__ : Optional[Union[str, TensorType]] = None , **lowerCamelCase__ : List[str] , ) -> Any: '''simple docstring''' if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: UpperCamelCase__ : Dict = self.tokenizer( text=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , padding=lowerCamelCase__ , truncation=lowerCamelCase__ , max_length=lowerCamelCase__ , stride=lowerCamelCase__ , pad_to_multiple_of=lowerCamelCase__ , return_token_type_ids=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , return_overflowing_tokens=lowerCamelCase__ , return_special_tokens_mask=lowerCamelCase__ , return_offsets_mapping=lowerCamelCase__ , return_length=lowerCamelCase__ , verbose=lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ , ) if images is not None: UpperCamelCase__ : Optional[int] = self.image_processor( lowerCamelCase__ , return_image_mask=lowerCamelCase__ , return_codebook_pixels=lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ , ) if text is not None and images is not None: encoding.update(lowerCamelCase__ ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowerCamelCase__ ) , tensor_type=lowerCamelCase__ ) def UpperCAmelCase__ ( self : Optional[Any] , *lowerCamelCase__ : str , **lowerCamelCase__ : int ) -> Optional[Any]: '''simple docstring''' return self.tokenizer.batch_decode(*lowerCamelCase__ , **lowerCamelCase__ ) def UpperCAmelCase__ ( self : Dict , *lowerCamelCase__ : Dict , **lowerCamelCase__ : int ) -> List[str]: '''simple docstring''' return self.tokenizer.decode(*lowerCamelCase__ , **lowerCamelCase__ ) @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ : Optional[Any] = self.tokenizer.model_input_names UpperCamelCase__ : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def UpperCAmelCase__ ( self : Tuple ) -> Dict: '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowerCamelCase__ , ) return self.image_processor_class @property def UpperCAmelCase__ ( self : List[Any] ) -> Any: '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowerCamelCase__ , ) return self.image_processor
51
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a_ = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys a_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
340
from __future__ import annotations import os from collections.abc import Mapping a_ = tuple[int, int] class lowercase__ : def __init__( self , __UpperCAmelCase , __UpperCAmelCase )-> None: '''simple docstring''' lowerCAmelCase__ = vertices lowerCAmelCase__ = { (min(__UpperCAmelCase ), max(__UpperCAmelCase )): weight for edge, weight in edges.items() } def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase )-> None: '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) lowerCAmelCase__ = weight def UpperCAmelCase ( self )-> Graph: '''simple docstring''' lowerCAmelCase__ = Graph({min(self.vertices )} , {} ) lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 while len(subgraph.vertices ) < len(self.vertices ): lowerCAmelCase__ = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: lowerCAmelCase__ = edge lowerCAmelCase__ = weight subgraph.add_edge(__UpperCAmelCase , __UpperCAmelCase ) return subgraph def _a ( UpperCamelCase_ : str = "p107_network.txt" ) -> int: """simple docstring""" lowerCAmelCase__ = os.path.abspath(os.path.dirname(UpperCamelCase_ ) ) lowerCAmelCase__ = os.path.join(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = {} lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 with open(UpperCamelCase_ ) as f: lowerCAmelCase__ = f.read().strip().split("\n" ) lowerCAmelCase__ = [line.split("," ) for line in data] for edgea in range(1 , len(UpperCamelCase_ ) ): for edgea in range(UpperCamelCase_ ): if adjaceny_matrix[edgea][edgea] != "-": lowerCAmelCase__ = int(adjaceny_matrix[edgea][edgea] ) lowerCAmelCase__ = Graph(set(range(len(UpperCamelCase_ ) ) ) , UpperCamelCase_ ) lowerCAmelCase__ = graph.prims_algorithm() lowerCAmelCase__ = sum(graph.edges.values() ) lowerCAmelCase__ = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
340
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Any = "▁" _lowerCamelCase : Any = {"vocab_file": "sentencepiece.bpe.model"} _lowerCamelCase : Union[str, Any] = { "vocab_file": { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model", } } _lowerCamelCase : List[Any] = { "facebook/xglm-564M": 2048, } class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""] def __init__( self : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict="<s>" , UpperCamelCase__ : Tuple="</s>" , UpperCamelCase__ : Optional[Any]="</s>" , UpperCamelCase__ : Dict="<s>" , UpperCamelCase__ : Dict="<unk>" , UpperCamelCase__ : Union[str, Any]="<pad>" , UpperCamelCase__ : Optional[Dict[str, Any]] = None , **UpperCamelCase__ : Dict , ): """simple docstring""" UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer UpperCamelCase = 7 UpperCamelCase = [f"""<madeupword{i}>""" for i in range(self.num_madeup_words )] UpperCamelCase = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , ) UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCamelCase__ ) ) UpperCamelCase = 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' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab UpperCamelCase = 1 # Mimic fairseq token-to-id alignment for the first 4 token UpperCamelCase = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} UpperCamelCase = len(self.sp_model ) UpperCamelCase = {f"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(UpperCamelCase__ ) UpperCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : str ): """simple docstring""" UpperCamelCase = self.__dict__.copy() UpperCamelCase = None UpperCamelCase = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[Any] , UpperCamelCase__ : Union[str, Any] ): """simple docstring""" UpperCamelCase = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase = {} UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def A ( self : Optional[int] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.sep_token_id] + token_ids_a UpperCamelCase = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def A ( self : Optional[int] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase__ )) return [1] + ([0] * len(UpperCamelCase__ )) + [1, 1] + ([0] * len(UpperCamelCase__ )) def A ( self : Optional[int] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): """simple docstring""" UpperCamelCase = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def A ( self : int ): """simple docstring""" return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def A ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A ( self : Optional[int] , UpperCamelCase__ : str ): """simple docstring""" return self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) def A ( self : Optional[int] , UpperCamelCase__ : Union[str, Any] ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCamelCase = self.sp_model.PieceToId(UpperCamelCase__ ) # 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 A ( self : str , UpperCamelCase__ : List[Any] ): """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 A ( self : Any , UpperCamelCase__ : Dict ): """simple docstring""" UpperCamelCase = ''.join(UpperCamelCase__ ).replace(UpperCamelCase__ , ' ' ).strip() return out_string def A ( self : Any , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCamelCase = os.path.join( UpperCamelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase__ , 'wb' ) as fi: UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,)
249
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __lowerCamelCase ( A__ ) -> Any: """simple docstring""" UpperCamelCase , UpperCamelCase = image.size UpperCamelCase , UpperCamelCase = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase = image.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) UpperCamelCase = np.array(A__ ).astype(np.floataa ) / 255.0 UpperCamelCase = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase = torch.from_numpy(A__ ) return 2.0 * image - 1.0 class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : str , UpperCamelCase__ : VQModel , UpperCamelCase__ : UNetaDModel , UpperCamelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCamelCase__ , unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) @torch.no_grad() def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , UpperCamelCase__ : Optional[int] = 1 , UpperCamelCase__ : Optional[int] = 1_0_0 , UpperCamelCase__ : Optional[float] = 0.0 , UpperCamelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase__ : Optional[str] = "pil" , UpperCamelCase__ : bool = True , ): """simple docstring""" if isinstance(UpperCamelCase__ , PIL.Image.Image ): UpperCamelCase = 1 elif isinstance(UpperCamelCase__ , torch.Tensor ): UpperCamelCase = image.shape[0] else: raise ValueError(f"""`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(UpperCamelCase__ )}""" ) if isinstance(UpperCamelCase__ , PIL.Image.Image ): UpperCamelCase = preprocess(UpperCamelCase__ ) UpperCamelCase , UpperCamelCase = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase = next(self.unet.parameters() ).dtype UpperCamelCase = randn_tensor(UpperCamelCase__ , generator=UpperCamelCase__ , device=self.device , dtype=UpperCamelCase__ ) UpperCamelCase = image.to(device=self.device , dtype=UpperCamelCase__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(UpperCamelCase__ , device=self.device ) UpperCamelCase = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase = {} if accepts_eta: UpperCamelCase = eta for t in self.progress_bar(UpperCamelCase__ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase = torch.cat([latents, image] , dim=1 ) UpperCamelCase = self.scheduler.scale_model_input(UpperCamelCase__ , UpperCamelCase__ ) # predict the noise residual UpperCamelCase = self.unet(UpperCamelCase__ , UpperCamelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase = self.scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase = self.vqvae.decode(UpperCamelCase__ ).sample UpperCamelCase = torch.clamp(UpperCamelCase__ , -1.0 , 1.0 ) UpperCamelCase = image / 2 + 0.5 UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase = self.numpy_to_pil(UpperCamelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCamelCase__ )
249
1
'''simple docstring''' from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class lowercase ( A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = None , UpperCamelCase_ = None , **UpperCamelCase_ , ): '''simple docstring''' super().__init__( features=UpperCamelCase_ , cache_dir=UpperCamelCase_ , keep_in_memory=UpperCamelCase_ , streaming=UpperCamelCase_ , num_proc=UpperCamelCase_ , **UpperCamelCase_ , ) UpperCamelCase__ :Any = Generator( cache_dir=UpperCamelCase_ , features=UpperCamelCase_ , generator=UpperCamelCase_ , gen_kwargs=UpperCamelCase_ , **UpperCamelCase_ , ) def lowerCAmelCase__ ( self ): '''simple docstring''' if self.streaming: UpperCamelCase__ :Optional[Any] = self.builder.as_streaming_dataset(split='''train''' ) # Build regular (map-style) dataset else: UpperCamelCase__ :Optional[int] = None UpperCamelCase__ :int = None UpperCamelCase__ :Any = None UpperCamelCase__ :Any = None self.builder.download_and_prepare( download_config=UpperCamelCase_ , download_mode=UpperCamelCase_ , verification_mode=UpperCamelCase_ , base_path=UpperCamelCase_ , num_proc=self.num_proc , ) UpperCamelCase__ :List[Any] = self.builder.as_dataset( split='''train''' , verification_mode=UpperCamelCase_ , in_memory=self.keep_in_memory ) return dataset
97
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) a : Union[str, Any] = logging.getLogger(__name__) def _SCREAMING_SNAKE_CASE ( ) ->Tuple: '''simple docstring''' a : Dict = argparse.ArgumentParser( description="Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids)." ) parser.add_argument("--file_path" , type=_lowercase , default="data/dump.txt" , help="The path to the data." ) parser.add_argument("--tokenizer_type" , type=_lowercase , default="bert" , choices=["bert", "roberta", "gpt2"] ) parser.add_argument("--tokenizer_name" , type=_lowercase , default="bert-base-uncased" , help="The tokenizer to use." ) parser.add_argument("--dump_file" , type=_lowercase , default="data/dump" , help="The dump file prefix." ) a : Dict = parser.parse_args() logger.info(F"""Loading Tokenizer ({args.tokenizer_name})""" ) if args.tokenizer_type == "bert": a : Optional[Any] = BertTokenizer.from_pretrained(args.tokenizer_name ) a : str = tokenizer.special_tokens_map["cls_token"] # `[CLS]` a : List[str] = tokenizer.special_tokens_map["sep_token"] # `[SEP]` elif args.tokenizer_type == "roberta": a : Tuple = RobertaTokenizer.from_pretrained(args.tokenizer_name ) a : Union[str, Any] = tokenizer.special_tokens_map["cls_token"] # `<s>` a : str = tokenizer.special_tokens_map["sep_token"] # `</s>` elif args.tokenizer_type == "gpt2": a : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) a : Optional[int] = tokenizer.special_tokens_map["bos_token"] # `<|endoftext|>` a : List[Any] = tokenizer.special_tokens_map["eos_token"] # `<|endoftext|>` logger.info(F"""Loading text from {args.file_path}""" ) with open(args.file_path , "r" , encoding="utf8" ) as fp: a : List[Any] = fp.readlines() logger.info("Start encoding" ) logger.info(F"""{len(_lowercase )} examples to process.""" ) a : Optional[Any] = [] a : Optional[Any] = 0 a : int = 1_0000 a : Dict = time.time() for text in data: a : List[Any] = F"""{bos} {text.strip()} {sep}""" a : Optional[int] = tokenizer.encode(_lowercase , add_special_tokens=_lowercase ) rslt.append(_lowercase ) iter += 1 if iter % interval == 0: a : Optional[Any] = time.time() logger.info(F"""{iter} examples processed. - {(end-start):.2f}s/{interval}expl""" ) a : Optional[Any] = time.time() logger.info("Finished binarization" ) logger.info(F"""{len(_lowercase )} examples processed.""" ) a : Optional[int] = F"""{args.dump_file}.{args.tokenizer_name}.pickle""" a : Tuple = tokenizer.vocab_size if vocab_size < (1 << 16): a : Optional[int] = [np.uintaa(_lowercase ) for d in rslt] else: a : Optional[Any] = [np.intaa(_lowercase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F"""Dump to {dp_file}""" ) with open(_lowercase , "wb" ) as handle: pickle.dump(rslt_ , _lowercase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
105
0
"""simple docstring""" import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class lowerCAmelCase__ ( lowercase, unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = RoFormerTokenizer lowerCamelCase__ = RoFormerTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def A_ ( self ): super().setUp() def A_ ( self , **lowercase ): return self.tokenizer_class.from_pretrained('junnyu/roformer_chinese_base' , **lowercase ) def A_ ( self , **lowercase ): return self.rust_tokenizer_class.from_pretrained('junnyu/roformer_chinese_base' , **lowercase ) def A_ ( self ): _lowerCamelCase : str = '永和服装饰品有限公司,今天天气非常好' _lowerCamelCase : Optional[int] = '永和 服装 饰品 有限公司 , 今 天 天 气 非常 好' return input_text, output_text def A_ ( self ): _lowerCamelCase : Optional[int] = self.get_tokenizer() _lowerCamelCase, _lowerCamelCase : List[str] = self.get_chinese_input_output_texts() _lowerCamelCase : List[Any] = tokenizer.tokenize(lowercase ) self.assertListEqual(lowercase , output_text.split() ) _lowerCamelCase : Union[str, Any] = tokens + [tokenizer.unk_token] _lowerCamelCase : Optional[Any] = [22943, 21332, 34431, 45904, 117, 306, 1231, 1231, 2653, 33994, 1266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase ) , lowercase ) def A_ ( self ): _lowerCamelCase : int = self.get_rust_tokenizer() _lowerCamelCase, _lowerCamelCase : int = self.get_chinese_input_output_texts() _lowerCamelCase : int = tokenizer.tokenize(lowercase ) self.assertListEqual(lowercase , output_text.split() ) _lowerCamelCase : List[Any] = tokens + [tokenizer.unk_token] _lowerCamelCase : Tuple = [22943, 21332, 34431, 45904, 117, 306, 1231, 1231, 2653, 33994, 1266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase ) , lowercase ) def A_ ( self ): pass def A_ ( self ): pass def A_ ( self ): pass
12
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def A_ ( self , lowercase , lowercase , lowercase ): _lowerCamelCase : Optional[int] = hf_hub_download( repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) _lowerCamelCase : Tuple = VideoClassificationPipeline(model=lowercase , image_processor=lowercase , top_k=2 ) _lowerCamelCase : List[str] = [ example_video_filepath, 'https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4', ] return video_classifier, examples def A_ ( self , lowercase , lowercase ): for example in examples: _lowerCamelCase : Tuple = video_classifier(lowercase ) self.assertEqual( lowercase , [ {'score': ANY(lowercase ), 'label': ANY(lowercase )}, {'score': ANY(lowercase ), 'label': ANY(lowercase )}, ] , ) @require_torch def A_ ( self ): _lowerCamelCase : Optional[Any] = 'hf-internal-testing/tiny-random-VideoMAEForVideoClassification' _lowerCamelCase : Tuple = VideoMAEFeatureExtractor( size={'shortest_edge': 10} , crop_size={'height': 10, 'width': 10} ) _lowerCamelCase : Dict = pipeline( 'video-classification' , model=lowercase , feature_extractor=lowercase , frame_sampling_rate=4 ) _lowerCamelCase : Any = hf_hub_download(repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) _lowerCamelCase : Dict = video_classifier(lowercase , top_k=2 ) self.assertEqual( nested_simplify(lowercase , decimals=4 ) , [{'score': 0.51_99, 'label': 'LABEL_0'}, {'score': 0.48_01, 'label': 'LABEL_1'}] , ) _lowerCamelCase : str = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(lowercase , decimals=4 ) , [ [{'score': 0.51_99, 'label': 'LABEL_0'}, {'score': 0.48_01, 'label': 'LABEL_1'}], [{'score': 0.51_99, 'label': 'LABEL_0'}, {'score': 0.48_01, 'label': 'LABEL_1'}], ] , ) @require_tf def A_ ( self ): pass
12
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor lowerCamelCase__ : Tuple = logging.get_logger(__name__) class _UpperCAmelCase ( __a): def __init__( self , *_A , **_A ) -> None: '''simple docstring''' warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , _A , ) super().__init__(*_A , **_A )
246
"""simple docstring""" def UpperCamelCase ( _lowerCAmelCase : int, _lowerCAmelCase : int ) -> int: _UpperCAmelCase : str = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): _UpperCAmelCase : Dict = n - k # Calculate C(n,k) for i in range(_lowerCAmelCase ): result *= n - i result //= i + 1 return result def UpperCamelCase ( _lowerCAmelCase : int ) -> int: return binomial_coefficient(2 * node_count, _lowerCAmelCase ) // (node_count + 1) def UpperCamelCase ( _lowerCAmelCase : int ) -> int: if n < 0: raise ValueError("""factorial() not defined for negative values""" ) _UpperCAmelCase : str = 1 for i in range(1, n + 1 ): result *= i return result def UpperCamelCase ( _lowerCAmelCase : int ) -> int: return catalan_number(_lowerCAmelCase ) * factorial(_lowerCAmelCase ) if __name__ == "__main__": lowerCamelCase__ : Optional[Any] = int(input('''Enter the number of nodes: ''').strip() or 0) if node_count <= 0: raise ValueError('''We need some nodes to work with.''') print( F'''Given {node_count} nodes, there are {binary_tree_count(node_count)} ''' F'''binary trees and {catalan_number(node_count)} binary search trees.''' )
246
1
'''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 UpperCamelCase ( a ) -> Dict: '''simple docstring''' # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. __magic_name__ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: __magic_name__ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: __magic_name__ = v.replace(a , a ) __magic_name__ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: __magic_name__ = v.replace(a , a ) __magic_name__ = v __magic_name__ = {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 UpperCamelCase ( a ) -> Dict: '''simple docstring''' # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape , 1 , 1 ) def UpperCamelCase ( a ) -> Tuple: '''simple docstring''' __magic_name__ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: __magic_name__ = v.replace(a , a ) __magic_name__ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: __magic_name__ = v.replace(a , a ) __magic_name__ = v __magic_name__ = {v: vae_state_dict[k] for k, v in mapping.items()} __magic_name__ = ['''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''' ) __magic_name__ = reshape_weight_for_sd(a ) 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 UpperCamelCase ( a ) -> Tuple: '''simple docstring''' __magic_name__ = {} __magic_name__ = {} __magic_name__ = {} 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''' ) ): __magic_name__ = k[: -len('''.q_proj.weight''' )] __magic_name__ = k[-len('''q_proj.weight''' )] if k_pre not in capture_qkv_weight: __magic_name__ = [None, None, None] __magic_name__ = 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''' ) ): __magic_name__ = k[: -len('''.q_proj.bias''' )] __magic_name__ = k[-len('''q_proj.bias''' )] if k_pre not in capture_qkv_bias: __magic_name__ = [None, None, None] __magic_name__ = v continue __magic_name__ = textenc_pattern.sub(lambda a : protected[re.escape(m.group(0 ) )] , a ) __magic_name__ = 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''' ) __magic_name__ = textenc_pattern.sub(lambda a : protected[re.escape(m.group(0 ) )] , a ) __magic_name__ = torch.cat(a ) 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''' ) __magic_name__ = textenc_pattern.sub(lambda a : protected[re.escape(m.group(0 ) )] , a ) __magic_name__ = torch.cat(a ) return new_state_dict def UpperCamelCase ( a ) -> int: '''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)
98
'''simple docstring''' from pathlib import Path import fire from tqdm import tqdm def UpperCamelCase ( a="ro" , a="en" , a="wmt16" , a=None ) -> None: '''simple docstring''' try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError('''run pip install datasets''' ) __magic_name__ = F'''{src_lang}-{tgt_lang}''' print(F'''Converting {dataset}-{pair}''' ) __magic_name__ = datasets.load_dataset(a , a ) if save_dir is None: __magic_name__ = F'''{dataset}-{pair}''' __magic_name__ = Path(a ) save_dir.mkdir(exist_ok=a ) for split in ds.keys(): print(F'''Splitting {split} with {ds[split].num_rows} records''' ) # to save to val.source, val.target like summary datasets __magic_name__ = '''val''' if split == '''validation''' else split __magic_name__ = save_dir.joinpath(F'''{fn}.source''' ) __magic_name__ = save_dir.joinpath(F'''{fn}.target''' ) __magic_name__ = src_path.open('''w+''' ) __magic_name__ = tgt_path.open('''w+''' ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): __magic_name__ = x['''translation'''] src_fp.write(ex[src_lang] + '''\n''' ) tgt_fp.write(ex[tgt_lang] + '''\n''' ) print(F'''Saved {dataset} dataset to {save_dir}''' ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
98
1
"""simple docstring""" def UpperCamelCase_ ( lowerCAmelCase__ : Union[str, Any] ) -> str: """simple docstring""" if not all(char in '01' for char in bin_string ): raise ValueError('Non-binary value was passed to the function' ) if not bin_string: raise ValueError('Empty string was passed to the function' ) lowerCAmelCase_ : int = '' while len(_lowerCAmelCase ) % 3 != 0: lowerCAmelCase_ : str = '0' + bin_string lowerCAmelCase_ : Union[str, Any] = [ bin_string[index : index + 3] for index in range(len(_lowerCAmelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: lowerCAmelCase_ : Tuple = 0 for index, val in enumerate(_lowerCAmelCase ): oct_val += int(2 ** (2 - index) * int(_lowerCAmelCase ) ) oct_string += str(_lowerCAmelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
224
'''simple docstring''' from __future__ import annotations import math from collections.abc import Callable def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase = 100 ,) -> float: __lowerCamelCase : Dict = x_start __lowerCamelCase : int = fnc(_lowerCAmelCase ) __lowerCamelCase : Dict = 0.0 for _ in range(_lowerCAmelCase ): # Approximates curve as a sequence of linear lines and sums their length __lowerCamelCase : List[str] = (x_end - x_start) / steps + xa __lowerCamelCase : List[Any] = fnc(_lowerCAmelCase ) length += math.hypot(xa - xa ,fxa - fxa ) # Increment step __lowerCamelCase : Any = xa __lowerCamelCase : Tuple = fxa return length if __name__ == "__main__": def a_ ( _lowerCAmelCase ) -> Dict: return math.sin(10 * x ) print('f(x) = sin(10 * x)') print('The length of the curve from x = -10 to x = 10 is:') _UpperCamelCase = 10 while i <= 100000: print(f'''With {i} steps: {line_length(f, -10, 10, i)}''') i *= 10
208
0
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : Dict , snake_case_ : Any , snake_case_ : List[Any] , snake_case_ : Union[str, Any] ) -> List[Any]: '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: UpperCAmelCase_ = mf_knapsack(i - 1 , snake_case_ , snake_case_ , snake_case_ ) else: UpperCAmelCase_ = max( mf_knapsack(i - 1 , snake_case_ , snake_case_ , snake_case_ ) , mf_knapsack(i - 1 , snake_case_ , snake_case_ , j - wt[i - 1] ) + val[i - 1] , ) UpperCAmelCase_ = val return f[i][j] def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : Dict , snake_case_ : Dict , snake_case_ : Tuple ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: UpperCAmelCase_ = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: UpperCAmelCase_ = dp[i - 1][w_] return dp[n][w_], dp def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : list , snake_case_ : list ) -> Union[str, Any]: '''simple docstring''' if not (isinstance(snake_case_ , (list, tuple) ) and isinstance(snake_case_ , (list, tuple) )): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) UpperCAmelCase_ = len(snake_case_ ) if num_items != len(snake_case_ ): UpperCAmelCase_ = ( "The number of weights must be the same as the number of values.\n" f"""But got {num_items} weights and {len(snake_case_ )} values""" ) raise ValueError(snake_case_ ) for i in range(snake_case_ ): if not isinstance(wt[i] , snake_case_ ): UpperCAmelCase_ = ( "All weights must be integers but got weight of " f"""type {type(wt[i] )} at index {i}""" ) raise TypeError(snake_case_ ) UpperCAmelCase_ , UpperCAmelCase_ = knapsack(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) UpperCAmelCase_ = set() _construct_solution(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) return optimal_val, example_optional_set def lowerCAmelCase_ ( snake_case_ : list , snake_case_ : list , snake_case_ : int , snake_case_ : int , snake_case_ : set ) -> Tuple: '''simple docstring''' if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(snake_case_ , snake_case_ , i - 1 , snake_case_ , snake_case_ ) else: optimal_set.add(snake_case_ ) _construct_solution(snake_case_ , snake_case_ , i - 1 , j - wt[i - 1] , snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: List[Any] =[3, 2, 4, 4] SCREAMING_SNAKE_CASE_: int =[4, 3, 2, 3] SCREAMING_SNAKE_CASE_: str =4 SCREAMING_SNAKE_CASE_: Tuple =6 SCREAMING_SNAKE_CASE_: Optional[int] =[[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Optional[Any] =knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Dict =knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('optimal_value = ', optimal_solution) print('An optimal subset corresponding to the optimal value', optimal_subset)
106
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib SCREAMING_SNAKE_CASE_: List[str] =get_logger() SCREAMING_SNAKE_CASE_: Optional[dict] =None class __A ( TensorFormatter[Mapping, """jax.Array""", Mapping] ): def __init__(self : List[Any] , __a : Optional[int]=None , __a : Any=None , **__a : Dict ): super().__init__(features=__a ) import jax from jaxlib.xla_client import Device if isinstance(__a , __a ): raise ValueError( f"""Expected {device} to be a `str` not {type(__a )}, as `jaxlib.xla_extension.Device` """ "is not serializable neither with `pickle` nor with `dill`. Instead you can surround " "the device with `str()` to get its string identifier that will be internally mapped " "to the actual `jaxlib.xla_extension.Device`." ) UpperCAmelCase_ = device if isinstance(__a , __a ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: UpperCAmelCase_ = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f"""Device with string identifier {self.device} not listed among the available """ f"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ f"""device: {str(jax.devices()[0] )}.""" ) UpperCAmelCase_ = str(jax.devices()[0] ) UpperCAmelCase_ = jnp_array_kwargs @staticmethod def _lowercase (): import jax return {str(__a ): device for device in jax.devices()} def _lowercase (self : str , __a : Tuple ): import jax import jax.numpy as jnp if isinstance(__a , __a ) and column: if all( isinstance(__a , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(__a , axis=0 ) return column def _lowercase (self : Any , __a : Optional[int] ): import jax import jax.numpy as jnp if isinstance(__a , (str, bytes, type(__a )) ): return value elif isinstance(__a , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() UpperCAmelCase_ = {} if isinstance(__a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: UpperCAmelCase_ = {"dtype": jnp.intaa} else: UpperCAmelCase_ = {"dtype": jnp.intaa} elif isinstance(__a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): UpperCAmelCase_ = {"dtype": jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(__a , PIL.Image.Image ): UpperCAmelCase_ = np.asarray(__a ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: UpperCAmelCase_ = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(__a , **{**default_dtype, **self.jnp_array_kwargs} ) def _lowercase (self : int , __a : Any ): import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(__a , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(__a , "__array__" ) and not isinstance(__a , jax.Array ): UpperCAmelCase_ = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(__a , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(__a ) for substruct in data_struct] ) elif isinstance(__a , (list, tuple) ): return self._consolidate([self.recursive_tensorize(__a ) for substruct in data_struct] ) return self._tensorize(__a ) def _lowercase (self : Union[str, Any] , __a : dict ): return map_nested(self._recursive_tensorize , __a , map_list=__a ) def _lowercase (self : str , __a : pa.Table ): UpperCAmelCase_ = self.numpy_arrow_extractor().extract_row(__a ) UpperCAmelCase_ = self.python_features_decoder.decode_row(__a ) return self.recursive_tensorize(__a ) def _lowercase (self : Tuple , __a : pa.Table ): UpperCAmelCase_ = self.numpy_arrow_extractor().extract_column(__a ) UpperCAmelCase_ = self.python_features_decoder.decode_column(__a , pa_table.column_names[0] ) UpperCAmelCase_ = self.recursive_tensorize(__a ) UpperCAmelCase_ = self._consolidate(__a ) return column def _lowercase (self : str , __a : pa.Table ): UpperCAmelCase_ = self.numpy_arrow_extractor().extract_batch(__a ) UpperCAmelCase_ = self.python_features_decoder.decode_batch(__a ) UpperCAmelCase_ = self.recursive_tensorize(__a ) for column_name in batch: UpperCAmelCase_ = self._consolidate(batch[column_name] ) return batch
106
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''microsoft/biogpt''': '''https://huggingface.co/microsoft/biogpt/resolve/main/config.json''', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class lowercase( __a ): '''simple docstring''' lowercase__ = "biogpt" def __init__( self: Dict, a_: List[Any]=42_384, a_: int=1_024, a_: Optional[int]=24, a_: List[str]=16, a_: Optional[Any]=4_096, a_: int="gelu", a_: int=0.1, a_: List[Any]=0.1, a_: Any=1_024, a_: Optional[Any]=0.02, a_: Dict=1E-12, a_: Tuple=True, a_: Any=True, a_: Tuple=0.0, a_: str=0.0, a_: int=1, a_: Any=0, a_: List[str]=2, **a_: Optional[int], ): '''simple docstring''' _snake_case : Dict = vocab_size _snake_case : int = max_position_embeddings _snake_case : Optional[int] = hidden_size _snake_case : Any = num_hidden_layers _snake_case : List[str] = num_attention_heads _snake_case : Optional[int] = intermediate_size _snake_case : Dict = hidden_act _snake_case : Tuple = hidden_dropout_prob _snake_case : Tuple = attention_probs_dropout_prob _snake_case : Optional[Any] = initializer_range _snake_case : List[str] = layer_norm_eps _snake_case : List[str] = scale_embedding _snake_case : Dict = use_cache _snake_case : Optional[int] = layerdrop _snake_case : Any = activation_dropout super().__init__(pad_token_id=a_, bos_token_id=a_, eos_token_id=a_, **a_ )
64
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() a_ :str = logging.get_logger(__name__) def lowercase_ (A : str ): snake_case__ : Tuple = SwinConfig.from_pretrained( 'microsoft/swin-tiny-patch4-window7-224' , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) snake_case__ : List[Any] = MaskFormerConfig(backbone_config=A ) snake_case__ : Union[str, Any] = 'huggingface/label-files' if "ade20k-full" in model_name: # this should be ok snake_case__ : Dict = 8_4_7 snake_case__ : List[str] = 'maskformer-ade20k-full-id2label.json' elif "ade" in model_name: # this should be ok snake_case__ : Union[str, Any] = 1_5_0 snake_case__ : Any = 'ade20k-id2label.json' elif "coco-stuff" in model_name: # this should be ok snake_case__ : List[str] = 1_7_1 snake_case__ : Union[str, Any] = 'maskformer-coco-stuff-id2label.json' elif "coco" in model_name: # TODO snake_case__ : Dict = 1_3_3 snake_case__ : str = 'coco-panoptic-id2label.json' elif "cityscapes" in model_name: # this should be ok snake_case__ : List[str] = 1_9 snake_case__ : Union[str, Any] = 'cityscapes-id2label.json' elif "vistas" in model_name: # this should be ok snake_case__ : Tuple = 6_5 snake_case__ : List[str] = 'mapillary-vistas-id2label.json' snake_case__ : Dict = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) snake_case__ : List[str] = {int(A ): v for k, v in idalabel.items()} return config def lowercase_ (A : Any ): snake_case__ : Optional[int] = [] # stem # fmt: off rename_keys.append(('backbone.patch_embed.proj.weight', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.patch_embed.proj.bias', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.patch_embed.norm.weight', 'model.pixel_level_module.encoder.model.embeddings.norm.weight') ) rename_keys.append(('backbone.patch_embed.norm.bias', 'model.pixel_level_module.encoder.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.layers.{i}.blocks.{j}.norm1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.layers.{i}.downsample.reduction.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((F'''backbone.norm{i}.weight''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((F'''backbone.norm{i}.bias''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(('sem_seg_head.layer_4.weight', 'model.pixel_level_module.decoder.fpn.stem.0.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.weight', 'model.pixel_level_module.decoder.fpn.stem.1.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.bias', 'model.pixel_level_module.decoder.fpn.stem.1.bias') ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((F'''sem_seg_head.adapter_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(('sem_seg_head.mask_features.weight', 'model.pixel_level_module.decoder.mask_projection.weight') ) rename_keys.append(('sem_seg_head.mask_features.bias', 'model.pixel_level_module.decoder.mask_projection.bias') ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.weight', 'model.transformer_module.decoder.layernorm.weight') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.bias', 'model.transformer_module.decoder.layernorm.bias') ) # heads on top rename_keys.append(('sem_seg_head.predictor.query_embed.weight', 'model.transformer_module.queries_embedder.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.weight', 'model.transformer_module.input_projection.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.bias', 'model.transformer_module.input_projection.bias') ) rename_keys.append(('sem_seg_head.predictor.class_embed.weight', 'class_predictor.weight') ) rename_keys.append(('sem_seg_head.predictor.class_embed.bias', 'class_predictor.bias') ) for i in range(3 ): rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', F'''mask_embedder.{i}.0.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', F'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def lowercase_ (A : Tuple , A : Tuple , A : Optional[Any] ): snake_case__ : Optional[int] = dct.pop(A ) snake_case__ : Union[str, Any] = val def lowercase_ (A : Optional[Any] , A : Tuple ): snake_case__ : Optional[int] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): snake_case__ : Optional[int] = 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) snake_case__ : int = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) snake_case__ : Tuple = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : str = in_proj_weight[:dim, :] snake_case__ : int = in_proj_bias[: dim] snake_case__ : List[Any] = in_proj_weight[ dim : dim * 2, : ] snake_case__ : List[str] = in_proj_bias[ dim : dim * 2 ] snake_case__ : List[Any] = in_proj_weight[ -dim :, : ] snake_case__ : Dict = in_proj_bias[-dim :] # fmt: on def lowercase_ (A : List[str] , A : List[Any] ): # fmt: off snake_case__ : str = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case__ : List[Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) snake_case__ : int = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Any = in_proj_weight[: hidden_size, :] snake_case__ : Tuple = in_proj_bias[:config.hidden_size] snake_case__ : List[str] = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case__ : Dict = in_proj_bias[hidden_size : hidden_size * 2] snake_case__ : Any = in_proj_weight[-hidden_size :, :] snake_case__ : int = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case__ : List[Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) snake_case__ : List[str] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[: hidden_size, :] snake_case__ : Optional[Any] = in_proj_bias[:config.hidden_size] snake_case__ : int = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case__ : List[str] = in_proj_bias[hidden_size : hidden_size * 2] snake_case__ : List[str] = in_proj_weight[-hidden_size :, :] snake_case__ : str = in_proj_bias[-hidden_size :] # fmt: on def lowercase_ (): snake_case__ : Any = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case__ : int = Image.open(requests.get(A , stream=A ).raw ) return im @torch.no_grad() def lowercase_ (A : str , A : str , A : str , A : bool = False ): snake_case__ : Optional[int] = get_maskformer_config(A ) # load original state_dict with open(A , 'rb' ) as f: snake_case__ : List[Any] = pickle.load(A ) snake_case__ : Optional[int] = data['model'] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys snake_case__ : List[str] = create_rename_keys(A ) for src, dest in rename_keys: rename_key(A , A , A ) read_in_swin_q_k_v(A , config.backbone_config ) read_in_decoder_q_k_v(A , A ) # update to torch tensors for key, value in state_dict.items(): snake_case__ : int = torch.from_numpy(A ) # load 🤗 model snake_case__ : str = MaskFormerForInstanceSegmentation(A ) model.eval() for name, param in model.named_parameters(): print(A , param.shape ) snake_case__ , snake_case__ : Union[str, Any] = model.load_state_dict(A , strict=A ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(A ) == 0, F'''Unexpected keys: {unexpected_keys}''' # verify results snake_case__ : Optional[Any] = prepare_img() if "vistas" in model_name: snake_case__ : int = 6_5 elif "cityscapes" in model_name: snake_case__ : Dict = 6_5_5_3_5 else: snake_case__ : Tuple = 2_5_5 snake_case__ : Optional[int] = True if 'ade' in model_name else False snake_case__ : Dict = MaskFormerImageProcessor(ignore_index=A , reduce_labels=A ) snake_case__ : Any = image_processor(A , return_tensors='pt' ) snake_case__ : Any = model(**A ) print('Logits:' , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": snake_case__ : Tuple = torch.tensor( [[3.6353, -4.4770, -2.6065], [0.5081, -4.2394, -3.5343], [2.1909, -5.0353, -1.9323]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , A , atol=1e-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(A ).mkdir(exist_ok=A ) model.save_pretrained(A ) image_processor.save_pretrained(A ) if push_to_hub: print('Pushing model and image processor to the hub...' ) model.push_to_hub(F'''nielsr/{model_name}''' ) image_processor.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": a_ :Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="maskformer-swin-tiny-ade", type=str, help=("Name of the MaskFormer model you'd like to convert",), ) parser.add_argument( "--checkpoint_path", default="/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl", type=str, help="Path to the original state dict (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a_ :Dict = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
277
0
"""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 __A = ( '''https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py''' ) __A = logging.get_logger(__name__) # pylint: disable=invalid-name def lowercase_ ( ) -> Tuple: '''simple docstring''' __lowerCamelCase : List[str] = '''https://pypi.org/pypi/diffusers/json''' __lowerCamelCase : Any = json.loads(request.urlopen(A_ ).read() )['''releases'''].keys() return sorted(A_ , key=lambda _lowerCamelCase : version.Version(A_ ) ) def lowercase_ ( ) -> Union[str, Any]: '''simple docstring''' if HF_MODULES_CACHE in sys.path: return sys.path.append(A_ ) os.makedirs(A_ , exist_ok=A_ ) __lowerCamelCase : List[Any] = Path(A_ ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowercase_ ( _lowerCamelCase: List[Any] ) -> Tuple: '''simple docstring''' init_hf_modules() __lowerCamelCase : List[str] = Path(A_ ) / 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(A_ , exist_ok=A_ ) __lowerCamelCase : Union[str, Any] = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowercase_ ( _lowerCamelCase: Optional[Any] ) -> Optional[Any]: '''simple docstring''' with open(A_ , "r" , encoding="utf-8" ) as f: __lowerCamelCase : List[str] = f.read() # Imports of the form `import .xxx` __lowerCamelCase : Any = re.findall("^\s*import\s+\.(\S+)\s*$" , A_ , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import" , A_ , flags=re.MULTILINE ) # Unique-ify return list(set(A_ ) ) def lowercase_ ( _lowerCamelCase: List[Any] ) -> str: '''simple docstring''' __lowerCamelCase : Optional[Any] = False __lowerCamelCase : Optional[Any] = [module_file] __lowerCamelCase : int = [] # Let's recurse through all relative imports while not no_change: __lowerCamelCase : Optional[Any] = [] for f in files_to_check: new_imports.extend(get_relative_imports(A_ ) ) __lowerCamelCase : Optional[int] = Path(A_ ).parent __lowerCamelCase : List[Any] = [str(module_path / m ) for m in new_imports] __lowerCamelCase : Tuple = [f for f in new_import_files if f not in all_relative_imports] __lowerCamelCase : Dict = [F"""{f}.py""" for f in new_import_files] __lowerCamelCase : Union[str, Any] = len(A_ ) == 0 all_relative_imports.extend(A_ ) return all_relative_imports def lowercase_ ( _lowerCamelCase: int ) -> Optional[int]: '''simple docstring''' with open(A_ , "r" , encoding="utf-8" ) as f: __lowerCamelCase : Optional[Any] = f.read() # Imports of the form `import xxx` __lowerCamelCase : Tuple = re.findall("^\s*import\s+(\S+)\s*$" , A_ , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall("^\s*from\s+(\S+)\s+import" , A_ , flags=re.MULTILINE ) # Only keep the top-level module __lowerCamelCase : str = [imp.split("." )[0] for imp in imports if not imp.startswith("." )] # Unique-ify and test we got them all __lowerCamelCase : Union[str, Any] = list(set(A_ ) ) __lowerCamelCase : List[Any] = [] for imp in imports: try: importlib.import_module(A_ ) except ImportError: missing_packages.append(A_ ) if len(A_ ) > 0: raise ImportError( "This modeling file requires the following packages that were not found in your environment: " F"""{", ".join(A_ )}. Run `pip install {" ".join(A_ )}`""" ) return get_relative_imports(A_ ) def lowercase_ ( _lowerCamelCase: Any , _lowerCamelCase: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __lowerCamelCase : List[str] = module_path.replace(os.path.sep , "." ) __lowerCamelCase : Any = importlib.import_module(A_ ) if class_name is None: return find_pipeline_class(A_ ) return getattr(A_ , A_ ) def lowercase_ ( _lowerCamelCase: List[Any] ) -> Dict: '''simple docstring''' from ..pipelines import DiffusionPipeline __lowerCamelCase : List[Any] = dict(inspect.getmembers(A_ , inspect.isclass ) ) __lowerCamelCase : Union[str, Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , A_ ) 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}.""" ) __lowerCamelCase : Tuple = cls return pipeline_class def lowercase_ ( _lowerCamelCase: Tuple , _lowerCamelCase: Tuple , _lowerCamelCase: Tuple = None , _lowerCamelCase: int = False , _lowerCamelCase: List[str] = False , _lowerCamelCase: List[str] = None , _lowerCamelCase: List[str] = None , _lowerCamelCase: Any = None , _lowerCamelCase: List[Any] = False , ) -> Dict: '''simple docstring''' __lowerCamelCase : Tuple = str(A_ ) __lowerCamelCase : str = os.path.join(A_ , A_ ) if os.path.isfile(A_ ): __lowerCamelCase : Optional[Any] = module_file_or_url __lowerCamelCase : Dict = '''local''' elif pretrained_model_name_or_path.count("/" ) == 0: __lowerCamelCase : Union[str, Any] = get_diffusers_versions() # cut ".dev0" __lowerCamelCase : Any = '''v''' + '''.'''.join(__version__.split("." )[:3] ) # retrieve github version that matches if revision is None: __lowerCamelCase : 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: __lowerCamelCase : Optional[Any] = F"""v{revision}""" elif revision == "main": __lowerCamelCase : Tuple = 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 __lowerCamelCase : Tuple = COMMUNITY_PIPELINES_URL.format(revision=A_ , pipeline=A_ ) try: __lowerCamelCase : str = cached_download( A_ , cache_dir=A_ , force_download=A_ , proxies=A_ , resume_download=A_ , local_files_only=A_ , use_auth_token=A_ , ) __lowerCamelCase : Dict = '''git''' __lowerCamelCase : Union[str, Any] = 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 __lowerCamelCase : Dict = hf_hub_download( A_ , A_ , cache_dir=A_ , force_download=A_ , proxies=A_ , resume_download=A_ , local_files_only=A_ , use_auth_token=A_ , ) __lowerCamelCase : str = 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 __lowerCamelCase : Optional[int] = check_imports(A_ ) # Now we move the module inside our cached dynamic modules. __lowerCamelCase : int = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(A_ ) __lowerCamelCase : Tuple = Path(A_ ) / 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(A_ , submodule_path / module_file ) for module_needed in modules_needed: __lowerCamelCase : str = F"""{module_needed}.py""" shutil.copy(os.path.join(A_ , A_ ) , 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(A_ , A_ ): __lowerCamelCase : List[str] = use_auth_token elif use_auth_token is True: __lowerCamelCase : Optional[int] = HfFolder.get_token() else: __lowerCamelCase : List[Any] = None __lowerCamelCase : List[Any] = model_info(A_ , revision=A_ , token=A_ ).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. __lowerCamelCase : List[str] = submodule_path / commit_hash __lowerCamelCase : Optional[Any] = full_submodule + os.path.sep + commit_hash create_dynamic_module(A_ ) if not (submodule_path / module_file).exists(): shutil.copy(A_ , 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( A_ , F"""{module_needed}.py""" , cache_dir=A_ , force_download=A_ , resume_download=A_ , proxies=A_ , use_auth_token=A_ , revision=A_ , local_files_only=A_ , ) return os.path.join(A_ , A_ ) def lowercase_ ( _lowerCamelCase: Tuple , _lowerCamelCase: Optional[Any] , _lowerCamelCase: Optional[Any] = None , _lowerCamelCase: int = None , _lowerCamelCase: str = False , _lowerCamelCase: Union[str, Any] = False , _lowerCamelCase: List[str] = None , _lowerCamelCase: Optional[int] = None , _lowerCamelCase: Optional[int] = None , _lowerCamelCase: int = False , **_lowerCamelCase: str , ) -> int: '''simple docstring''' __lowerCamelCase : Tuple = get_cached_module_file( A_ , A_ , cache_dir=A_ , force_download=A_ , resume_download=A_ , proxies=A_ , use_auth_token=A_ , revision=A_ , local_files_only=A_ , ) return get_class_in_module(A_ , final_module.replace(".py" , "" ) )
357
"""simple docstring""" from typing import Any import numpy as np def lowercase_ ( _lowerCamelCase: np.ndarray ) -> bool: '''simple docstring''' return np.array_equal(_lowerCamelCase , matrix.conjugate().T ) def lowercase_ ( _lowerCamelCase: np.ndarray , _lowerCamelCase: np.ndarray ) -> Any: '''simple docstring''' __lowerCamelCase : Union[str, Any] = v.conjugate().T __lowerCamelCase : Any = v_star.dot(_lowerCamelCase ) assert isinstance(_lowerCamelCase , np.ndarray ) return (v_star_dot.dot(_lowerCamelCase )) / (v_star.dot(_lowerCamelCase )) def lowercase_ ( ) -> None: '''simple docstring''' __lowerCamelCase : List[str] = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) __lowerCamelCase : int = np.array([[1], [2], [3]] ) assert is_hermitian(_lowerCamelCase ), F"""{a} is not hermitian.""" print(rayleigh_quotient(_lowerCamelCase , _lowerCamelCase ) ) __lowerCamelCase : Dict = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(_lowerCamelCase ), F"""{a} is not hermitian.""" assert rayleigh_quotient(_lowerCamelCase , _lowerCamelCase ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
64
0
"""simple docstring""" import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def lowercase ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : Union[str, Any] ) ->Optional[Any]: """simple docstring""" __snake_case : Optional[Any] = AlbertConfig.from_json_file(_snake_case ) print(f"""Building PyTorch model from configuration: {config}""" ) __snake_case : Tuple = AlbertForPreTraining(_snake_case ) # Load weights from tf checkpoint load_tf_weights_in_albert(_snake_case , _snake_case , _snake_case ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _snake_case ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : Optional[Any] = 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( """--albert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained ALBERT 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.""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
102
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer __lowerCamelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} __lowerCamelCase = { """vocab_file""": { """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt""", }, """tokenizer_file""": { """unc-nlp/lxmert-base-uncased""": ( """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json""" ), }, } __lowerCamelCase = { """unc-nlp/lxmert-base-uncased""": 5_12, } __lowerCamelCase = { """unc-nlp/lxmert-base-uncased""": {"""do_lower_case""": True}, } class UpperCAmelCase ( A_ ): A__ : Any = VOCAB_FILES_NAMES A__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP A__ : Tuple = PRETRAINED_INIT_CONFIGURATION A__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : List[Any] = LxmertTokenizer def __init__(self : Dict , snake_case__ : Tuple=None , snake_case__ : Optional[Any]=None , snake_case__ : Optional[Any]=True , snake_case__ : Tuple="[UNK]" , snake_case__ : Optional[Any]="[SEP]" , snake_case__ : Optional[Any]="[PAD]" , snake_case__ : List[Any]="[CLS]" , snake_case__ : Tuple="[MASK]" , snake_case__ : Dict=True , snake_case__ : Union[str, Any]=None , **snake_case__ : Dict , ) -> Optional[int]: '''simple docstring''' super().__init__( snake_case__ , tokenizer_file=snake_case__ , do_lower_case=snake_case__ , unk_token=snake_case__ , sep_token=snake_case__ , pad_token=snake_case__ , cls_token=snake_case__ , mask_token=snake_case__ , tokenize_chinese_chars=snake_case__ , strip_accents=snake_case__ , **snake_case__ , ) snake_case : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , snake_case__ ) != do_lower_case or normalizer_state.get("strip_accents" , snake_case__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , snake_case__ ) != tokenize_chinese_chars ): snake_case : Union[str, Any] = getattr(snake_case__ , normalizer_state.pop("type" ) ) snake_case : str = do_lower_case snake_case : List[Any] = strip_accents snake_case : Optional[int] = tokenize_chinese_chars snake_case : int = normalizer_class(**snake_case__ ) snake_case : Optional[Any] = do_lower_case def _SCREAMING_SNAKE_CASE (self : Union[str, Any] , snake_case__ : Optional[Any] , snake_case__ : Dict=None ) -> Any: '''simple docstring''' snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : List[int] , snake_case__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' snake_case : Optional[Any] = [self.sep_token_id] snake_case : Optional[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 ) * [0] + len(token_ids_a + sep ) * [1] def _SCREAMING_SNAKE_CASE (self : Any , snake_case__ : str , snake_case__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' snake_case : List[Any] = self._tokenizer.model.save(snake_case__ , name=snake_case__ ) return tuple(snake_case__ )
59
0
'''simple docstring''' import os from typing import Dict, List, Tuple, TypeVar, Union a_ : Tuple = TypeVar("""T""") a_ : Dict = Union[List[T], Tuple[T, ...]] a_ : int = Union[T, List[T], Dict[str, T]] a_ : Optional[Any] = Union[str, bytes, os.PathLike]
6
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __UpperCamelCase ( lowerCamelCase__ , unittest.TestCase ): lowercase : Union[str, Any] =ShapEImgaImgPipeline lowercase : Dict =['image'] lowercase : str =['image'] lowercase : int =[ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] lowercase : int =False @property def lowercase__ ( self ): """simple docstring""" return 32 @property def lowercase__ ( self ): """simple docstring""" return 32 @property def lowercase__ ( self ): """simple docstring""" return self.time_input_dim * 4 @property def lowercase__ ( self ): """simple docstring""" return 8 @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ =CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size, image_size=64, projection_dim=self.text_embedder_hidden_size, intermediate_size=37, num_attention_heads=4, num_channels=3, num_hidden_layers=5, patch_size=1, ) lowerCamelCase_ =CLIPVisionModel(lowerCAmelCase ) return model @property def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =CLIPImageProcessor( crop_size=224, do_center_crop=lowerCAmelCase, do_normalize=lowerCAmelCase, do_resize=lowerCAmelCase, image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], resample=3, size=224, ) return image_processor @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ ={ '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowerCamelCase_ =PriorTransformer(**lowerCAmelCase ) return model @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ ={ '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } lowerCamelCase_ =ShapERenderer(**lowerCAmelCase ) return model def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.dummy_prior lowerCamelCase_ =self.dummy_image_encoder lowerCamelCase_ =self.dummy_image_processor lowerCamelCase_ =self.dummy_renderer lowerCamelCase_ =HeunDiscreteScheduler( beta_schedule='''exp''', num_train_timesteps=1_024, prediction_type='''sample''', use_karras_sigmas=lowerCAmelCase, clip_sample=lowerCAmelCase, clip_sample_range=1.0, ) lowerCamelCase_ ={ '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase=0 ): """simple docstring""" lowerCamelCase_ =floats_tensor((1, 3, 64, 64), rng=random.Random(lowerCAmelCase ) ).to(lowerCAmelCase ) if str(lowerCAmelCase ).startswith('''mps''' ): lowerCamelCase_ =torch.manual_seed(lowerCAmelCase ) else: lowerCamelCase_ =torch.Generator(device=lowerCAmelCase ).manual_seed(lowerCAmelCase ) lowerCamelCase_ ={ '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ='''cpu''' lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =self.pipeline_class(**lowerCAmelCase ) lowerCamelCase_ =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =pipe(**self.get_dummy_inputs(lowerCAmelCase ) ) lowerCamelCase_ =output.images[0] lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowerCamelCase_ =np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =torch_device == '''cpu''' lowerCamelCase_ =True self._test_inference_batch_single_identical( batch_size=2, test_max_difference=lowerCAmelCase, relax_max_difference=lowerCAmelCase, ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.get_dummy_components() lowerCamelCase_ =self.pipeline_class(**lowerCAmelCase ) lowerCamelCase_ =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =1 lowerCamelCase_ =2 lowerCamelCase_ =self.get_dummy_inputs(lowerCAmelCase ) for key in inputs.keys(): if key in self.batch_params: lowerCamelCase_ =batch_size * [inputs[key]] lowerCamelCase_ =pipe(**lowerCAmelCase, num_images_per_prompt=lowerCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def lowercase__ ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowerCamelCase_ =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowerCamelCase_ =ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowerCamelCase_ =pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =torch.Generator(device=lowerCAmelCase ).manual_seed(0 ) lowerCamelCase_ =pipe( lowerCAmelCase, generator=lowerCAmelCase, guidance_scale=3.0, num_inference_steps=64, frame_size=64, output_type='''np''', ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(lowerCAmelCase, lowerCAmelCase )
6
1
def A_ ( _lowerCAmelCase = 1000 ) -> int: UpperCamelCase , UpperCamelCase : Any = 1, 1 UpperCamelCase : Dict = [] for i in range(1 , n + 1 ): UpperCamelCase : Union[str, Any] = prev_numerator + 2 * prev_denominator UpperCamelCase : List[Any] = prev_numerator + prev_denominator if len(str(_lowerCAmelCase ) ) > len(str(_lowerCAmelCase ) ): result.append(_lowerCAmelCase ) UpperCamelCase : Dict = numerator UpperCamelCase : Dict = denominator return len(_lowerCAmelCase ) if __name__ == "__main__": print(f"""{solution() = }""")
52
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated lowerCamelCase = collections.namedtuple('''_Datasets''', ['''train''', '''validation''', '''test''']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ lowerCamelCase = '''https://storage.googleapis.com/cvdf-datasets/mnist/''' def lowerCamelCase_ ( _a ): """simple docstring""" lowerCAmelCase__ : Dict = numpy.dtype(numpy.uintaa ).newbyteorder('''>''' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=_a )[0] @deprecated(_a , '''Please use tf.data to implement this functionality.''' ) def lowerCamelCase_ ( _a ): """simple docstring""" print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=_a ) as bytestream: lowerCAmelCase__ : Any = _readaa(_a ) if magic != 2_051: raise ValueError( '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) ) lowerCAmelCase__ : Any = _readaa(_a ) lowerCAmelCase__ : Tuple = _readaa(_a ) lowerCAmelCase__ : List[Any] = _readaa(_a ) lowerCAmelCase__ : Union[str, Any] = bytestream.read(rows * cols * num_images ) lowerCAmelCase__ : List[Any] = numpy.frombuffer(_a , dtype=numpy.uinta ) lowerCAmelCase__ : int = data.reshape(_a , _a , _a , 1 ) return data @deprecated(_a , '''Please use tf.one_hot on tensors.''' ) def lowerCamelCase_ ( _a , _a ): """simple docstring""" lowerCAmelCase__ : List[Any] = labels_dense.shape[0] lowerCAmelCase__ : Optional[Any] = numpy.arange(_a ) * num_classes lowerCAmelCase__ : str = numpy.zeros((num_labels, num_classes) ) lowerCAmelCase__ : Optional[Any] = 1 return labels_one_hot @deprecated(_a , '''Please use tf.data to implement this functionality.''' ) def lowerCamelCase_ ( _a , _a=False , _a=10 ): """simple docstring""" print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=_a ) as bytestream: lowerCAmelCase__ : Optional[int] = _readaa(_a ) if magic != 2_049: raise ValueError( '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) ) lowerCAmelCase__ : Union[str, Any] = _readaa(_a ) lowerCAmelCase__ : Tuple = bytestream.read(_a ) lowerCAmelCase__ : Dict = numpy.frombuffer(_a , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(_a , _a ) return labels class _a : @deprecated( _SCREAMING_SNAKE_CASE , '''Please use alternatives such as official/mnist/_DataSet.py''' ''' from tensorflow/models.''' , ) def __init__( self : Dict , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Tuple=False , _SCREAMING_SNAKE_CASE : Any=False , _SCREAMING_SNAKE_CASE : Optional[Any]=dtypes.floataa , _SCREAMING_SNAKE_CASE : List[str]=True , _SCREAMING_SNAKE_CASE : List[str]=None , )-> List[Any]: lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = random_seed.get_seed(_SCREAMING_SNAKE_CASE ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) lowerCAmelCase__ : Optional[int] = dtypes.as_dtype(_SCREAMING_SNAKE_CASE ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype ) if fake_data: lowerCAmelCase__ : int = 1_0000 lowerCAmelCase__ : List[Any] = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F'images.shape: {images.shape} labels.shape: {labels.shape}' lowerCAmelCase__ : List[Any] = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 lowerCAmelCase__ : Tuple = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. lowerCAmelCase__ : Any = images.astype(numpy.floataa ) lowerCAmelCase__ : Any = numpy.multiply(_SCREAMING_SNAKE_CASE , 1.0 / 255.0 ) lowerCAmelCase__ : Tuple = images lowerCAmelCase__ : Tuple = labels lowerCAmelCase__ : List[Any] = 0 lowerCAmelCase__ : Tuple = 0 @property def UpperCAmelCase__( self : Tuple )-> Dict: return self._images @property def UpperCAmelCase__( self : Tuple )-> Optional[int]: return self._labels @property def UpperCAmelCase__( self : Tuple )-> Dict: return self._num_examples @property def UpperCAmelCase__( self : Tuple )-> Any: return self._epochs_completed def UpperCAmelCase__( self : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Dict=False , _SCREAMING_SNAKE_CASE : Optional[int]=True )-> List[str]: if fake_data: lowerCAmelCase__ : Dict = [1] * 784 lowerCAmelCase__ : Union[str, Any] = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(_SCREAMING_SNAKE_CASE )], [fake_label for _ in range(_SCREAMING_SNAKE_CASE )], ) lowerCAmelCase__ : str = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: lowerCAmelCase__ : Union[str, Any] = numpy.arange(self._num_examples ) numpy.random.shuffle(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : List[Any] = self.images[perma] lowerCAmelCase__ : Tuple = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch lowerCAmelCase__ : Any = self._num_examples - start lowerCAmelCase__ : List[str] = self._images[start : self._num_examples] lowerCAmelCase__ : Tuple = self._labels[start : self._num_examples] # Shuffle the data if shuffle: lowerCAmelCase__ : Union[str, Any] = numpy.arange(self._num_examples ) numpy.random.shuffle(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : str = self.images[perm] lowerCAmelCase__ : List[Any] = self.labels[perm] # Start next epoch lowerCAmelCase__ : Dict = 0 lowerCAmelCase__ : Union[str, Any] = batch_size - rest_num_examples lowerCAmelCase__ : Any = self._index_in_epoch lowerCAmelCase__ : Optional[Any] = self._images[start:end] lowerCAmelCase__ : Optional[Any] = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size lowerCAmelCase__ : Dict = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(_a , '''Please write your own downloading logic.''' ) def lowerCamelCase_ ( _a , _a , _a ): """simple docstring""" if not gfile.Exists(_a ): gfile.MakeDirs(_a ) lowerCAmelCase__ : str = os.path.join(_a , _a ) if not gfile.Exists(_a ): urllib.request.urlretrieve(_a , _a ) # noqa: S310 with gfile.GFile(_a ) as f: lowerCAmelCase__ : Optional[Any] = f.size() print('''Successfully downloaded''' , _a , _a , '''bytes.''' ) return filepath @deprecated( _a , '''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' ) def lowerCamelCase_ ( _a , _a=False , _a=False , _a=dtypes.floataa , _a=True , _a=5_000 , _a=None , _a=DEFAULT_SOURCE_URL , ): """simple docstring""" if fake_data: def fake(): return _DataSet( [] , [] , fake_data=_a , one_hot=_a , dtype=_a , seed=_a ) lowerCAmelCase__ : Tuple = fake() lowerCAmelCase__ : Union[str, Any] = fake() lowerCAmelCase__ : Tuple = fake() return _Datasets(train=_a , validation=_a , test=_a ) if not source_url: # empty string check lowerCAmelCase__ : Optional[Any] = DEFAULT_SOURCE_URL lowerCAmelCase__ : Tuple = '''train-images-idx3-ubyte.gz''' lowerCAmelCase__ : Dict = '''train-labels-idx1-ubyte.gz''' lowerCAmelCase__ : List[str] = '''t10k-images-idx3-ubyte.gz''' lowerCAmelCase__ : Optional[int] = '''t10k-labels-idx1-ubyte.gz''' lowerCAmelCase__ : Optional[Any] = _maybe_download( _a , _a , source_url + train_images_file ) with gfile.Open(_a , '''rb''' ) as f: lowerCAmelCase__ : Optional[Any] = _extract_images(_a ) lowerCAmelCase__ : Any = _maybe_download( _a , _a , source_url + train_labels_file ) with gfile.Open(_a , '''rb''' ) as f: lowerCAmelCase__ : Any = _extract_labels(_a , one_hot=_a ) lowerCAmelCase__ : Any = _maybe_download( _a , _a , source_url + test_images_file ) with gfile.Open(_a , '''rb''' ) as f: lowerCAmelCase__ : str = _extract_images(_a ) lowerCAmelCase__ : Dict = _maybe_download( _a , _a , source_url + test_labels_file ) with gfile.Open(_a , '''rb''' ) as f: lowerCAmelCase__ : int = _extract_labels(_a , one_hot=_a ) if not 0 <= validation_size <= len(_a ): lowerCAmelCase__ : Dict = ( '''Validation size should be between 0 and ''' f'{len(_a )}. Received: {validation_size}.' ) raise ValueError(_a ) lowerCAmelCase__ : List[str] = train_images[:validation_size] lowerCAmelCase__ : Any = train_labels[:validation_size] lowerCAmelCase__ : Optional[Any] = train_images[validation_size:] lowerCAmelCase__ : Optional[int] = train_labels[validation_size:] lowerCAmelCase__ : Optional[Any] = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} lowerCAmelCase__ : List[str] = _DataSet(_a , _a , **_a ) lowerCAmelCase__ : Dict = _DataSet(_a , _a , **_a ) lowerCAmelCase__ : Dict = _DataSet(_a , _a , **_a ) return _Datasets(train=_a , validation=_a , test=_a )
131
0
def _A ( lowerCAmelCase_ : str = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" lowerCAmelCase__ = set() # Replace all the whitespace in our sentence lowerCAmelCase__ = input_str.replace(" " , "" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase_ ) == 26 def _A ( lowerCAmelCase_ : str = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" lowerCAmelCase__ = [False] * 26 for char in input_str: if char.islower(): lowerCAmelCase__ = True elif char.isupper(): lowerCAmelCase__ = True return all(lowerCAmelCase_ ) def _A ( lowerCAmelCase_ : str = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit lowerCAmelCase__ = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=lowerCAmelCase_ ) ) print(timeit("is_pangram_faster()" , setup=lowerCAmelCase_ ) ) print(timeit("is_pangram_fastest()" , setup=lowerCAmelCase_ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
354
from __future__ import annotations UpperCamelCase = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def _A ( lowerCAmelCase_ : list[list[int]] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : list[list[int]] , ): """simple docstring""" lowerCAmelCase__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the reference grid lowerCAmelCase__ = 1 lowerCAmelCase__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the action grid lowerCAmelCase__ = init[0] lowerCAmelCase__ = init[1] lowerCAmelCase__ = 0 lowerCAmelCase__ = g + heuristic[x][y] # cost from starting cell to destination cell lowerCAmelCase__ = [[f, g, x, y]] lowerCAmelCase__ = False # flag that is set when search is complete lowerCAmelCase__ = False # flag set if we can't find expand while not found and not resign: if len(lowerCAmelCase_ ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() lowerCAmelCase__ = cell.pop() lowerCAmelCase__ = next_cell[2] lowerCAmelCase__ = next_cell[3] lowerCAmelCase__ = next_cell[1] if x == goal[0] and y == goal[1]: lowerCAmelCase__ = True else: for i in range(len(lowerCAmelCase_ ) ): # to try out different valid actions lowerCAmelCase__ = x + DIRECTIONS[i][0] lowerCAmelCase__ = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(lowerCAmelCase_ ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: lowerCAmelCase__ = g + cost lowerCAmelCase__ = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) lowerCAmelCase__ = 1 lowerCAmelCase__ = i lowerCAmelCase__ = [] lowerCAmelCase__ = goal[0] lowerCAmelCase__ = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: lowerCAmelCase__ = x - DIRECTIONS[action[x][y]][0] lowerCAmelCase__ = y - DIRECTIONS[action[x][y]][1] lowerCAmelCase__ = xa lowerCAmelCase__ = ya invpath.append([x, y] ) lowerCAmelCase__ = [] for i in range(len(lowerCAmelCase_ ) ): path.append(invpath[len(lowerCAmelCase_ ) - 1 - i] ) return path, action if __name__ == "__main__": UpperCamelCase = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] UpperCamelCase = [0, 0] # all coordinates are given in format [y,x] UpperCamelCase = [len(grid) - 1, len(grid[0]) - 1] UpperCamelCase = 1 # the cost map which pushes the path closer to the goal UpperCamelCase = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): UpperCamelCase = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map UpperCamelCase = 99 UpperCamelCase , UpperCamelCase = search(grid, init, goal, cost, heuristic) print('ACTION MAP') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
221
0
'''simple docstring''' def _A ( A__ ): """simple docstring""" if not grid or not grid[0]: raise TypeError('''The grid does not contain the appropriate information''' ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] __lowercase = grid[0] for row_n in range(1 , len(A__ ) ): __lowercase = grid[row_n] __lowercase = fill_row(A__ , A__ ) __lowercase = grid[row_n] return grid[-1][-1] def _A ( A__ , A__ ): """simple docstring""" current_row[0] += row_above[0] for cell_n in range(1 , len(A__ ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
104
"""simple docstring""" import colorsys from PIL import Image # type: ignore def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): UpperCAmelCase = x UpperCAmelCase = y for step in range(lowercase_ ): # noqa: B007 UpperCAmelCase = a * a - b * b + x UpperCAmelCase = 2 * a * b + y UpperCAmelCase = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _lowerCAmelCase ( lowercase_ ): if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def _lowerCAmelCase ( lowercase_ ): if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(lowercase_ , 1 , 1 ) ) def _lowerCAmelCase ( lowercase_ = 800 , lowercase_ = 600 , lowercase_ = -0.6 , lowercase_ = 0 , lowercase_ = 3.2 , lowercase_ = 50 , lowercase_ = True , ): UpperCAmelCase = Image.new('RGB' , (image_width, image_height) ) UpperCAmelCase = img.load() # loop through the image-coordinates for image_x in range(lowercase_ ): for image_y in range(lowercase_ ): # determine the figure-coordinates based on the image-coordinates UpperCAmelCase = figure_width / image_width * image_height UpperCAmelCase = figure_center_x + (image_x / image_width - 0.5) * figure_width UpperCAmelCase = figure_center_y + (image_y / image_height - 0.5) * figure_height UpperCAmelCase = get_distance(lowercase_ , lowercase_ , lowercase_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: UpperCAmelCase = get_color_coded_rgb(lowercase_ ) else: UpperCAmelCase = get_black_and_white_rgb(lowercase_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure snake_case_ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
78
0
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, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class a ( UpperCAmelCase ): _lowercase = 4_2 class a ( UpperCAmelCase , UpperCAmelCase ): @register_to_config def __init__( self , A_ = 3 , A_ = 3 , A_ = ("DownEncoderBlock2D",) , A_ = ("UpDecoderBlock2D",) , A_ = (64,) , A_ = 1 , A_ = "silu" , A_ = 3 , A_ = 32 , A_ = 256 , A_ = 32 , A_ = None , A_ = 0.1_82_15 , A_ = "group" , ): '''simple docstring''' super().__init__() # pass init params to Encoder _UpperCAmelCase : Optional[Any] = Encoder( in_channels=A_ , out_channels=A_ , down_block_types=A_ , block_out_channels=A_ , layers_per_block=A_ , act_fn=A_ , norm_num_groups=A_ , double_z=A_ , ) _UpperCAmelCase : Union[str, Any] = vq_embed_dim if vq_embed_dim is not None else latent_channels _UpperCAmelCase : Optional[Any] = nn.Convad(A_ , A_ , 1 ) _UpperCAmelCase : Any = VectorQuantizer(A_ , A_ , beta=0.25 , remap=A_ , sane_index_shape=A_ ) _UpperCAmelCase : Any = nn.Convad(A_ , A_ , 1 ) # pass init params to Decoder _UpperCAmelCase : Tuple = Decoder( in_channels=A_ , out_channels=A_ , up_block_types=A_ , block_out_channels=A_ , layers_per_block=A_ , act_fn=A_ , norm_num_groups=A_ , norm_type=A_ , ) @apply_forward_hook def _UpperCAmelCase ( self , A_ , A_ = True ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] = self.encoder(A_ ) _UpperCAmelCase : List[str] = self.quant_conv(A_ ) if not return_dict: return (h,) return VQEncoderOutput(latents=A_ ) @apply_forward_hook def _UpperCAmelCase ( self , A_ , A_ = False , A_ = True ): '''simple docstring''' if not force_not_quantize: _UpperCAmelCase : Optional[int] = self.quantize(A_ ) else: _UpperCAmelCase : List[str] = h _UpperCAmelCase : List[Any] = self.post_quant_conv(A_ ) _UpperCAmelCase : Optional[int] = self.decoder(A_ , quant if self.config.norm_type == "spatial" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=A_ ) def _UpperCAmelCase ( self , A_ , A_ = True ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] = sample _UpperCAmelCase : Any = self.encode(A_ ).latents _UpperCAmelCase : Optional[int] = self.decode(A_ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=A_ )
354
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str , lowerCAmelCase: str ) -> bool: _UpperCAmelCase : Optional[Any] = len(lowerCAmelCase ) + 1 _UpperCAmelCase : Optional[int] = len(lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. _UpperCAmelCase : List[str] = [[0 for i in range(lowerCAmelCase )] for j in range(lowerCAmelCase )] # since string of zero length match pattern of zero length _UpperCAmelCase : List[Any] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , lowerCAmelCase ): _UpperCAmelCase : Dict = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , lowerCAmelCase ): _UpperCAmelCase : Tuple = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , lowerCAmelCase ): for j in range(1 , lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": _UpperCAmelCase : Optional[Any] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: _UpperCAmelCase : List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): _UpperCAmelCase : str = dp[i - 1][j] else: _UpperCAmelCase : int = 0 else: _UpperCAmelCase : List[Any] = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") SCREAMING_SNAKE_CASE_ = 'aab' SCREAMING_SNAKE_CASE_ = 'c*a*b' # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(F'''{input_string} matches the given pattern {pattern}''') else: print(F'''{input_string} does not match with the given pattern {pattern}''')
189
0
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __SCREAMING_SNAKE_CASE ( lowercase_ ): A : Union[str, Any] = 'Speech2TextFeatureExtractor' A : Dict = 'Speech2TextTokenizer' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): super().__init__(__UpperCamelCase , __UpperCamelCase ) lowercase : List[Any] = self.feature_extractor lowercase : Optional[Any] = False def __call__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): if self._in_target_context_manager: return self.current_processor(*__UpperCamelCase , **__UpperCamelCase ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) lowercase : List[str] = kwargs.pop('''raw_speech''' ) else: lowercase : str = kwargs.pop('''audio''' , __UpperCamelCase ) lowercase : List[Any] = kwargs.pop('''sampling_rate''' , __UpperCamelCase ) lowercase : Optional[int] = kwargs.pop('''text''' , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: lowercase : int = args[0] lowercase : Any = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: lowercase : Tuple = self.feature_extractor(__UpperCamelCase , *__UpperCamelCase , sampling_rate=__UpperCamelCase , **__UpperCamelCase ) if text is not None: lowercase : Tuple = self.tokenizer(__UpperCamelCase , **__UpperCamelCase ) if text is None: return inputs elif audio is None: return encodings else: lowercase : Dict = encodings['input_ids'] return inputs def __lowerCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): return self.tokenizer.batch_decode(*__UpperCamelCase , **__UpperCamelCase ) def __lowerCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): return self.tokenizer.decode(*__UpperCamelCase , **__UpperCamelCase ) @contextmanager def __lowerCamelCase ( self ): warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) lowercase : Optional[Any] = True lowercase : Any = self.tokenizer yield lowercase : Optional[int] = self.feature_extractor lowercase : Any = False
337
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class UpperCamelCase ( unittest.TestCase ): def __init__( self ,__UpperCamelCase ,__UpperCamelCase=13 ,__UpperCamelCase=30 ,__UpperCamelCase=2 ,__UpperCamelCase=3 ,__UpperCamelCase=True ,__UpperCamelCase=True ,__UpperCamelCase=32 ,__UpperCamelCase=5 ,__UpperCamelCase=4 ,__UpperCamelCase=37 ,__UpperCamelCase="gelu" ,__UpperCamelCase=0.1 ,__UpperCamelCase=0.1 ,__UpperCamelCase=10 ,__UpperCamelCase=0.02 ,) -> Tuple: '''simple docstring''' lowercase_ : Tuple = parent lowercase_ : Union[str, Any] = batch_size lowercase_ : int = image_size lowercase_ : Tuple = patch_size lowercase_ : Optional[int] = num_channels lowercase_ : Union[str, Any] = is_training lowercase_ : Dict = use_labels lowercase_ : Optional[int] = hidden_size lowercase_ : List[str] = num_hidden_layers lowercase_ : Optional[Any] = num_attention_heads lowercase_ : Optional[int] = intermediate_size lowercase_ : Tuple = hidden_act lowercase_ : int = hidden_dropout_prob lowercase_ : str = attention_probs_dropout_prob lowercase_ : str = type_sequence_label_size lowercase_ : Optional[int] = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowercase_ : str = (image_size // patch_size) ** 2 lowercase_ : Optional[int] = num_patches + 1 def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' lowercase_ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase_ : List[Any] = ViTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=__UpperCamelCase ,initializer_range=self.initializer_range ,) return config, pixel_values def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Dict: '''simple docstring''' lowercase_ : List[Any] = FlaxViTModel(config=__UpperCamelCase ) lowercase_ : Dict = model(__UpperCamelCase ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) lowercase_ : Union[str, Any] = (self.image_size, self.image_size) lowercase_ : List[Any] = (self.patch_size, self.patch_size) lowercase_ : List[str] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, num_patches + 1, self.hidden_size) ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]: '''simple docstring''' lowercase_ : List[Any] = self.type_sequence_label_size lowercase_ : str = FlaxViTForImageClassification(config=__UpperCamelCase ) lowercase_ : Optional[Any] = model(__UpperCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowercase_ : Union[str, Any] = 1 lowercase_ : Optional[int] = FlaxViTForImageClassification(__UpperCamelCase ) lowercase_ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase_ : str = model(__UpperCamelCase ) def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' lowercase_ : Optional[int] = self.prepare_config_and_inputs() ( ( lowercase_ ) , ( lowercase_ ) , ) : List[Any] = config_and_inputs lowercase_ : Tuple = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class UpperCamelCase ( lowercase_ , unittest.TestCase ): lowercase = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def _UpperCAmelCase ( self ) -> None: '''simple docstring''' lowercase_ : Optional[Any] = FlaxViTModelTester(self ) lowercase_ : Union[str, Any] = ConfigTester(self ,config_class=__UpperCamelCase ,has_text_modality=__UpperCamelCase ,hidden_size=37 ) def _UpperCAmelCase ( self ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase ) def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase ) def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ , lowercase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ : Optional[Any] = model_class(__UpperCamelCase ) lowercase_ : Tuple = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase_ : Union[str, Any] = [*signature.parameters.keys()] lowercase_ : str = ['pixel_values'] self.assertListEqual(arg_names[:1] ,__UpperCamelCase ) def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ , lowercase_ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase_ : Optional[Any] = self._prepare_for_class(__UpperCamelCase ,__UpperCamelCase ) lowercase_ : Dict = model_class(__UpperCamelCase ) @jax.jit def model_jitted(__UpperCamelCase ,**__UpperCamelCase ): return model(pixel_values=__UpperCamelCase ,**__UpperCamelCase ) with self.subTest('JIT Enabled' ): lowercase_ : Optional[int] = model_jitted(**__UpperCamelCase ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): lowercase_ : List[str] = model_jitted(**__UpperCamelCase ).to_tuple() self.assertEqual(len(__UpperCamelCase ) ,len(__UpperCamelCase ) ) for jitted_output, output in zip(__UpperCamelCase ,__UpperCamelCase ): self.assertEqual(jitted_output.shape ,output.shape ) @slow def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' for model_class_name in self.all_model_classes: lowercase_ : Optional[int] = model_class_name.from_pretrained('google/vit-base-patch16-224' ) lowercase_ : int = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(__UpperCamelCase )
213
0
'''simple docstring''' def _UpperCamelCase ( UpperCamelCase__ = 1 , UpperCamelCase__ = 1_0_0_0 ) -> Optional[Any]: UpperCAmelCase__ : List[Any] = 1 UpperCAmelCase__ : Optional[Any] = 0 for divide_by_number in range(UpperCamelCase__ , digit + 1 ): UpperCAmelCase__ : list[int] = [] UpperCAmelCase__ : Union[str, Any] = numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(UpperCamelCase__ ): UpperCAmelCase__ : int = len(UpperCamelCase__ ) UpperCAmelCase__ : List[str] = divide_by_number else: has_been_divided.append(UpperCamelCase__ ) UpperCAmelCase__ : Optional[int] = now_divide * 1_0 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
357
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _snake_case ( a__ ): lowerCAmelCase :Optional[int] = ['''image_processor''', '''tokenizer'''] lowerCAmelCase :Optional[int] = '''BridgeTowerImageProcessor''' lowerCAmelCase :List[str] = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , _lowerCamelCase , _lowerCamelCase): super().__init__(_lowerCamelCase , _lowerCamelCase) def __call__( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = 0 , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = None , **_lowerCamelCase , ): UpperCAmelCase__ : List[str] = self.tokenizer( text=_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , stride=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_overflowing_tokens=_lowerCamelCase , return_special_tokens_mask=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , return_length=_lowerCamelCase , verbose=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase , ) # add pixel_values + pixel_mask UpperCAmelCase__ : Optional[Any] = self.image_processor( _lowerCamelCase , return_tensors=_lowerCamelCase , do_normalize=_lowerCamelCase , do_center_crop=_lowerCamelCase , **_lowerCamelCase) encoding.update(_lowerCamelCase) return encoding def snake_case__ ( self , *_lowerCamelCase , **_lowerCamelCase): return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase) def snake_case__ ( self , *_lowerCamelCase , **_lowerCamelCase): return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase) @property def snake_case__ ( self): UpperCAmelCase__ : Optional[int] = self.tokenizer.model_input_names UpperCAmelCase__ : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
283
0
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup __snake_case = logging.get_logger(__name__) class lowercase__ ( _UpperCAmelCase ): def __init__( self : Optional[int] , **UpperCAmelCase_ : Tuple ): requires_backends(self , ['bs4'] ) super().__init__(**UpperCAmelCase_ ) def A_ ( self : Union[str, Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag SCREAMING_SNAKE_CASE__ = parent.find_all(child.name , recursive=UpperCAmelCase_ ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(UpperCAmelCase_ ) else next(i for i, s in enumerate(UpperCAmelCase_ , 1 ) if s is child ) ) SCREAMING_SNAKE_CASE__ = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def A_ ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE__ = BeautifulSoup(UpperCAmelCase_ , 'html.parser' ) SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for element in html_code.descendants: if type(UpperCAmelCase_ ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue SCREAMING_SNAKE_CASE__ = html.unescape(UpperCAmelCase_ ).strip() if not text_in_this_tag: continue all_doc_strings.append(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.xpath_soup(UpperCAmelCase_ ) stringaxtag_seq.append(UpperCAmelCase_ ) stringaxsubs_seq.append(UpperCAmelCase_ ) if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError('Number of doc strings and xtags does not correspond' ) if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError('Number of doc strings and xsubs does not correspond' ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def A_ ( self : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE__ = '' for tagname, subs in zip(UpperCAmelCase_ , UpperCAmelCase_ ): xpath += F'/{tagname}' if subs != 0: xpath += F'[{subs}]' return xpath def __call__( self : Union[str, Any] , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE__ = False # Check that strings has a valid type if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE__ = True elif isinstance(UpperCAmelCase_ , (list, tuple) ): if len(UpperCAmelCase_ ) == 0 or isinstance(html_strings[0] , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE__ = True if not valid_strings: raise ValueError( 'HTML strings must of type `str`, `List[str]` (batch of examples), ' F'but is of type {type(UpperCAmelCase_ )}.' ) SCREAMING_SNAKE_CASE__ = bool(isinstance(UpperCAmelCase_ , (list, tuple) ) and (isinstance(html_strings[0] , UpperCAmelCase_ )) ) if not is_batched: SCREAMING_SNAKE_CASE__ = [html_strings] # Get nodes + xpaths SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for html_string in html_strings: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.get_three_from_single(UpperCAmelCase_ ) nodes.append(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = [] for node, tag_list, sub_list in zip(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE__ = self.construct_xpath(UpperCAmelCase_ , UpperCAmelCase_ ) xpath_strings.append(UpperCAmelCase_ ) xpaths.append(UpperCAmelCase_ ) # return as Dict SCREAMING_SNAKE_CASE__ = {'nodes': nodes, 'xpaths': xpaths} SCREAMING_SNAKE_CASE__ = BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) return encoded_inputs
176
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __snake_case = logging.get_logger(__name__) __snake_case = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class lowercase__ ( _UpperCAmelCase ): def __init__( self : str , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[str]=None , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[Any] ): super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) if config is None: assert isinstance(self.model , UpperCAmelCase_ ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F' {self.model.__class__}' ) SCREAMING_SNAKE_CASE__ = self.model.config else: SCREAMING_SNAKE_CASE__ = config SCREAMING_SNAKE_CASE__ = data_args SCREAMING_SNAKE_CASE__ = self.config.tgt_vocab_size if isinstance(self.config , UpperCAmelCase_ ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F'The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for' ' padding..' ) if self.args.label_smoothing == 0: SCREAMING_SNAKE_CASE__ = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss SCREAMING_SNAKE_CASE__ = label_smoothed_nll_loss def A_ ( self : Tuple , UpperCAmelCase_ : int ): if self.optimizer is None: SCREAMING_SNAKE_CASE__ = ['bias', 'LayerNorm.weight'] SCREAMING_SNAKE_CASE__ = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] SCREAMING_SNAKE_CASE__ = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: SCREAMING_SNAKE_CASE__ = Adafactor SCREAMING_SNAKE_CASE__ = {'scale_parameter': False, 'relative_step': False} else: SCREAMING_SNAKE_CASE__ = AdamW SCREAMING_SNAKE_CASE__ = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } SCREAMING_SNAKE_CASE__ = self.args.learning_rate if self.sharded_ddp: SCREAMING_SNAKE_CASE__ = OSS( params=UpperCAmelCase_ , optim=UpperCAmelCase_ , **UpperCAmelCase_ , ) else: SCREAMING_SNAKE_CASE__ = optimizer_cls(UpperCAmelCase_ , **UpperCAmelCase_ ) if self.lr_scheduler is None: SCREAMING_SNAKE_CASE__ = self._get_lr_scheduler(UpperCAmelCase_ ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def A_ ( self : str , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE__ = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": SCREAMING_SNAKE_CASE__ = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": SCREAMING_SNAKE_CASE__ = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: SCREAMING_SNAKE_CASE__ = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=UpperCAmelCase_ ) return scheduler def A_ ( self : List[str] ): if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def A_ ( self : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict ): if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token SCREAMING_SNAKE_CASE__ = model(**UpperCAmelCase_ , use_cache=UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE__ = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model(**UpperCAmelCase_ , labels=UpperCAmelCase_ , use_cache=UpperCAmelCase_ )[:2] else: # compute label smoothed loss SCREAMING_SNAKE_CASE__ = model(**UpperCAmelCase_ , use_cache=UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE__ = torch.nn.functional.log_softmax(UpperCAmelCase_ , dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.loss_fn(UpperCAmelCase_ , UpperCAmelCase_ , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def A_ ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE__ = inputs.pop('labels' ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self._compute_loss(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return loss def A_ ( self : List[str] , UpperCAmelCase_ : nn.Module , UpperCAmelCase_ : Dict[str, Union[torch.Tensor, Any]] , UpperCAmelCase_ : bool , UpperCAmelCase_ : Optional[List[str]] = None , ): SCREAMING_SNAKE_CASE__ = self._prepare_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: SCREAMING_SNAKE_CASE__ = self.model.generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , **UpperCAmelCase_ , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: SCREAMING_SNAKE_CASE__ = self._pad_tensors_to_max_len(UpperCAmelCase_ , gen_kwargs['max_length'] ) SCREAMING_SNAKE_CASE__ = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self._compute_loss(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) SCREAMING_SNAKE_CASE__ = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: SCREAMING_SNAKE_CASE__ = self._pad_tensors_to_max_len(UpperCAmelCase_ , gen_kwargs['max_length'] ) return (loss, logits, labels) def A_ ( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] ): # If PAD token is not defined at least EOS token has to be defined SCREAMING_SNAKE_CASE__ = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F' padded to `max_length`={max_length}' ) SCREAMING_SNAKE_CASE__ = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) SCREAMING_SNAKE_CASE__ = tensor return padded_tensor
176
1
def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if exponent == 1: return base if exponent % 2 == 0: SCREAMING_SNAKE_CASE_ = _modexpt(__lowerCamelCase, exponent // 2, __lowerCamelCase ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(__lowerCamelCase, exponent - 1, __lowerCamelCase )) % modulo_value def A__ ( __lowerCamelCase = 17_77, __lowerCamelCase = 18_55, __lowerCamelCase = 8 ): SCREAMING_SNAKE_CASE_ = base for _ in range(1, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = _modexpt(__lowerCamelCase, __lowerCamelCase, 10**digits ) return result if __name__ == "__main__": print(F"""{solution() = }""")
360
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if not arr: return None, None, 0 if low == high: return low, high, arr[low] SCREAMING_SNAKE_CASE_ = (low + high) // 2 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = max_subarray(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = max_subarray(__lowerCamelCase, mid + 1, __lowerCamelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = max_cross_sum(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = float('''-inf''' ), -1 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = float('''-inf''' ), -1 SCREAMING_SNAKE_CASE_ = 0 for i in range(__lowerCamelCase, low - 1, -1 ): summ += arr[i] if summ > left_sum: SCREAMING_SNAKE_CASE_ = summ SCREAMING_SNAKE_CASE_ = i SCREAMING_SNAKE_CASE_ = 0 for i in range(mid + 1, high + 1 ): summ += arr[i] if summ > right_sum: SCREAMING_SNAKE_CASE_ = summ SCREAMING_SNAKE_CASE_ = i return max_left, max_right, (left_sum + right_sum) def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [randint(1, __lowerCamelCase ) for _ in range(__lowerCamelCase )] SCREAMING_SNAKE_CASE_ = time.time() max_subarray(__lowerCamelCase, 0, input_size - 1 ) SCREAMING_SNAKE_CASE_ = time.time() return end - start def A__ ( ): SCREAMING_SNAKE_CASE_ = [10, 1_00, 10_00, 1_00_00, 5_00_00, 10_00_00, 20_00_00, 30_00_00, 40_00_00, 50_00_00] SCREAMING_SNAKE_CASE_ = [time_max_subarray(__lowerCamelCase ) for input_size in input_sizes] print('''No of Inputs\t\tTime Taken''' ) for input_size, runtime in zip(__lowerCamelCase, __lowerCamelCase ): print(__lowerCamelCase, '''\t\t''', __lowerCamelCase ) plt.plot(__lowerCamelCase, __lowerCamelCase ) plt.xlabel('''Number of Inputs''' ) plt.ylabel('''Time taken in seconds''' ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
257
0
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class lowerCamelCase__( __lowerCamelCase , unittest.TestCase): UpperCAmelCase__ : Union[str, Any] = RoFormerTokenizer UpperCAmelCase__ : Dict = RoFormerTokenizerFast UpperCAmelCase__ : Union[str, Any] = True UpperCAmelCase__ : Tuple = True def lowerCAmelCase__ ( self: str ): super().setUp() def lowerCAmelCase__ ( self: Optional[int] , **UpperCamelCase_: List[str] ): return self.tokenizer_class.from_pretrained("""junnyu/roformer_chinese_base""" , **UpperCamelCase_ ) def lowerCAmelCase__ ( self: Dict , **UpperCamelCase_: str ): return self.rust_tokenizer_class.from_pretrained("""junnyu/roformer_chinese_base""" , **UpperCamelCase_ ) def lowerCAmelCase__ ( self: List[Any] ): __lowerCamelCase = """永和服装饰品有限公司,今天天气非常好""" __lowerCamelCase = """永和 服装 饰品 有限公司 , 今 天 天 气 非常 好""" return input_text, output_text def lowerCAmelCase__ ( self: Optional[Any] ): __lowerCamelCase = self.get_tokenizer() __lowerCamelCase, __lowerCamelCase = self.get_chinese_input_output_texts() __lowerCamelCase = tokenizer.tokenize(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , output_text.split() ) __lowerCamelCase = tokens + [tokenizer.unk_token] __lowerCamelCase = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , UpperCamelCase_ ) def lowerCAmelCase__ ( self: Optional[Any] ): __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase, __lowerCamelCase = self.get_chinese_input_output_texts() __lowerCamelCase = tokenizer.tokenize(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , output_text.split() ) __lowerCamelCase = tokens + [tokenizer.unk_token] __lowerCamelCase = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , UpperCamelCase_ ) def lowerCAmelCase__ ( self: Any ): pass def lowerCAmelCase__ ( self: Union[str, Any] ): pass def lowerCAmelCase__ ( self: Any ): pass
12
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig UpperCAmelCase_ = logging.get_logger(__name__) class lowerCamelCase__: def __init__( self: Any , UpperCamelCase_: str , UpperCamelCase_: Dict ): __lowerCamelCase = question_encoder __lowerCamelCase = generator __lowerCamelCase = self.question_encoder def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: Optional[Any] ): if os.path.isfile(UpperCamelCase_ ): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) __lowerCamelCase = os.path.join(UpperCamelCase_ , """question_encoder_tokenizer""" ) __lowerCamelCase = os.path.join(UpperCamelCase_ , """generator_tokenizer""" ) self.question_encoder.save_pretrained(UpperCamelCase_ ) self.generator.save_pretrained(UpperCamelCase_ ) @classmethod def lowerCAmelCase__ ( cls: List[Any] , UpperCamelCase_: Dict , **UpperCamelCase_: Union[str, Any] ): # dynamically import AutoTokenizer from ..auto.tokenization_auto import AutoTokenizer __lowerCamelCase = kwargs.pop("""config""" , UpperCamelCase_ ) if config is None: __lowerCamelCase = RagConfig.from_pretrained(UpperCamelCase_ ) __lowerCamelCase = AutoTokenizer.from_pretrained( UpperCamelCase_ , config=config.question_encoder , subfolder="""question_encoder_tokenizer""" ) __lowerCamelCase = AutoTokenizer.from_pretrained( UpperCamelCase_ , config=config.generator , subfolder="""generator_tokenizer""" ) return cls(question_encoder=UpperCamelCase_ , generator=UpperCamelCase_ ) def __call__( self: Tuple , *UpperCamelCase_: int , **UpperCamelCase_: int ): return self.current_tokenizer(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self: Tuple , *UpperCamelCase_: List[Any] , **UpperCamelCase_: List[Any] ): return self.generator.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self: Optional[Any] , *UpperCamelCase_: str , **UpperCamelCase_: Union[str, Any] ): return self.generator.decode(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self: str ): __lowerCamelCase = self.question_encoder def lowerCAmelCase__ ( self: Optional[int] ): __lowerCamelCase = self.generator def lowerCAmelCase__ ( self: Tuple , UpperCamelCase_: List[str] , UpperCamelCase_: Optional[List[str]] = None , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: str = "longest" , UpperCamelCase_: str = None , UpperCamelCase_: bool = True , **UpperCamelCase_: int , ): warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , UpperCamelCase_ , ) if max_length is None: __lowerCamelCase = self.current_tokenizer.model_max_length __lowerCamelCase = self( UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , return_tensors=UpperCamelCase_ , max_length=UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , **UpperCamelCase_ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: __lowerCamelCase = self.current_tokenizer.model_max_length __lowerCamelCase = self( text_target=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , return_tensors=UpperCamelCase_ , padding=UpperCamelCase_ , max_length=UpperCamelCase_ , truncation=UpperCamelCase_ , **UpperCamelCase_ , ) __lowerCamelCase = labels["""input_ids"""] return model_inputs
12
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { 'microsoft/swin-tiny-patch4-window7-224': ( 'https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json' ), # See all Swin models at https://huggingface.co/models?filter=swin } class A ( UpperCAmelCase_ , UpperCAmelCase_ ): __UpperCAmelCase : int = 'swin' __UpperCAmelCase : str = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__(self : Dict , __UpperCAmelCase : Dict=2_2_4 , __UpperCAmelCase : Tuple=4 , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : str=9_6 , __UpperCAmelCase : Union[str, Any]=[2, 2, 6, 2] , __UpperCAmelCase : int=[3, 6, 1_2, 2_4] , __UpperCAmelCase : Tuple=7 , __UpperCAmelCase : Tuple=4.0 , __UpperCAmelCase : Dict=True , __UpperCAmelCase : List[str]=0.0 , __UpperCAmelCase : Union[str, Any]=0.0 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : List[Any]="gelu" , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : List[Any]=0.02 , __UpperCAmelCase : Any=1E-5 , __UpperCAmelCase : str=3_2 , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Any=None , **__UpperCAmelCase : Any , ) -> Optional[Any]: """simple docstring""" super().__init__(**__UpperCAmelCase ) UpperCAmelCase__ = image_size UpperCAmelCase__ = patch_size UpperCAmelCase__ = num_channels UpperCAmelCase__ = embed_dim UpperCAmelCase__ = depths UpperCAmelCase__ = len(__UpperCAmelCase ) UpperCAmelCase__ = num_heads UpperCAmelCase__ = window_size UpperCAmelCase__ = mlp_ratio UpperCAmelCase__ = qkv_bias UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = drop_path_rate UpperCAmelCase__ = hidden_act UpperCAmelCase__ = use_absolute_embeddings UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = initializer_range UpperCAmelCase__ = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model UpperCAmelCase__ = int(embed_dim * 2 ** (len(__UpperCAmelCase ) - 1) ) UpperCAmelCase__ = ["stem"] + [f"""stage{idx}""" for idx in range(1 , len(__UpperCAmelCase ) + 1 )] UpperCAmelCase__ , UpperCAmelCase__ = get_aligned_output_features_output_indices( out_features=__UpperCAmelCase , out_indices=__UpperCAmelCase , stage_names=self.stage_names ) class A ( UpperCAmelCase_ ): __UpperCAmelCase : List[str] = version.parse('1.11' ) @property def lowercase_ (self : str ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def lowercase_ (self : str ) -> float: """simple docstring""" return 1E-4
143
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer UpperCamelCase__ = logging.getLogger(__name__) def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name", type=__A, default="wikitext", help="Name of the training. Explore datasets at: hf.co/datasets.", ) parser.add_argument( "--dataset_config", type=__A, default="wikitext-103-raw-v1", help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path", type=__A, default="sayakpaul/unigram-tokenizer-wikitext", help="Tokenizer identifier. Can be a local filepath or a Hub identifier.", ) parser.add_argument( "--shard_size", type=__A, default=1_000, help="Number of entries to go in a single shard.", ) parser.add_argument("--split", type=__A, default="train", choices=["train", "test", "validation"] ) parser.add_argument( "--limit", default=__A, type=__A, help="Limit the number of shards (used for debugging).", ) parser.add_argument( "--max_length", type=__A, default=512, help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8.", ) parser.add_argument( "--output_dir", default="tf-tpu", type=__A, help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket.", ) UpperCAmelCase__ = parser.parse_args() return args def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' def fn(__A ): return tokenizer(examples["text"] ) return fn def lowerCAmelCase_ ( __A ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ = [] for i in range(len(tokenized_data["input_ids"] ) ): UpperCAmelCase__ = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } UpperCAmelCase__ = tf.train.Features(feature=__A ) UpperCAmelCase__ = tf.train.Example(features=__A ) UpperCAmelCase__ = example.SerializeToString() records.append(__A ) return records def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = datasets.load_dataset(args.dataset_name, args.dataset_config, split=args.split ) if args.limit is not None: UpperCAmelCase__ = min(len(__A ), args.limit ) UpperCAmelCase__ = dataset.select(range(__A ) ) print(f"""Limiting the dataset to {args.limit} entries.""" ) UpperCAmelCase__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) UpperCAmelCase__ = os.path.join(args.output_dir, args.split ) if not os.path.exists(__A ): os.makedirs(__A ) else: UpperCAmelCase__ = os.path.join(args.output_dir, args.split ) # Tokenize the whole dataset at once. UpperCAmelCase__ = tokenize_function(__A ) UpperCAmelCase__ = dataset.map(__A, batched=__A, num_proc=4, remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__A ): # Concatenate all texts. UpperCAmelCase__ = {k: sum(examples[k], [] ) for k in examples.keys()} UpperCAmelCase__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 UpperCAmelCase__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. UpperCAmelCase__ = { k: [t[i : i + args.max_length] for i in range(0, __A, args.max_length )] for k, t in concatenated_examples.items() } return result UpperCAmelCase__ = dataset_tokenized.map(__A, batched=__A, batch_size=1_000, num_proc=4 ) UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 for shard in range(0, len(__A ), args.shard_size ): UpperCAmelCase__ = grouped_dataset[shard : shard + args.shard_size] UpperCAmelCase__ = len(dataset_snapshot["input_ids"] ) UpperCAmelCase__ = os.path.join(__A, f"""dataset-{shard_count}-{records_containing}.tfrecord""" ) UpperCAmelCase__ = get_serialized_examples(__A ) with tf.io.TFRecordWriter(__A ) as out_file: for i in range(len(__A ) ): UpperCAmelCase__ = serialized_examples[i] out_file.write(__A ) print("Wrote file {} containing {} records".format(__A, __A ) ) shard_count += 1 total_records += records_containing with open(f"""split-{args.split}-records-count.txt""", "w" ) as f: print(f"""Total {args.split} records: {total_records}""", file=__A ) if __name__ == "__main__": UpperCamelCase__ = parse_args() main(args)
143
1
"""simple docstring""" import os import sys import unittest lowerCAmelCase__ : Tuple = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) lowerCAmelCase__ : Tuple = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') lowerCAmelCase__ : Optional[Any] = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class snake_case ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : List[str] ): UpperCAmelCase__ = get_test_to_tester_mapping(lowerCamelCase__ ) UpperCAmelCase__ = get_test_to_tester_mapping(lowerCamelCase__ ) UpperCAmelCase__ = {'BertModelTest': 'BertModelTester'} UpperCAmelCase__ = { 'BlipModelTest': 'BlipModelTester', 'BlipTextImageModelTest': 'BlipTextImageModelsModelTester', 'BlipTextModelTest': 'BlipTextModelTester', 'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester', 'BlipVQAModelTest': 'BlipVQAModelTester', 'BlipVisionModelTest': 'BlipVisionModelTester', } self.assertEqual(get_test_info.to_json(lowerCamelCase__ ) ,lowerCamelCase__ ) self.assertEqual(get_test_info.to_json(lowerCamelCase__ ) ,lowerCamelCase__ ) def __lowerCAmelCase ( self : Optional[Any] ): UpperCAmelCase__ = get_model_to_test_mapping(lowerCamelCase__ ) UpperCAmelCase__ = get_model_to_test_mapping(lowerCamelCase__ ) UpperCAmelCase__ = { 'BertForMaskedLM': ['BertModelTest'], 'BertForMultipleChoice': ['BertModelTest'], 'BertForNextSentencePrediction': ['BertModelTest'], 'BertForPreTraining': ['BertModelTest'], 'BertForQuestionAnswering': ['BertModelTest'], 'BertForSequenceClassification': ['BertModelTest'], 'BertForTokenClassification': ['BertModelTest'], 'BertLMHeadModel': ['BertModelTest'], 'BertModel': ['BertModelTest'], } UpperCAmelCase__ = { 'BlipForConditionalGeneration': ['BlipTextImageModelTest'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'], 'BlipForQuestionAnswering': ['BlipVQAModelTest'], 'BlipModel': ['BlipModelTest'], 'BlipTextModel': ['BlipTextModelTest'], 'BlipVisionModel': ['BlipVisionModelTest'], } self.assertEqual(get_test_info.to_json(lowerCamelCase__ ) ,lowerCamelCase__ ) self.assertEqual(get_test_info.to_json(lowerCamelCase__ ) ,lowerCamelCase__ ) def __lowerCAmelCase ( self : int ): UpperCAmelCase__ = get_model_to_tester_mapping(lowerCamelCase__ ) UpperCAmelCase__ = get_model_to_tester_mapping(lowerCamelCase__ ) UpperCAmelCase__ = { 'BertForMaskedLM': ['BertModelTester'], 'BertForMultipleChoice': ['BertModelTester'], 'BertForNextSentencePrediction': ['BertModelTester'], 'BertForPreTraining': ['BertModelTester'], 'BertForQuestionAnswering': ['BertModelTester'], 'BertForSequenceClassification': ['BertModelTester'], 'BertForTokenClassification': ['BertModelTester'], 'BertLMHeadModel': ['BertModelTester'], 'BertModel': ['BertModelTester'], } UpperCAmelCase__ = { 'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'], 'BlipForQuestionAnswering': ['BlipVQAModelTester'], 'BlipModel': ['BlipModelTester'], 'BlipTextModel': ['BlipTextModelTester'], 'BlipVisionModel': ['BlipVisionModelTester'], } self.assertEqual(get_test_info.to_json(lowerCamelCase__ ) ,lowerCamelCase__ ) self.assertEqual(get_test_info.to_json(lowerCamelCase__ ) ,lowerCamelCase__ )
98
"""simple docstring""" def a_ ( lowerCamelCase ): return str(lowerCamelCase ) == str(lowerCamelCase )[::-1] def a_ ( lowerCamelCase ): return int(lowerCamelCase ) + int(str(lowerCamelCase )[::-1] ) def a_ ( lowerCamelCase = 1_0_0_0_0 ): UpperCAmelCase__ = [] for num in range(1 , lowerCamelCase ): UpperCAmelCase__ = 0 UpperCAmelCase__ = num while iterations < 5_0: UpperCAmelCase__ = sum_reverse(lowerCamelCase ) iterations += 1 if is_palindrome(lowerCamelCase ): break else: lychrel_nums.append(lowerCamelCase ) return len(lowerCamelCase ) if __name__ == "__main__": print(F"""{solution() = }""")
98
1
"""simple docstring""" from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def a ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase : List[Any] = analyze_text(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = list(''' ''' + ascii_lowercase ) # what is our total sum of probabilities. UpperCamelCase : str = sum(single_char_strings.values() ) # one length string UpperCamelCase : str = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: UpperCamelCase : Dict = single_char_strings[ch] UpperCamelCase : str = my_str / all_sum my_fir_sum += prob * math.loga(SCREAMING_SNAKE_CASE_ ) # entropy formula. # print entropy print(F"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string UpperCamelCase : Tuple = sum(two_char_strings.values() ) UpperCamelCase : Any = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: UpperCamelCase : List[Any] = cha + cha if sequence in two_char_strings: UpperCamelCase : Optional[Any] = two_char_strings[sequence] UpperCamelCase : Any = int(SCREAMING_SNAKE_CASE_ ) / all_sum my_sec_sum += prob * math.loga(SCREAMING_SNAKE_CASE_ ) # print second entropy print(F"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(F"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def a ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase : Optional[int] = Counter() # type: ignore UpperCamelCase : List[str] = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def a ( ): """simple docstring""" import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
370
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase : Union[str, Any] = { "configuration_mgp_str": ["MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP", "MgpstrConfig"], "processing_mgp_str": ["MgpstrProcessor"], "tokenization_mgp_str": ["MgpstrTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase : Union[str, Any] = [ "MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST", "MgpstrModel", "MgpstrPreTrainedModel", "MgpstrForSceneTextRecognition", ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys __UpperCAmelCase : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
315
0
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if exponent == 1: return base if exponent % 2 == 0: snake_case_ = _modexpt(SCREAMING_SNAKE_CASE__ , exponent // 2 , SCREAMING_SNAKE_CASE__ ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(SCREAMING_SNAKE_CASE__ , exponent - 1 , SCREAMING_SNAKE_CASE__ )) % modulo_value def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ = 1777 , SCREAMING_SNAKE_CASE__ = 1855 , SCREAMING_SNAKE_CASE__ = 8 ): snake_case_ = base for _ in range(1 , SCREAMING_SNAKE_CASE__ ): snake_case_ = _modexpt(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 10**digits ) return result if __name__ == "__main__": print(f"""{solution() = }""")
8
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( """The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion""" ) __UpperCamelCase : Union[str, Any] = None __UpperCamelCase : Any = { """7B""": 11008, """13B""": 13824, """30B""": 17920, """65B""": 22016, """70B""": 28672, } __UpperCamelCase : Optional[Any] = { """7B""": 1, """7Bf""": 1, """13B""": 2, """13Bf""": 2, """30B""": 4, """65B""": 8, """70B""": 8, """70Bf""": 8, } def a_ ( _A , _A=1 , _A=256 ) -> str: """simple docstring""" return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def a_ ( _A ) -> int: """simple docstring""" with open(_A , 'r' ) as f: return json.load(_A ) def a_ ( _A , _A ) -> int: """simple docstring""" with open(_A , 'w' ) as f: json.dump(_A , _A ) def a_ ( _A , _A , _A , _A=True ) -> List[str]: """simple docstring""" os.makedirs(_A , exist_ok=_A ) snake_case__ = os.path.join(_A , 'tmp' ) os.makedirs(_A , exist_ok=_A ) snake_case__ = read_json(os.path.join(_A , 'params.json' ) ) snake_case__ = NUM_SHARDS[model_size] snake_case__ = params['n_layers'] snake_case__ = params['n_heads'] snake_case__ = n_heads // num_shards snake_case__ = params['dim'] snake_case__ = dim // n_heads snake_case__ = 10000.0 snake_case__ = 1.0 / (base ** (torch.arange(0 , _A , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: snake_case__ = params['n_kv_heads'] # for GQA / MQA snake_case__ = n_heads_per_shard // num_key_value_heads snake_case__ = dim // num_key_value_heads else: # compatibility with other checkpoints snake_case__ = n_heads snake_case__ = n_heads_per_shard snake_case__ = dim # permute for sliced rotary def permute(_A , _A=n_heads , _A=dim , _A=dim ): return w.view(_A , dima // n_heads // 2 , 2 , _A ).transpose(1 , 2 ).reshape(_A , _A ) print(f'''Fetching all parameters from the checkpoint at {input_base_path}.''' ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) snake_case__ = torch.load(os.path.join(_A , 'consolidated.00.pth' ) , map_location='cpu' ) else: # Sharded snake_case__ = [ torch.load(os.path.join(_A , f'''consolidated.{i:02d}.pth''' ) , map_location='cpu' ) for i in range(_A ) ] snake_case__ = 0 snake_case__ = {'weight_map': {}} for layer_i in range(_A ): snake_case__ = f'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded snake_case__ = { f'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wq.weight'''] ), f'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wk.weight'''] ), f'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[f'''layers.{layer_i}.attention.wv.weight'''], f'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[f'''layers.{layer_i}.attention.wo.weight'''], f'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w1.weight'''], f'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w2.weight'''], f'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w3.weight'''], f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[f'''layers.{layer_i}.attention_norm.weight'''], f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[f'''layers.{layer_i}.ffn_norm.weight'''], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. snake_case__ = { f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.attention_norm.weight''' ].clone(), f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.ffn_norm.weight''' ].clone(), } snake_case__ = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wq.weight'''].view(_A , _A , _A ) for i in range(_A ) ] , dim=0 , ).reshape(_A , _A ) ) snake_case__ = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wk.weight'''].view( _A , _A , _A ) for i in range(_A ) ] , dim=0 , ).reshape(_A , _A ) , _A , _A , _A , ) snake_case__ = torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wv.weight'''].view( _A , _A , _A ) for i in range(_A ) ] , dim=0 , ).reshape(_A , _A ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.attention.wo.weight'''] for i in range(_A )] , dim=1 ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(_A )] , dim=0 ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(_A )] , dim=1 ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(_A )] , dim=0 ) snake_case__ = inv_freq for k, v in state_dict.items(): snake_case__ = filename param_count += v.numel() torch.save(_A , os.path.join(_A , _A ) ) snake_case__ = f'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded snake_case__ = { 'model.embed_tokens.weight': loaded['tok_embeddings.weight'], 'model.norm.weight': loaded['norm.weight'], 'lm_head.weight': loaded['output.weight'], } else: snake_case__ = { 'model.norm.weight': loaded[0]['norm.weight'], 'model.embed_tokens.weight': torch.cat( [loaded[i]['tok_embeddings.weight'] for i in range(_A )] , dim=1 ), 'lm_head.weight': torch.cat([loaded[i]['output.weight'] for i in range(_A )] , dim=0 ), } for k, v in state_dict.items(): snake_case__ = filename param_count += v.numel() torch.save(_A , os.path.join(_A , _A ) ) # Write configs snake_case__ = {'total_size': param_count * 2} write_json(_A , os.path.join(_A , 'pytorch_model.bin.index.json' ) ) snake_case__ = params['ffn_dim_multiplier'] if 'ffn_dim_multiplier' in params else 1 snake_case__ = params['multiple_of'] if 'multiple_of' in params else 256 snake_case__ = LlamaConfig( hidden_size=_A , intermediate_size=compute_intermediate_size(_A , _A , _A ) , num_attention_heads=params['n_heads'] , num_hidden_layers=params['n_layers'] , rms_norm_eps=params['norm_eps'] , num_key_value_heads=_A , ) config.save_pretrained(_A ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print('Loading the checkpoint in a Llama model.' ) snake_case__ = LlamaForCausalLM.from_pretrained(_A , torch_dtype=torch.floataa , low_cpu_mem_usage=_A ) # Avoid saving this as part of the config. del model.config._name_or_path print('Saving in the Transformers format.' ) model.save_pretrained(_A , safe_serialization=_A ) shutil.rmtree(_A ) def a_ ( _A , _A ) -> Tuple: """simple docstring""" # Initialize the tokenizer based on the `spm` model snake_case__ = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(f'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.''' ) snake_case__ = tokenizer_class(_A ) tokenizer.save_pretrained(_A ) def a_ ( ) -> str: """simple docstring""" snake_case__ = argparse.ArgumentParser() parser.add_argument( '--input_dir' , help='Location of LLaMA weights, which contains tokenizer.model and model folders' , ) parser.add_argument( '--model_size' , choices=['7B', '7Bf', '13B', '13Bf', '30B', '65B', '70B', '70Bf', 'tokenizer_only'] , ) parser.add_argument( '--output_dir' , help='Location to write HF model and tokenizer' , ) parser.add_argument('--safe_serialization' , type=_A , help='Whether or not to save using `safetensors`.' ) snake_case__ = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) snake_case__ = os.path.join(args.input_dir , 'tokenizer.model' ) write_tokenizer(args.output_dir , _A ) if __name__ == "__main__": main()
307
0
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def snake_case_ (UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray , UpperCamelCase : int , UpperCamelCase : int ): '''simple docstring''' _a = cva.getAffineTransform(UpperCamelCase , UpperCamelCase ) return cva.warpAffine(UpperCamelCase , UpperCamelCase , (rows, cols) ) if __name__ == "__main__": # read original image _snake_case : Optional[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value _snake_case : Union[str, Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape _snake_case , _snake_case : str = gray_img.shape # set different points to rotate image _snake_case : Tuple = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) _snake_case : str = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) _snake_case : Optional[int] = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) _snake_case : int = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list _snake_case : Optional[int] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations _snake_case : Optional[Any] = plt.figure(1) _snake_case : int = ['Original', 'Rotation 1', 'Rotation 2', 'Rotation 3'] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, 'gray') plt.title(titles[i]) plt.axis('off') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
179
'''simple docstring''' import argparse from collections import defaultdict import yaml _snake_case : int = 'docs/source/en/_toctree.yml' def snake_case_ (UpperCamelCase : Optional[int] ): '''simple docstring''' _a = defaultdict(UpperCamelCase ) for doc in model_doc: counts[doc["local"]] += 1 _a = [key for key, value in counts.items() if value > 1] _a = [] for duplicate_key in duplicates: _a = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(UpperCamelCase ) > 1: raise ValueError( f'{duplicate_key} is present several times in the documentation table of content at ' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(UpperCamelCase , key=lambda UpperCamelCase : s["title"].lower() ) def snake_case_ (UpperCamelCase : str=False ): '''simple docstring''' with open(UpperCamelCase , encoding='''utf-8''' ) as f: _a = yaml.safe_load(f.read() ) # Get to the API doc _a = 0 while content[api_idx]["title"] != "API": api_idx += 1 _a = content[api_idx]['''sections'''] # Then to the model doc _a = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 _a = api_doc[model_idx]['''sections'''] _a = [(idx, section) for idx, section in enumerate(UpperCamelCase ) if '''sections''' in section] _a = False for idx, modality_doc in modalities_docs: _a = modality_doc['''sections'''] _a = clean_model_doc_toc(UpperCamelCase ) if old_modality_doc != new_modality_doc: _a = True if overwrite: _a = new_modality_doc if diff: if overwrite: _a = model_doc _a = api_doc with open(UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(UpperCamelCase , allow_unicode=UpperCamelCase ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": _snake_case : List[str] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') _snake_case : List[Any] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
179
1
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : List[str] = MobileBertConfig.from_json_file(_UpperCAmelCase ) print(f"""Building PyTorch model from configuration: {config}""" ) A_ : List[Any] = MobileBertForPreTraining(_UpperCAmelCase ) # Load weights from tf checkpoint A_ : List[str] = load_tf_weights_in_mobilebert(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": lowerCamelCase_ : Optional[Any] = 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( '--mobilebert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained MobileBERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) lowerCamelCase_ : List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
286
"""simple docstring""" def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" if isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('\'float\' object cannot be interpreted as an integer' ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('\'str\' object cannot be interpreted as an integer' ) if num == 0: return "0b0" A_ : str = False if num < 0: A_ : Dict = True A_ : Union[str, Any] = -num A_ : list[int] = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(_UpperCAmelCase ) for e in binary ) return "0b" + "".join(str(_UpperCAmelCase ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
286
1
'''simple docstring''' import unittest import numpy as np def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = None , ): '''simple docstring''' A : List[Any] = np.shape(snake_case__ ) A : Optional[Any] = np.shape(snake_case__ ) A : Any = np.shape(snake_case__ ) if shape_a[0] != shape_b[0]: A : Tuple = ( '''Expected the same number of rows for A and B. ''' F'Instead found A of size {shape_a} and B of size {shape_b}' ) raise ValueError(snake_case__ ) if shape_b[1] != shape_c[1]: A : List[Any] = ( '''Expected the same number of columns for B and C. ''' F'Instead found B of size {shape_b} and C of size {shape_c}' ) raise ValueError(snake_case__ ) A : str = pseudo_inv if a_inv is None: try: A : str = np.linalg.inv(snake_case__ ) except np.linalg.LinAlgError: raise ValueError( '''Input matrix A is not invertible. Cannot compute Schur complement.''' ) return mat_c - mat_b.T @ a_inv @ mat_b class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> None: """simple docstring""" A : Optional[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) A : Any = np.array([[0, 3], [3, 0], [2, 3]] ) A : Optional[int] = np.array([[2, 1], [6, 3]] ) A : int = schur_complement(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Union[str, Any] = np.block([[a, b], [b.T, c]] ) A : Any = np.linalg.det(SCREAMING_SNAKE_CASE ) A : List[str] = np.linalg.det(SCREAMING_SNAKE_CASE ) A : Tuple = np.linalg.det(SCREAMING_SNAKE_CASE ) self.assertAlmostEqual(SCREAMING_SNAKE_CASE , det_a * det_s ) def __lowerCAmelCase ( self ) -> None: """simple docstring""" A : Union[str, Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) A : str = np.array([[0, 3], [3, 0], [2, 3]] ) A : Tuple = np.array([[2, 1], [6, 3]] ) with self.assertRaises(SCREAMING_SNAKE_CASE ): schur_complement(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> None: """simple docstring""" A : Dict = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) A : Optional[int] = np.array([[0, 3], [3, 0], [2, 3]] ) A : int = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(SCREAMING_SNAKE_CASE ): schur_complement(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
311
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> List[str]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : int = patch_size A : Optional[int] = num_channels A : str = is_training A : List[Any] = use_labels A : Any = hidden_size A : Any = num_hidden_layers A : Optional[int] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : str = hidden_dropout_prob A : Tuple = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Optional[int] = initializer_range A : Dict = scope A : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A : List[Any] = (image_size // patch_size) ** 2 A : Tuple = num_patches + 2 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = TFDeiTModel(config=SCREAMING_SNAKE_CASE ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Tuple = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[int] = 1 A : str = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) A : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Tuple = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[Any] = 1 A : List[str] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() A, A, A : Tuple = config_and_inputs A : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = TFDeiTModelTester(self ) A : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Union[str, Any] = [*signature.parameters.keys()] A : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) A : Dict = self.default_image_processor A : List[str] = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Optional[int] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : str = tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
import os from typing import Dict, List, Tuple, TypeVar, Union A : str = TypeVar('T') A : Dict = Union[List[T], Tuple[T, ...]] A : Union[str, Any] = Union[T, List[T], Dict[str, T]] A : int = Union[str, bytes, os.PathLike]
6
from typing import Dict from .base import GenericTensor, Pipeline class __A( a ): def SCREAMING_SNAKE_CASE_ ( self , _snake_case=None , _snake_case=None , _snake_case=None , **_snake_case ) -> Optional[Any]: '''simple docstring''' if tokenize_kwargs is None: __a = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( '''truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)''' ) __a = truncation __a = tokenize_kwargs __a = {} if return_tensors is not None: __a = return_tensors return preprocess_params, {}, postprocess_params def SCREAMING_SNAKE_CASE_ ( self , _snake_case , **_snake_case ) -> Dict[str, GenericTensor]: '''simple docstring''' __a = self.framework __a = self.tokenizer(_snake_case , return_tensors=_snake_case , **_snake_case ) return model_inputs def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Optional[Any]: '''simple docstring''' __a = self.model(**_snake_case ) return model_outputs def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case=False ) -> Optional[int]: '''simple docstring''' if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self , *_snake_case , **_snake_case ) -> Any: '''simple docstring''' return super().__call__(*_snake_case , **_snake_case )
6
1
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def _lowercase ( __snake_case ) -> Optional[Any]: __lowerCAmelCase : str = fname.split(os.path.sep )[-1] return re.search(r"^(.*)_\d+\.jpg$" ,__snake_case ).groups()[0] class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict=None , _SCREAMING_SNAKE_CASE: Any=None) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : str = file_names __lowerCAmelCase : Optional[int] = image_transform __lowerCAmelCase : List[Any] = label_to_id def __len__( self: Union[str, Any]) -> int: """simple docstring""" return len(self.file_names) def __getitem__( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Any]) -> Optional[int]: """simple docstring""" __lowerCAmelCase : int = self.file_names[idx] __lowerCAmelCase : List[str] = PIL.Image.open(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = raw_image.convert("RGB") if self.image_transform is not None: __lowerCAmelCase : Union[str, Any] = self.image_transform(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = extract_label(_SCREAMING_SNAKE_CASE) if self.label_to_id is not None: __lowerCAmelCase : str = self.label_to_id[label] return {"image": image, "label": label} def _lowercase ( __snake_case ,__snake_case ) -> Optional[int]: # Initialize accelerator if args.with_tracking: __lowerCAmelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,log_with="all" ,project_dir=args.project_dir ) else: __lowerCAmelCase : Any = Accelerator(cpu=args.cpu ,mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __lowerCAmelCase : int = config["lr"] __lowerCAmelCase : Union[str, Any] = int(config["num_epochs"] ) __lowerCAmelCase : Tuple = int(config["seed"] ) __lowerCAmelCase : Tuple = int(config["batch_size"] ) __lowerCAmelCase : int = config["image_size"] if not isinstance(__snake_case ,(list, tuple) ): __lowerCAmelCase : Tuple = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps ,"isdigit" ): if args.checkpointing_steps == "epoch": __lowerCAmelCase : Optional[Any] = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): __lowerCAmelCase : Dict = int(args.checkpointing_steps ) else: raise ValueError( F"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.""" ) else: __lowerCAmelCase : int = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: __lowerCAmelCase : Dict = os.path.split(__snake_case )[-1].split("." )[0] accelerator.init_trackers(__snake_case ,__snake_case ) # Grab all the image filenames __lowerCAmelCase : Union[str, Any] = [os.path.join(args.data_dir ,__snake_case ) for fname in os.listdir(args.data_dir ) if fname.endswith(".jpg" )] # Build the label correspondences __lowerCAmelCase : Union[str, Any] = [extract_label(__snake_case ) for fname in file_names] __lowerCAmelCase : Any = list(set(__snake_case ) ) id_to_label.sort() __lowerCAmelCase : Optional[Any] = {lbl: i for i, lbl in enumerate(__snake_case )} # Set the seed before splitting the data. np.random.seed(__snake_case ) torch.manual_seed(__snake_case ) torch.cuda.manual_seed_all(__snake_case ) # Split our filenames between train and validation __lowerCAmelCase : List[str] = np.random.permutation(len(__snake_case ) ) __lowerCAmelCase : Dict = int(0.8 * len(__snake_case ) ) __lowerCAmelCase : str = random_perm[:cut] __lowerCAmelCase : Optional[int] = random_perm[cut:] # For training we use a simple RandomResizedCrop __lowerCAmelCase : str = Compose([RandomResizedCrop(__snake_case ,scale=(0.5, 1.0) ), ToTensor()] ) __lowerCAmelCase : List[str] = PetsDataset( [file_names[i] for i in train_split] ,image_transform=__snake_case ,label_to_id=__snake_case ) # For evaluation, we use a deterministic Resize __lowerCAmelCase : Union[str, Any] = Compose([Resize(__snake_case ), ToTensor()] ) __lowerCAmelCase : List[str] = PetsDataset([file_names[i] for i in eval_split] ,image_transform=__snake_case ,label_to_id=__snake_case ) # Instantiate dataloaders. __lowerCAmelCase : Union[str, Any] = DataLoader(__snake_case ,shuffle=__snake_case ,batch_size=__snake_case ,num_workers=4 ) __lowerCAmelCase : Any = DataLoader(__snake_case ,shuffle=__snake_case ,batch_size=__snake_case ,num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __lowerCAmelCase : int = create_model("resnet50d" ,pretrained=__snake_case ,num_classes=len(__snake_case ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __lowerCAmelCase : List[str] = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): __lowerCAmelCase : Any = False for param in model.get_classifier().parameters(): __lowerCAmelCase : List[Any] = True # We normalize the batches of images to be a bit faster. __lowerCAmelCase : Optional[Any] = torch.tensor(model.default_cfg["mean"] )[None, :, None, None].to(accelerator.device ) __lowerCAmelCase : int = torch.tensor(model.default_cfg["std"] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer __lowerCAmelCase : int = torch.optim.Adam(params=model.parameters() ,lr=lr / 25 ) # Instantiate learning rate scheduler __lowerCAmelCase : List[Any] = OneCycleLR(optimizer=__snake_case ,max_lr=__snake_case ,epochs=__snake_case ,steps_per_epoch=len(__snake_case ) ) # 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 : Tuple = accelerator.prepare( __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) # We need to keep track of how many total steps we have iterated over __lowerCAmelCase : Dict = 0 # We also need to keep track of the starting epoch so files are named properly __lowerCAmelCase : List[str] = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}""" ) accelerator.load_state(args.resume_from_checkpoint ) __lowerCAmelCase : Optional[Any] = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint __lowerCAmelCase : Optional[int] = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) __lowerCAmelCase : Optional[Any] = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` __lowerCAmelCase : str = os.path.splitext(__snake_case )[0] if "epoch" in training_difference: __lowerCAmelCase : Dict = int(training_difference.replace("epoch_" ,"" ) ) + 1 __lowerCAmelCase : Optional[Any] = None else: __lowerCAmelCase : Any = int(training_difference.replace("step_" ,"" ) ) __lowerCAmelCase : Optional[int] = resume_step // len(__snake_case ) resume_step -= starting_epoch * len(__snake_case ) # Now we train the model for epoch in range(__snake_case ,__snake_case ): model.train() if args.with_tracking: __lowerCAmelCase : Any = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step __lowerCAmelCase : Optional[int] = accelerator.skip_first_batches(__snake_case ,__snake_case ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader __lowerCAmelCase : Optional[int] = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. __lowerCAmelCase : List[Any] = {k: v.to(accelerator.device ) for k, v in batch.items()} __lowerCAmelCase : Union[str, Any] = (batch["image"] - mean) / std __lowerCAmelCase : Optional[int] = model(__snake_case ) __lowerCAmelCase : List[str] = torch.nn.functional.cross_entropy(__snake_case ,batch["label"] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__snake_case ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__snake_case ,__snake_case ): __lowerCAmelCase : List[Any] = F"""step_{overall_step}""" if overall_step % checkpointing_steps == 0: if args.output_dir is not None: __lowerCAmelCase : Tuple = os.path.join(args.output_dir ,__snake_case ) accelerator.save_state(__snake_case ) model.eval() __lowerCAmelCase : int = 0 __lowerCAmelCase : Optional[int] = 0 for step, batch in enumerate(__snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. __lowerCAmelCase : Tuple = {k: v.to(accelerator.device ) for k, v in batch.items()} __lowerCAmelCase : Optional[Any] = (batch["image"] - mean) / std with torch.no_grad(): __lowerCAmelCase : Optional[Any] = model(__snake_case ) __lowerCAmelCase : List[str] = outputs.argmax(dim=-1 ) __lowerCAmelCase : Optional[int] = accelerator.gather_for_metrics((predictions, batch["label"]) ) __lowerCAmelCase : str = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() __lowerCAmelCase : Optional[Any] = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}: {100 * eval_metric:.2f}""" ) if args.with_tracking: accelerator.log( { "accuracy": 100 * eval_metric, "train_loss": total_loss.item() / len(__snake_case ), "epoch": epoch, } ,step=__snake_case ,) if checkpointing_steps == "epoch": __lowerCAmelCase : Tuple = F"""epoch_{epoch}""" if args.output_dir is not None: __lowerCAmelCase : Optional[Any] = os.path.join(args.output_dir ,__snake_case ) accelerator.save_state(__snake_case ) if args.with_tracking: accelerator.end_training() def _lowercase ( ) -> Tuple: __lowerCAmelCase : Union[str, Any] = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument("--data_dir" ,required=__snake_case ,help="The data folder on disk." ) parser.add_argument("--fp16" ,action="store_true" ,help="If passed, will use FP16 training." ) parser.add_argument( "--mixed_precision" ,type=__snake_case ,default=__snake_case ,choices=["no", "fp16", "bf16", "fp8"] ,help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." ,) parser.add_argument("--cpu" ,action="store_true" ,help="If passed, will train on the CPU." ) parser.add_argument( "--checkpointing_steps" ,type=__snake_case ,default=__snake_case ,help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch." ,) parser.add_argument( "--output_dir" ,type=__snake_case ,default="." ,help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." ,) parser.add_argument( "--resume_from_checkpoint" ,type=__snake_case ,default=__snake_case ,help="If the training should continue from a checkpoint folder." ,) parser.add_argument( "--with_tracking" ,action="store_true" ,help="Whether to load in all available experiment trackers from the environment and use them for logging." ,) parser.add_argument( "--project_dir" ,type=__snake_case ,default="logs" ,help="Location on where to store experiment tracking logs` and relevent project information" ,) __lowerCAmelCase : List[Any] = parser.parse_args() __lowerCAmelCase : List[Any] = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224} training_function(__snake_case ,__snake_case ) if __name__ == "__main__": main()
358
"""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 A__ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self: Dict) -> Any: """simple docstring""" __lowerCAmelCase : Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" , return_dict=_SCREAMING_SNAKE_CASE).to(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = AutoTokenizer.from_pretrained("google/mt5-small") __lowerCAmelCase : Tuple = tokenizer("Hello there" , return_tensors="pt").input_ids __lowerCAmelCase : List[str] = tokenizer("Hi I am" , return_tensors="pt").input_ids __lowerCAmelCase : List[str] = model(input_ids.to(_SCREAMING_SNAKE_CASE) , labels=labels.to(_SCREAMING_SNAKE_CASE)).loss __lowerCAmelCase : Optional[int] = -(labels.shape[-1] * loss.item()) __lowerCAmelCase : List[str] = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
58
0
def A ( _SCREAMING_SNAKE_CASE ) -> list: if n_term == "": return [] lowerCamelCase : list = [] for temp in range(int(_SCREAMING_SNAKE_CASE ) ): series.append(f'''1/{temp + 1}''' if series else "1" ) return series if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Dict = input('Enter the last number (nth term) of the Harmonic Series') print('Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n') print(harmonic_series(nth_term))
48
from ...processing_utils import ProcessorMixin class lowercase_ ( UpperCamelCase_ ): """simple docstring""" UpperCAmelCase_ : List[Any] = ["""image_processor""", """feature_extractor"""] UpperCAmelCase_ : Optional[int] = """TvltImageProcessor""" UpperCAmelCase_ : Optional[int] = """TvltFeatureExtractor""" def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->Optional[int]: super().__init__(image_processor=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) lowerCAmelCase = image_processor lowerCAmelCase = feature_extractor def __call__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) ->List[Any]: if images is None and audio is None: raise ValueError('''You need to specify either an `images` or `audio` input to process.''' ) lowerCAmelCase = None if images is not None: lowerCAmelCase = self.image_processor(__SCREAMING_SNAKE_CASE , mask_pixel=__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if images_mixed is not None: lowerCAmelCase = self.image_processor(__SCREAMING_SNAKE_CASE , is_mixed=__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if audio is not None: lowerCAmelCase = self.feature_extractor( __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , mask_audio=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowerCAmelCase = {} if audio is not None: output_dict.update(__SCREAMING_SNAKE_CASE ) if images is not None: output_dict.update(__SCREAMING_SNAKE_CASE ) if images_mixed_dict is not None: output_dict.update(__SCREAMING_SNAKE_CASE ) return output_dict @property def SCREAMING_SNAKE_CASE_ ( self ) ->Any: lowerCAmelCase = self.image_processor.model_input_names lowerCAmelCase = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
338
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _A = {"""configuration_speech_encoder_decoder""": ["""SpeechEncoderDecoderConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ["""SpeechEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ["""FlaxSpeechEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
365
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = {"""vocab_file""": """vocab.json"""} _A = { """vocab_file""": { """mgp-str""": """https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json""", } } _A = {"""mgp-str""": 2_7} class _lowerCamelCase ( a_ ): _lowerCamelCase :Dict = VOCAB_FILES_NAMES _lowerCamelCase :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase :Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Optional[int] , UpperCamelCase : int , UpperCamelCase : Union[str, Any]="[GO]" , UpperCamelCase : Any="[GO]" , UpperCamelCase : Tuple="[s]" , UpperCamelCase : List[Any]="[GO]" , **UpperCamelCase : Dict ) -> Union[str, Any]: """simple docstring""" super().__init__( unk_token=UpperCamelCase , bos_token=UpperCamelCase , eos_token=UpperCamelCase , pad_token=UpperCamelCase , **UpperCamelCase , ) with open(UpperCamelCase , encoding="""utf-8""" ) as vocab_handle: lowerCAmelCase__ : Optional[Any] = json.load(UpperCamelCase ) lowerCAmelCase__ : Union[str, Any] = {v: k for k, v in self.vocab.items()} @property def _lowerCAmelCase ( self : int ) -> Dict: """simple docstring""" return len(self.vocab ) def _lowerCAmelCase ( self : Dict ) -> Any: """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def _lowerCAmelCase ( self : List[Any] , UpperCamelCase : Tuple ) -> Optional[Any]: """simple docstring""" lowerCAmelCase__ : Optional[Any] = [] for s in text: char_tokens.extend(UpperCamelCase ) return char_tokens def _lowerCAmelCase ( self : List[Any] , UpperCamelCase : str ) -> Tuple: """simple docstring""" return self.vocab.get(UpperCamelCase , self.vocab.get(self.unk_token ) ) def _lowerCAmelCase ( self : List[str] , UpperCamelCase : int ) -> Any: """simple docstring""" return self.decoder.get(UpperCamelCase ) def _lowerCAmelCase ( self : Dict , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCamelCase ): logger.error("""Vocabulary path ({}) should be a directory""".format(UpperCamelCase ) ) return lowerCAmelCase__ : Union[str, Any] = os.path.join( UpperCamelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) with open(UpperCamelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=UpperCamelCase , ensure_ascii=UpperCamelCase ) + """\n""" ) return (vocab_file,)
212
0
import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class UpperCAmelCase_ : def __init__( self, __a, __a=13, __a=7, __a=True, __a=True, __a=True, __a=True, __a=99, __a=64, __a=5, __a=4, __a=37, __a="gelu", __a=0.1, __a=0.1, __a=512, __a=16, __a=2, __a=0.02, __a=3, __a=4, __a=None, ): '''simple docstring''' _lowerCAmelCase : Tuple = parent _lowerCAmelCase : Optional[int] = batch_size _lowerCAmelCase : Optional[int] = seq_length _lowerCAmelCase : List[Any] = is_training _lowerCAmelCase : Any = use_input_mask _lowerCAmelCase : List[Any] = use_token_type_ids _lowerCAmelCase : str = use_labels _lowerCAmelCase : Optional[int] = vocab_size _lowerCAmelCase : Optional[Any] = hidden_size _lowerCAmelCase : int = num_hidden_layers _lowerCAmelCase : str = num_attention_heads _lowerCAmelCase : Any = intermediate_size _lowerCAmelCase : Optional[Any] = hidden_act _lowerCAmelCase : Optional[int] = hidden_dropout_prob _lowerCAmelCase : List[Any] = attention_probs_dropout_prob _lowerCAmelCase : List[Any] = max_position_embeddings _lowerCAmelCase : Union[str, Any] = type_vocab_size _lowerCAmelCase : str = type_sequence_label_size _lowerCAmelCase : Optional[Any] = initializer_range _lowerCAmelCase : Dict = num_labels _lowerCAmelCase : Any = num_choices _lowerCAmelCase : Optional[int] = scope _lowerCAmelCase : List[str] = vocab_size - 1 def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) _lowerCAmelCase : Union[str, Any] = None if self.use_input_mask: _lowerCAmelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCAmelCase : Any = None if self.use_labels: _lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length], self.num_labels) _lowerCAmelCase : Optional[Any] = self.get_config() return config, input_ids, input_mask, token_labels def snake_case__ ( self): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=__a, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, ) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[str] = self.prepare_config_and_inputs() _lowerCAmelCase : str = True return config, input_ids, input_mask, token_labels def snake_case__ ( self, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : List[str] = GPTNeoXModel(config=__a) model.to(__a) model.eval() _lowerCAmelCase : Optional[int] = model(__a, attention_mask=__a) _lowerCAmelCase : str = model(__a) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def snake_case__ ( self, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : List[Any] = True _lowerCAmelCase : List[Any] = GPTNeoXModel(__a) model.to(__a) model.eval() _lowerCAmelCase : List[Any] = model(__a, attention_mask=__a) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def snake_case__ ( self, __a, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : int = GPTNeoXForCausalLM(config=__a) model.to(__a) model.eval() _lowerCAmelCase : Tuple = model(__a, attention_mask=__a, labels=__a) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def snake_case__ ( self, __a, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : Optional[Any] = self.num_labels _lowerCAmelCase : Union[str, Any] = GPTNeoXForQuestionAnswering(__a) model.to(__a) model.eval() _lowerCAmelCase : Tuple = model(__a, attention_mask=__a) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def snake_case__ ( self, __a, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : str = self.num_labels _lowerCAmelCase : str = GPTNeoXForSequenceClassification(__a) model.to(__a) model.eval() _lowerCAmelCase : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size) _lowerCAmelCase : Dict = model(__a, attention_mask=__a, labels=__a) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def snake_case__ ( self, __a, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : str = self.num_labels _lowerCAmelCase : Dict = GPTNeoXForTokenClassification(__a) model.to(__a) model.eval() _lowerCAmelCase : str = model(__a, attention_mask=__a, labels=__a) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def snake_case__ ( self, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : Tuple = True _lowerCAmelCase : Dict = GPTNeoXForCausalLM(config=__a) model.to(__a) model.eval() # first forward pass _lowerCAmelCase : List[Any] = model(__a, attention_mask=__a, use_cache=__a) _lowerCAmelCase : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _lowerCAmelCase : Optional[Any] = ids_tensor((self.batch_size, 3), config.vocab_size) _lowerCAmelCase : Dict = ids_tensor((self.batch_size, 3), vocab_size=2) # append to next input_ids and _lowerCAmelCase : int = torch.cat([input_ids, next_tokens], dim=-1) _lowerCAmelCase : str = torch.cat([input_mask, next_mask], dim=-1) _lowerCAmelCase : List[str] = model(__a, attention_mask=__a, output_hidden_states=__a) _lowerCAmelCase : List[str] = output_from_no_past["hidden_states"][0] _lowerCAmelCase : List[Any] = model( __a, attention_mask=__a, past_key_values=__a, output_hidden_states=__a, )["hidden_states"][0] # select random slice _lowerCAmelCase : int = ids_tensor((1,), output_from_past.shape[-1]).item() _lowerCAmelCase : str = output_from_no_past[:, -3:, random_slice_idx].detach() _lowerCAmelCase : Union[str, Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__a, __a, atol=1E-3)) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Dict = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[str] = config_and_inputs _lowerCAmelCase : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( a , a , a , unittest.TestCase): lowerCamelCase__ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) lowerCamelCase__ = (GPTNeoXForCausalLM,) if is_torch_available() else () lowerCamelCase__ = ( { 'feature-extraction': GPTNeoXModel, 'question-answering': GPTNeoXForQuestionAnswering, 'text-classification': GPTNeoXForSequenceClassification, 'text-generation': GPTNeoXForCausalLM, 'token-classification': GPTNeoXForTokenClassification, 'zero-shot': GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Dict = GPTNeoXModelTester(self) _lowerCAmelCase : Union[str, Any] = ConfigTester(self, config_class=__a, hidden_size=64, num_attention_heads=8) def snake_case__ ( self): '''simple docstring''' self.config_tester.run_common_tests() def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a, __a, __a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(__a, __a, __a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() _lowerCAmelCase : List[str] = None self.model_tester.create_and_check_model_as_decoder(__a, __a, __a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(__a, __a, __a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*__a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__a) @unittest.skip(reason="Feed forward chunking is not implemented") def snake_case__ ( self): '''simple docstring''' pass @parameterized.expand([("linear",), ("dynamic",)]) def snake_case__ ( self, __a): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : Optional[Any] = ids_tensor([1, 10], config.vocab_size) _lowerCAmelCase : List[str] = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights _lowerCAmelCase : List[Any] = GPTNeoXModel(__a) original_model.to(__a) original_model.eval() _lowerCAmelCase : Union[str, Any] = original_model(__a).last_hidden_state _lowerCAmelCase : Union[str, Any] = original_model(__a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights _lowerCAmelCase : int = {"type": scaling_type, "factor": 10.0} _lowerCAmelCase : Optional[int] = GPTNeoXModel(__a) scaled_model.to(__a) scaled_model.eval() _lowerCAmelCase : Optional[Any] = scaled_model(__a).last_hidden_state _lowerCAmelCase : Optional[Any] = scaled_model(__a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__a, __a, atol=1E-5)) else: self.assertFalse(torch.allclose(__a, __a, atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(__a, __a, atol=1E-5)) @require_torch class UpperCAmelCase_ ( unittest.TestCase): @slow def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : int = AutoTokenizer.from_pretrained("EleutherAI/pythia-410m-deduped") for checkpointing in [True, False]: _lowerCAmelCase : List[str] = GPTNeoXForCausalLM.from_pretrained("EleutherAI/pythia-410m-deduped") if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(__a) _lowerCAmelCase : str = tokenizer("My favorite food is", return_tensors="pt").to(__a) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 _lowerCAmelCase : str = "My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure" _lowerCAmelCase : Any = model.generate(**__a, do_sample=__a, max_new_tokens=20) _lowerCAmelCase : str = tokenizer.batch_decode(__a)[0] self.assertEqual(__a, __a)
36
def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' if density <= 0: raise ValueError("Impossible fluid density" ) if bulk_modulus <= 0: raise ValueError("Impossible bulk modulus" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
36
1
import inspect import unittest class lowerCamelCase (unittest.TestCase ): """simple docstring""" def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def A_ ( self : List[str] ) -> List[str]: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ : str = inspect.getmembers(_UpperCAmelCase, inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ : Any = "k-diffusion" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ : Dict = "invisible-watermark" assert backend in deps, F'''{backend} is not in the deps table!'''
370
def _a ( SCREAMING_SNAKE_CASE__ : int = 50_00_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = set() SCREAMING_SNAKE_CASE__ : Dict = int((limit - 24) ** (1 / 2) ) SCREAMING_SNAKE_CASE__ : Any = 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: SCREAMING_SNAKE_CASE__ : Optional[int] = primea * primea for primea in primes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: SCREAMING_SNAKE_CASE__ : List[str] = primea * primea * primea * primea SCREAMING_SNAKE_CASE__ : Optional[int] = square + cube + tetr if total >= limit: break ret.add(SCREAMING_SNAKE_CASE__ ) return len(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": print(f"{solution() = }")
191
0
"""simple docstring""" def lowercase ( __snake_case : int , __snake_case : list[int] , __snake_case : int ): def count_of_possible_combinations(__snake_case : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(__snake_case ) def lowercase ( __snake_case : int , __snake_case : list[int] , __snake_case : int ): def count_of_possible_combinations_with_dp_array( __snake_case : int , __snake_case : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] lowercase_ : Optional[int] = sum( count_of_possible_combinations_with_dp_array(target - item , __snake_case ) for item in array ) lowercase_ : Union[str, Any] = answer return answer lowercase_ : Dict = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(__snake_case , __snake_case ) def lowercase ( __snake_case : int , __snake_case : list[int] , __snake_case : int ): lowercase_ : List[Any] = [0] * (target + 1) lowercase_ : Optional[Any] = 1 for i in range(1 , target + 1 ): for j in range(__snake_case ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() __A : int = 3 __A : Union[str, Any] = 5 __A : List[str] = [1, 2, 5] print(combination_sum_iv(n, array, target))
33
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : int = { 'transfo-xl-wt103': 'https://huggingface.co/transfo-xl-wt103/resolve/main/config.json', } class lowercase ( __UpperCAmelCase): __lowerCAmelCase : Union[str, Any] = """transfo-xl""" __lowerCAmelCase : Optional[Any] = ["""mems"""] __lowerCAmelCase : List[str] = { """n_token""": """vocab_size""", """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : int , _lowerCamelCase : List[Any]=26_77_35 , _lowerCamelCase : Any=[2_00_00, 4_00_00, 20_00_00] , _lowerCamelCase : str=10_24 , _lowerCamelCase : Union[str, Any]=10_24 , _lowerCamelCase : Union[str, Any]=16 , _lowerCamelCase : int=64 , _lowerCamelCase : Optional[int]=40_96 , _lowerCamelCase : Optional[int]=4 , _lowerCamelCase : str=False , _lowerCamelCase : Union[str, Any]=18 , _lowerCamelCase : Optional[Any]=16_00 , _lowerCamelCase : Optional[int]=10_00 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Any=True , _lowerCamelCase : Tuple=0 , _lowerCamelCase : List[Any]=-1 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : List[str]=0.1 , _lowerCamelCase : List[Any]=0.0 , _lowerCamelCase : List[Any]=True , _lowerCamelCase : List[str]="normal" , _lowerCamelCase : int=0.01 , _lowerCamelCase : List[str]=0.01 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : int=1E-5 , _lowerCamelCase : int=0 , **_lowerCamelCase : Union[str, Any] , ): """simple docstring""" A_ : Optional[Any] = vocab_size A_ : str = [] self.cutoffs.extend(_lowerCamelCase ) if proj_share_all_but_first: A_ : str = [False] + [True] * len(self.cutoffs ) else: A_ : str = [False] + [False] * len(self.cutoffs ) A_ : Optional[Any] = d_model A_ : Dict = d_embed A_ : List[str] = d_head A_ : List[Any] = d_inner A_ : Dict = div_val A_ : int = pre_lnorm A_ : Optional[Any] = n_layer A_ : List[Any] = n_head A_ : List[Any] = mem_len A_ : Dict = same_length A_ : Optional[Any] = attn_type A_ : Any = clamp_len A_ : Dict = sample_softmax A_ : List[Any] = adaptive A_ : Union[str, Any] = dropout A_ : List[Any] = dropatt A_ : Any = untie_r A_ : Optional[int] = init A_ : int = init_range A_ : List[Any] = proj_init_std A_ : Union[str, Any] = init_std A_ : List[Any] = layer_norm_epsilon super().__init__(eos_token_id=_lowerCamelCase , **_lowerCamelCase ) @property def a_ ( self : Union[str, Any] ): """simple docstring""" logger.info(F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def a_ ( self : Any , _lowerCamelCase : int ): """simple docstring""" raise NotImplementedError( F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
167
0
from __future__ import annotations from scipy.special import comb # type: ignore class UpperCamelCase : '''simple docstring''' def __init__( self , UpperCamelCase_ ): lowercase_ :Optional[Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. lowercase_ :str = len(UpperCamelCase_ ) - 1 def UpperCamelCase ( self , UpperCamelCase_ ): assert 0 <= t <= 1, "Time t must be between 0 and 1." lowercase_ :list[float] = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , UpperCamelCase_ ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(UpperCamelCase_ ) , 5 ) == 1 return output_values def UpperCamelCase ( self , UpperCamelCase_ ): assert 0 <= t <= 1, "Time t must be between 0 and 1." lowercase_ :Optional[Any] = self.basis_function(UpperCamelCase_ ) lowercase_ :Union[str, Any] = 0.0 lowercase_ :Tuple = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def UpperCamelCase ( self , UpperCamelCase_ = 0.01 ): from matplotlib import pyplot as plt # type: ignore lowercase_ :list[float] = [] # x coordinates of points to plot lowercase_ :list[float] = [] # y coordinates of points to plot lowercase_ :Optional[Any] = 0.0 while t <= 1: lowercase_ :Tuple = self.bezier_curve_function(UpperCamelCase_ ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size lowercase_ :List[str] = [i[0] for i in self.list_of_points] lowercase_ :Optional[int] = [i[1] for i in self.list_of_points] plt.plot( UpperCamelCase_ , UpperCamelCase_ , color='''blue''' , label='''Curve of Degree ''' + str(self.degree ) , ) plt.scatter(UpperCamelCase_ , UpperCamelCase_ , color='''red''' , label='''Control Points''' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
252
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Any = { "edbeeching/decision-transformer-gym-hopper-medium": ( "https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class UpperCamelCase ( lowercase__ ): '''simple docstring''' lowercase : Optional[int] ="""decision_transformer""" lowercase : Dict =["""past_key_values"""] lowercase : Any ={ """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , UpperCamelCase_=17 , UpperCamelCase_=4 , UpperCamelCase_=128 , UpperCamelCase_=4096 , UpperCamelCase_=True , UpperCamelCase_=1 , UpperCamelCase_=1024 , UpperCamelCase_=3 , UpperCamelCase_=1 , UpperCamelCase_=None , UpperCamelCase_="relu" , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=1E-5 , UpperCamelCase_=0.02 , UpperCamelCase_=True , UpperCamelCase_=True , UpperCamelCase_=5_0256 , UpperCamelCase_=5_0256 , UpperCamelCase_=False , UpperCamelCase_=False , **UpperCamelCase_ , ): lowercase_ :Any = state_dim lowercase_ :List[str] = act_dim lowercase_ :List[str] = hidden_size lowercase_ :int = max_ep_len lowercase_ :List[str] = action_tanh lowercase_ :Any = vocab_size lowercase_ :List[Any] = n_positions lowercase_ :List[str] = n_layer lowercase_ :Optional[Any] = n_head lowercase_ :int = n_inner lowercase_ :List[str] = activation_function lowercase_ :List[str] = resid_pdrop lowercase_ :Dict = embd_pdrop lowercase_ :List[Any] = attn_pdrop lowercase_ :Union[str, Any] = layer_norm_epsilon lowercase_ :List[str] = initializer_range lowercase_ :Any = scale_attn_weights lowercase_ :Union[str, Any] = use_cache lowercase_ :Any = scale_attn_by_inverse_layer_idx lowercase_ :Tuple = reorder_and_upcast_attn lowercase_ :int = bos_token_id lowercase_ :List[str] = eos_token_id super().__init__(bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ )
252
1
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): _lowerCamelCase : Optional[Any] = 'pt' elif is_tf_available(): _lowerCamelCase : List[str] = 'tf' else: _lowerCamelCase : Tuple = 'jax' class lowercase ( __UpperCAmelCase , unittest.TestCase): __lowerCAmelCase : Tuple = ByTaTokenizer __lowerCAmelCase : Optional[int] = False def a_ ( self : Union[str, Any] ): """simple docstring""" super().setUp() A_ : Tuple = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def a_ ( self : Any ): """simple docstring""" return ByTaTokenizer.from_pretrained('''google/byt5-small''' ) def a_ ( self : List[Any] , **_lowerCamelCase : Dict ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def a_ ( self : Optional[int] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str]=False , _lowerCamelCase : Optional[Any]=20 , _lowerCamelCase : Union[str, Any]=5 ): """simple docstring""" A_ : int = [] for i in range(len(_lowerCamelCase ) ): try: A_ : Optional[int] = tokenizer.decode([i] , clean_up_tokenization_spaces=_lowerCamelCase ) except UnicodeDecodeError: pass toks.append((i, tok) ) A_ : Dict = list(filter(lambda _lowerCamelCase : re.match(r'''^[ a-zA-Z]+$''' , t[1] ) , _lowerCamelCase ) ) A_ : Dict = list(filter(lambda _lowerCamelCase : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_lowerCamelCase ) , _lowerCamelCase ) ) if max_length is not None and len(_lowerCamelCase ) > max_length: A_ : List[str] = toks[:max_length] if min_length is not None and len(_lowerCamelCase ) < min_length and len(_lowerCamelCase ) > 0: while len(_lowerCamelCase ) < min_length: A_ : int = toks + toks # toks_str = [t[1] for t in toks] A_ : int = [t[0] for t in toks] # Ensure consistency A_ : List[str] = tokenizer.decode(_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) if " " not in output_txt and len(_lowerCamelCase ) > 1: A_ : Union[str, Any] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_lowerCamelCase ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_lowerCamelCase ) ) if with_prefix_space: A_ : Tuple = ''' ''' + output_txt A_ : Any = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) return output_txt, output_ids def a_ ( self : Optional[int] ): """simple docstring""" A_ : Any = self.ta_base_tokenizer A_ : Any = tokenizer(['''hi</s>''', '''I went to the gym</s>''', '''</s>'''] ) A_ : Dict = tokenizer(['''hi''', '''I went to the gym''', ''''''] ) self.assertListEqual(batch_with_eos_added['''input_ids'''] , batch_without_eos_added['''input_ids'''] ) def a_ ( self : int ): """simple docstring""" A_ : Dict = self.ta_base_tokenizer A_ : Dict = '''Unicode €.''' A_ : Dict = tokenizer(_lowerCamelCase ) A_ : str = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['''input_ids'''] , _lowerCamelCase ) # decoding A_ : Optional[Any] = tokenizer.decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , '''Unicode €.</s>''' ) A_ : Optional[Any] = tokenizer('''e è é ê ë''' ) A_ : str = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['''input_ids'''] , _lowerCamelCase ) # decoding A_ : Union[str, Any] = tokenizer.decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , '''e è é ê ë</s>''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''e è é ê ë</s>''' ) def a_ ( self : Optional[Any] ): """simple docstring""" A_ : int = self.ta_base_tokenizer A_ : str = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off A_ : Optional[Any] = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on A_ : Dict = tokenizer(_lowerCamelCase , padding=_lowerCamelCase , return_tensors=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) if FRAMEWORK != "jax": A_ : Union[str, Any] = list(batch.input_ids.numpy()[0] ) else: A_ : Optional[int] = list(batch.input_ids.tolist()[0] ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def a_ ( self : Optional[int] ): """simple docstring""" A_ : Tuple = self.ta_base_tokenizer A_ : Any = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] A_ : List[Any] = tokenizer(_lowerCamelCase , padding=_lowerCamelCase , return_tensors=_lowerCamelCase ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , _lowerCamelCase ) self.assertIn('''attention_mask''' , _lowerCamelCase ) self.assertNotIn('''decoder_input_ids''' , _lowerCamelCase ) self.assertNotIn('''decoder_attention_mask''' , _lowerCamelCase ) def a_ ( self : Optional[int] ): """simple docstring""" A_ : Dict = self.ta_base_tokenizer A_ : Any = [ '''Summary of the text.''', '''Another summary.''', ] A_ : Dict = tokenizer( text_target=_lowerCamelCase , max_length=32 , padding='''max_length''' , truncation=_lowerCamelCase , return_tensors=_lowerCamelCase ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) def a_ ( self : str ): """simple docstring""" A_ : int = self.ta_base_tokenizer A_ : Dict = ['''A long paragraph for summarization. </s>'''] A_ : str = ['''Summary of the text. </s>'''] # fmt: off A_ : Tuple = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] A_ : Optional[int] = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on A_ : Any = tokenizer(_lowerCamelCase , text_target=_lowerCamelCase ) self.assertEqual(_lowerCamelCase , batch['''input_ids'''][0] ) self.assertEqual(_lowerCamelCase , batch['''labels'''][0] ) def a_ ( self : Any ): """simple docstring""" A_ : Tuple = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test A_ : Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc A_ : List[str] = tempfile.mkdtemp() A_ : Dict = ''' He is very happy, UNwant\u00E9d,running''' A_ : Optional[Any] = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) tokenizer.save_pretrained(_lowerCamelCase ) A_ : List[Any] = tokenizer.__class__.from_pretrained(_lowerCamelCase ) A_ : str = after_tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) shutil.rmtree(_lowerCamelCase ) A_ : Any = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc A_ : List[Any] = tempfile.mkdtemp() A_ : Union[str, Any] = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) A_ : Union[str, Any] = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) A_ : List[Any] = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) tokenizer.save_pretrained(_lowerCamelCase ) A_ : str = tokenizer.__class__.from_pretrained(_lowerCamelCase ) A_ : Optional[Any] = after_tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) A_ : Tuple = tokenizer.__class__.from_pretrained(_lowerCamelCase , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(_lowerCamelCase ) def a_ ( self : Union[str, Any] ): """simple docstring""" A_ : List[Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_lowerCamelCase ) with open(os.path.join(_lowerCamelCase , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: A_ : Optional[int] = json.load(_lowerCamelCase ) with open(os.path.join(_lowerCamelCase , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: A_ : List[str] = json.load(_lowerCamelCase ) A_ : Optional[Any] = [F"""<extra_id_{i}>""" for i in range(1_25 )] A_ : Dict = added_tokens_extra_ids + [ '''an_additional_special_token''' ] A_ : Optional[Any] = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(_lowerCamelCase , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(_lowerCamelCase , _lowerCamelCase ) with open(os.path.join(_lowerCamelCase , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(_lowerCamelCase , _lowerCamelCase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files A_ : List[Any] = tokenizer_class.from_pretrained( _lowerCamelCase , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained A_ : Union[str, Any] = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=_lowerCamelCase )] A_ : List[Any] = tokenizer_class.from_pretrained( _lowerCamelCase , additional_special_tokens=_lowerCamelCase , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def a_ ( self : Dict ): """simple docstring""" A_ : str = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_lowerCamelCase ) A_ : List[str] = tokenizer_class.from_pretrained(_lowerCamelCase ) self.assertTrue(tokenizer.decode([2_55] ) == '''''' ) def a_ ( self : int ): """simple docstring""" pass def a_ ( self : Union[str, Any] ): """simple docstring""" pass def a_ ( self : str ): """simple docstring""" pass def a_ ( self : Optional[Any] ): """simple docstring""" pass def a_ ( self : Tuple ): """simple docstring""" A_ : str = self.get_tokenizers(fast=_lowerCamelCase , do_lower_case=_lowerCamelCase ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): A_ : Tuple = ['''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''x''', '''t''', '''</s>'''] A_ : int = tokenizer.convert_tokens_to_string(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def a_ ( self : Union[str, Any] ): """simple docstring""" A_ : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): A_ : str = [ '''bos_token''', '''eos_token''', '''unk_token''', '''sep_token''', '''pad_token''', '''cls_token''', '''mask_token''', ] A_ : str = 0 A_ : Dict = tokenizer.convert_ids_to_tokens( _lowerCamelCase , skip_special_tokens=_lowerCamelCase ) for attr in attributes_list: setattr(_lowerCamelCase , attr + '''_id''' , _lowerCamelCase ) self.assertEqual(getattr(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(getattr(_lowerCamelCase , attr + '''_id''' ) , _lowerCamelCase ) setattr(_lowerCamelCase , attr + '''_id''' , _lowerCamelCase ) self.assertEqual(getattr(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(getattr(_lowerCamelCase , attr + '''_id''' ) , _lowerCamelCase ) setattr(_lowerCamelCase , '''additional_special_tokens_ids''' , [] ) self.assertListEqual(getattr(_lowerCamelCase , '''additional_special_tokens''' ) , [] ) self.assertListEqual(getattr(_lowerCamelCase , '''additional_special_tokens_ids''' ) , [] ) setattr(_lowerCamelCase , '''additional_special_tokens_ids''' , [token_id_to_test_setters] ) self.assertListEqual(getattr(_lowerCamelCase , '''additional_special_tokens''' ) , [token_to_test_setters] ) self.assertListEqual(getattr(_lowerCamelCase , '''additional_special_tokens_ids''' ) , [token_id_to_test_setters] )
167
"""simple docstring""" import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class lowercase ( __UpperCAmelCase): __lowerCAmelCase : str = ["""image_processor""", """tokenizer"""] __lowerCAmelCase : Optional[Any] = """OwlViTImageProcessor""" __lowerCAmelCase : Any = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self : Union[str, Any] , _lowerCamelCase : str=None , _lowerCamelCase : Tuple=None , **_lowerCamelCase : List[Any] ): """simple docstring""" A_ : Optional[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.''' , _lowerCamelCase , ) A_ : List[Any] = kwargs.pop('''feature_extractor''' ) A_ : Any = 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__(_lowerCamelCase , _lowerCamelCase ) def __call__( self : Optional[int] , _lowerCamelCase : List[Any]=None , _lowerCamelCase : Dict=None , _lowerCamelCase : int=None , _lowerCamelCase : str="max_length" , _lowerCamelCase : List[Any]="np" , **_lowerCamelCase : Optional[int] ): """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( '''You have to specify at least one text or query image or image. All three cannot be none.''' ) if text is not None: if isinstance(_lowerCamelCase , _lowerCamelCase ) or (isinstance(_lowerCamelCase , _lowerCamelCase ) and not isinstance(text[0] , _lowerCamelCase )): A_ : List[str] = [self.tokenizer(_lowerCamelCase , padding=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase )] elif isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(text[0] , _lowerCamelCase ): A_ : Optional[int] = [] # Maximum number of queries across batch A_ : Any = max([len(_lowerCamelCase ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(_lowerCamelCase ) != max_num_queries: A_ : Optional[int] = t + [''' '''] * (max_num_queries - len(_lowerCamelCase )) A_ : Tuple = self.tokenizer(_lowerCamelCase , padding=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) encodings.append(_lowerCamelCase ) else: raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''' ) if return_tensors == "np": A_ : Union[str, Any] = np.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0 ) A_ : Dict = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp A_ : List[Any] = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0 ) A_ : Any = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch A_ : Any = torch.cat([encoding['''input_ids'''] for encoding in encodings] , dim=0 ) A_ : Union[str, Any] = torch.cat([encoding['''attention_mask'''] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf A_ : Tuple = tf.stack([encoding['''input_ids'''] for encoding in encodings] , axis=0 ) A_ : str = tf.stack([encoding['''attention_mask'''] for encoding in encodings] , axis=0 ) else: raise ValueError('''Target return tensor type could not be returned''' ) A_ : Any = BatchEncoding() A_ : Optional[Any] = input_ids A_ : str = attention_mask if query_images is not None: A_ : Union[str, Any] = BatchEncoding() A_ : Optional[Any] = self.image_processor( _lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ).pixel_values A_ : Dict = query_pixel_values if images is not None: A_ : int = self.image_processor(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if text is not None and images is not None: A_ : str = image_features.pixel_values return encoding elif query_images is not None and images is not None: A_ : Union[str, Any] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**_lowerCamelCase ) , tensor_type=_lowerCamelCase ) def a_ ( self : Optional[Any] , *_lowerCamelCase : int , **_lowerCamelCase : Dict ): """simple docstring""" return self.image_processor.post_process(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ): """simple docstring""" return self.image_processor.post_process_object_detection(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : List[Any] , *_lowerCamelCase : List[str] , **_lowerCamelCase : Optional[int] ): """simple docstring""" return self.image_processor.post_process_image_guided_detection(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : str , *_lowerCamelCase : Tuple , **_lowerCamelCase : List[Any] ): """simple docstring""" return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : Dict , *_lowerCamelCase : Any , **_lowerCamelCase : Union[str, Any] ): """simple docstring""" return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @property def a_ ( self : List[str] ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _lowerCamelCase , ) return self.image_processor_class @property def a_ ( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _lowerCamelCase , ) return self.image_processor
167
1
'''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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class _A ( __lowercase , __lowercase ): lowercase__: str = '''resnet''' lowercase__: Dict = ['''basic''', '''bottleneck'''] def __init__( self : Dict , __magic_name__ : int=3 , __magic_name__ : Optional[int]=64 , __magic_name__ : Optional[int]=[2_56, 5_12, 10_24, 20_48] , __magic_name__ : Optional[int]=[3, 4, 6, 3] , __magic_name__ : List[Any]="bottleneck" , __magic_name__ : int="relu" , __magic_name__ : Union[str, Any]=False , __magic_name__ : Tuple=None , __magic_name__ : Dict=None , **__magic_name__ : Any , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__magic_name__ ) if layer_type not in self.layer_types: raise ValueError(f'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) __snake_case : Tuple = num_channels __snake_case : List[Any] = embedding_size __snake_case : int = hidden_sizes __snake_case : List[Any] = depths __snake_case : int = layer_type __snake_case : Optional[Any] = hidden_act __snake_case : List[Any] = downsample_in_first_stage __snake_case : Tuple = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__magic_name__ ) + 1 )] __snake_case , __snake_case : List[str] = get_aligned_output_features_output_indices( out_features=__magic_name__ , out_indices=__magic_name__ , stage_names=self.stage_names ) class _A ( __lowercase ): lowercase__: List[str] = version.parse('''1.11''' ) @property def lowercase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowercase__ ( self : str ) -> float: """simple docstring""" return 1E-3
13
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { "Salesforce/codegen-350M-nl": "https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json", "Salesforce/codegen-350M-multi": "https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json", "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json", "Salesforce/codegen-2B-nl": "https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json", "Salesforce/codegen-2B-multi": "https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json", "Salesforce/codegen-2B-mono": "https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json", "Salesforce/codegen-6B-nl": "https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json", "Salesforce/codegen-6B-multi": "https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json", "Salesforce/codegen-6B-mono": "https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json", "Salesforce/codegen-16B-nl": "https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json", "Salesforce/codegen-16B-multi": "https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json", "Salesforce/codegen-16B-mono": "https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json", } class _A ( __lowercase ): lowercase__: str = '''codegen''' lowercase__: Optional[int] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Union[str, Any] , __magic_name__ : Optional[Any]=5_04_00 , __magic_name__ : Any=20_48 , __magic_name__ : List[str]=20_48 , __magic_name__ : Union[str, Any]=40_96 , __magic_name__ : Tuple=28 , __magic_name__ : Dict=16 , __magic_name__ : List[str]=64 , __magic_name__ : str=None , __magic_name__ : Tuple="gelu_new" , __magic_name__ : Tuple=0.0 , __magic_name__ : Tuple=0.0 , __magic_name__ : Dict=0.0 , __magic_name__ : Optional[Any]=1E-5 , __magic_name__ : int=0.02 , __magic_name__ : List[Any]=True , __magic_name__ : int=5_02_56 , __magic_name__ : int=5_02_56 , __magic_name__ : Any=False , **__magic_name__ : Optional[int] , ) -> int: """simple docstring""" __snake_case : List[str] = vocab_size __snake_case : Union[str, Any] = n_ctx __snake_case : int = n_positions __snake_case : str = n_embd __snake_case : Dict = n_layer __snake_case : List[Any] = n_head __snake_case : Any = n_inner __snake_case : str = rotary_dim __snake_case : List[str] = activation_function __snake_case : Tuple = resid_pdrop __snake_case : Dict = embd_pdrop __snake_case : int = attn_pdrop __snake_case : Tuple = layer_norm_epsilon __snake_case : Union[str, Any] = initializer_range __snake_case : Optional[Any] = use_cache __snake_case : Dict = bos_token_id __snake_case : Union[str, Any] = eos_token_id super().__init__( bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , tie_word_embeddings=__magic_name__ , **__magic_name__ ) class _A ( __lowercase ): def __init__( self : int , __magic_name__ : PretrainedConfig , __magic_name__ : str = "default" , __magic_name__ : List[PatchingSpec] = None , __magic_name__ : bool = False , ) -> Tuple: """simple docstring""" super().__init__(__magic_name__ , task=__magic_name__ , patching_specs=__magic_name__ , use_past=__magic_name__ ) if not getattr(self._config , """pad_token_id""" , __magic_name__ ): # TODO: how to do that better? __snake_case : List[str] = 0 @property def lowercase__ ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" __snake_case : Dict = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="""inputs""" ) __snake_case : Optional[Any] = {0: """batch""", 1: """past_sequence + sequence"""} else: __snake_case : Union[str, Any] = {0: """batch""", 1: """sequence"""} return common_inputs @property def lowercase__ ( self : Tuple ) -> int: """simple docstring""" return self._config.n_layer @property def lowercase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._config.n_head def lowercase__ ( self : Dict , __magic_name__ : PreTrainedTokenizer , __magic_name__ : int = -1 , __magic_name__ : int = -1 , __magic_name__ : bool = False , __magic_name__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: """simple docstring""" __snake_case : Tuple = super(__magic_name__ , self ).generate_dummy_inputs( __magic_name__ , batch_size=__magic_name__ , seq_length=__magic_name__ , is_pair=__magic_name__ , framework=__magic_name__ ) # We need to order the input in the way they appears in the forward() __snake_case : Union[str, Any] = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __snake_case , __snake_case : str = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __snake_case : Tuple = seqlen + 2 __snake_case : Union[str, Any] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __snake_case : List[str] = [ (torch.zeros(__magic_name__ ), torch.zeros(__magic_name__ )) for _ in range(self.num_layers ) ] __snake_case : Optional[int] = common_inputs["""attention_mask"""] if self.use_past: __snake_case : Union[str, Any] = ordered_inputs["""attention_mask"""].dtype __snake_case : Optional[Any] = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(__magic_name__ , __magic_name__ , dtype=__magic_name__ )] , dim=1 ) return ordered_inputs @property def lowercase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return 13
13
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ : Union[str, Any] = { '''configuration_blenderbot''': [ '''BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlenderbotConfig''', '''BlenderbotOnnxConfig''', ], '''tokenization_blenderbot''': ['''BlenderbotTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : List[Any] = ['''BlenderbotTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : List[str] = [ '''BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlenderbotForCausalLM''', '''BlenderbotForConditionalGeneration''', '''BlenderbotModel''', '''BlenderbotPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : int = [ '''TFBlenderbotForConditionalGeneration''', '''TFBlenderbotModel''', '''TFBlenderbotPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : List[str] = [ '''FlaxBlenderbotForConditionalGeneration''', '''FlaxBlenderbotModel''', '''FlaxBlenderbotPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys lowerCAmelCase__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
143
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __snake_case ( unittest.TestCase ): def __a ( self , __UpperCamelCase ) -> Dict: '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] , model_result['ss'] ): snake_case__ : Optional[int] = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(__UpperCamelCase ) def __a ( self ) -> Dict: '''simple docstring''' snake_case__ : List[str] = 'sshleifer/tiny-gpt2' snake_case__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : Optional[Any] = PyTorchBenchmark(__UpperCamelCase ) snake_case__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __a ( self ) -> Tuple: '''simple docstring''' snake_case__ : List[Any] = 'sgugger/tiny-distilbert-classification' snake_case__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , only_pretrain_model=__UpperCamelCase , ) snake_case__ : Dict = PyTorchBenchmark(__UpperCamelCase ) snake_case__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __a ( self ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Dict = 'sshleifer/tiny-gpt2' snake_case__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , torchscript=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : Optional[Any] = PyTorchBenchmark(__UpperCamelCase ) snake_case__ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' , 'Cant do half precision' ) def __a ( self ) -> int: '''simple docstring''' snake_case__ : Any = 'sshleifer/tiny-gpt2' snake_case__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , fpaa=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : Optional[int] = PyTorchBenchmark(__UpperCamelCase ) snake_case__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __a ( self ) -> List[Any]: '''simple docstring''' snake_case__ : Union[str, Any] = 'sshleifer/tiny-gpt2' snake_case__ : Optional[int] = AutoConfig.from_pretrained(__UpperCamelCase ) # set architectures equal to `None` snake_case__ : Union[str, Any] = None snake_case__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : List[Any] = PyTorchBenchmark(__UpperCamelCase , configs=[config] ) snake_case__ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __a ( self ) -> Any: '''simple docstring''' snake_case__ : Optional[Any] = 'sshleifer/tiny-gpt2' snake_case__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : str = PyTorchBenchmark(__UpperCamelCase ) snake_case__ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' , 'Can\'t do half precision' ) def __a ( self ) -> Tuple: '''simple docstring''' snake_case__ : List[str] = 'sshleifer/tiny-gpt2' snake_case__ : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=__UpperCamelCase , multi_process=__UpperCamelCase , ) snake_case__ : List[Any] = PyTorchBenchmark(__UpperCamelCase ) snake_case__ : int = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __a ( self ) -> int: '''simple docstring''' snake_case__ : Union[str, Any] = 'sshleifer/tiny-gpt2' snake_case__ : Optional[Any] = AutoConfig.from_pretrained(__UpperCamelCase ) snake_case__ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : List[str] = PyTorchBenchmark(__UpperCamelCase , configs=[config] ) snake_case__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __a ( self ) -> Dict: '''simple docstring''' snake_case__ : List[str] = 'sshleifer/tinier_bart' snake_case__ : List[str] = AutoConfig.from_pretrained(__UpperCamelCase ) snake_case__ : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : int = PyTorchBenchmark(__UpperCamelCase , configs=[config] ) snake_case__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __a ( self ) -> int: '''simple docstring''' snake_case__ : Any = 'sshleifer/tiny-gpt2' snake_case__ : Tuple = AutoConfig.from_pretrained(__UpperCamelCase ) snake_case__ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : int = PyTorchBenchmark(__UpperCamelCase , configs=[config] ) snake_case__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __a ( self ) -> Tuple: '''simple docstring''' snake_case__ : Optional[int] = 'sshleifer/tinier_bart' snake_case__ : Union[str, Any] = AutoConfig.from_pretrained(__UpperCamelCase ) snake_case__ : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) snake_case__ : Union[str, Any] = PyTorchBenchmark(__UpperCamelCase , configs=[config] ) snake_case__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __a ( self ) -> Optional[int]: '''simple docstring''' snake_case__ : Union[str, Any] = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: snake_case__ : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , save_to_csv=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__UpperCamelCase , 'inf_time.csv' ) , train_memory_csv_file=os.path.join(__UpperCamelCase , 'train_mem.csv' ) , inference_memory_csv_file=os.path.join(__UpperCamelCase , 'inf_mem.csv' ) , train_time_csv_file=os.path.join(__UpperCamelCase , 'train_time.csv' ) , env_info_csv_file=os.path.join(__UpperCamelCase , 'env.csv' ) , multi_process=__UpperCamelCase , ) snake_case__ : Union[str, Any] = PyTorchBenchmark(__UpperCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(__UpperCamelCase , 'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , 'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , 'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , 'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , 'env.csv' ) ).exists() ) def __a ( self ) -> Tuple: '''simple docstring''' snake_case__ : Optional[int] = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(__UpperCamelCase ): self.assertTrue(hasattr(__UpperCamelCase , 'sequential' ) ) self.assertTrue(hasattr(__UpperCamelCase , 'cumulative' ) ) self.assertTrue(hasattr(__UpperCamelCase , 'current' ) ) self.assertTrue(hasattr(__UpperCamelCase , 'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: snake_case__ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__UpperCamelCase , 'log.txt' ) , log_print=__UpperCamelCase , trace_memory_line_by_line=__UpperCamelCase , multi_process=__UpperCamelCase , ) snake_case__ : int = PyTorchBenchmark(__UpperCamelCase ) snake_case__ : Optional[Any] = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(__UpperCamelCase , 'log.txt' ) ).exists() )
143
1
"""simple docstring""" from __future__ import annotations def __lowerCamelCase ( a_ : Optional[Any] , a_ : Optional[Any] , a_ : int , a_ : Dict ) -> Dict: # noqa: E741 while r - l > 1: __SCREAMING_SNAKE_CASE :Union[str, Any] = (l + r) // 2 if v[m] >= key: __SCREAMING_SNAKE_CASE :Any = m else: __SCREAMING_SNAKE_CASE :List[Any] = m # noqa: E741 return r def __lowerCamelCase ( a_ : list[int] ) -> int: if len(a_ ) == 0: return 0 __SCREAMING_SNAKE_CASE :str = [0] * len(a_ ) __SCREAMING_SNAKE_CASE :Optional[Any] = 1 __SCREAMING_SNAKE_CASE :Optional[int] = v[0] for i in range(1 , len(a_ ) ): if v[i] < tail[0]: __SCREAMING_SNAKE_CASE :List[Any] = v[i] elif v[i] > tail[length - 1]: __SCREAMING_SNAKE_CASE :List[str] = v[i] length += 1 else: __SCREAMING_SNAKE_CASE :List[Any] = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
239
"""simple docstring""" from __future__ import annotations import math def __lowerCamelCase ( a_ : int , a_ : int , a_ : bool , a_ : list[int] , a_ : float ) -> int: if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if len(a_ ) == 0: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , a_ , a_ , a_ ) , minimax(depth + 1 , node_index * 2 + 1 , a_ , a_ , a_ ) , ) return min( minimax(depth + 1 , node_index * 2 , a_ , a_ , a_ ) , minimax(depth + 1 , node_index * 2 + 1 , a_ , a_ , a_ ) , ) def __lowerCamelCase ( ) -> None: __SCREAMING_SNAKE_CASE :Dict = [90, 23, 6, 33, 21, 65, 1_23, 3_44_23] __SCREAMING_SNAKE_CASE :Optional[int] = math.log(len(a_ ) , 2 ) print('''Optimal value : ''' , end='''''' ) print(minimax(0 , 0 , a_ , a_ , a_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
239
1
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class _a : def __init__( self: List[Any] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: List[Any]=14 , UpperCamelCase_: Dict=7 , UpperCamelCase_: str=True , UpperCamelCase_: str=True , UpperCamelCase_: Tuple=False , UpperCamelCase_: List[Any]=True , UpperCamelCase_: int=99 , UpperCamelCase_: int=32 , UpperCamelCase_: str=4 , UpperCamelCase_: List[Any]=4 , UpperCamelCase_: List[Any]=4 , UpperCamelCase_: Optional[int]=37 , UpperCamelCase_: Any="gelu" , UpperCamelCase_: Optional[int]=0.1 , UpperCamelCase_: Any=0.1 , UpperCamelCase_: Tuple=512 , UpperCamelCase_: int=0.02 , ) -> Tuple: """simple docstring""" 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__ = rotary_dim 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__ = initializer_range lowercase__ = None lowercase__ = vocab_size - 1 lowercase__ = vocab_size - 1 lowercase__ = vocab_size - 1 def lowerCamelCase_ ( self: str ) -> str: """simple docstring""" 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__ = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCamelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowerCamelCase_ ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" lowercase__ = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: Optional[int] , UpperCamelCase_: List[Any] , UpperCamelCase_: int , UpperCamelCase_: int ) -> Union[str, Any]: """simple docstring""" lowercase__ = 20 lowercase__ = model_class_name(UpperCamelCase_ ) lowercase__ = model.init_cache(input_ids.shape[0] , UpperCamelCase_ ) lowercase__ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) lowercase__ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowercase__ = model( input_ids[:, :-1] , attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , position_ids=UpperCamelCase_ , ) lowercase__ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase__ = model( input_ids[:, -1:] , attention_mask=UpperCamelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCamelCase_ , ) lowercase__ = model(UpperCamelCase_ ) lowercase__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'Max diff is {diff}' ) def lowerCamelCase_ ( self: Dict , UpperCamelCase_: List[Any] , UpperCamelCase_: Any , UpperCamelCase_: str , UpperCamelCase_: Tuple ) -> Any: """simple docstring""" lowercase__ = 20 lowercase__ = model_class_name(UpperCamelCase_ ) lowercase__ = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) lowercase__ = model.init_cache(input_ids.shape[0] , UpperCamelCase_ ) lowercase__ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowercase__ = model( input_ids[:, :-1] , attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , position_ids=UpperCamelCase_ , ) lowercase__ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase__ = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCamelCase_ , position_ids=UpperCamelCase_ , ) lowercase__ = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ ) lowercase__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'Max diff is {diff}' ) @require_flax class _a ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): _lowercase : List[Any] = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () _lowercase : List[Any] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowerCamelCase_ ( self: Tuple ) -> Optional[int]: """simple docstring""" lowercase__ = FlaxGPTJModelTester(self ) def lowerCamelCase_ ( self: Any ) -> Tuple: """simple docstring""" for model_class_name in self.all_model_classes: lowercase__ , lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase_ ( self: int ) -> Optional[Any]: """simple docstring""" for model_class_name in self.all_model_classes: lowercase__ , lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) @tooslow def lowerCamelCase_ ( self: Optional[int] ) -> List[str]: """simple docstring""" lowercase__ = GPTaTokenizer.from_pretrained('''gpt2''' , pad_token='''<|endoftext|>''' , padding_side='''left''' ) lowercase__ = tokenizer(['''Hello this is a long string''', '''Hey'''] , return_tensors='''np''' , padding=UpperCamelCase_ , truncation=UpperCamelCase_ ) lowercase__ = FlaxGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B''' ) lowercase__ = False lowercase__ = model.config.eos_token_id lowercase__ = jax.jit(model.generate ) lowercase__ = jit_generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , pad_token_id=tokenizer.pad_token_id ).sequences lowercase__ = tokenizer.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ ) lowercase__ = [ '''Hello this is a long string of text.\n\nI\'m trying to get the text of the''', '''Hey, I\'m a little late to the party. I\'m going to''', ] self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) @is_pt_flax_cross_test def lowerCamelCase_ ( self: List[str] ) -> str: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowercase__ = model_class.__name__[4:] # Skip the "Flax" at the beginning lowercase__ = getattr(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ , lowercase__ = pt_inputs['''input_ids'''].shape lowercase__ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCamelCase_ ): lowercase__ = 0 lowercase__ = 1 lowercase__ = 0 lowercase__ = 1 lowercase__ = pt_model_class(UpperCamelCase_ ).eval() lowercase__ = model_class(UpperCamelCase_ , dtype=jnp.floataa ) lowercase__ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCamelCase_ ) lowercase__ = fx_state with torch.no_grad(): lowercase__ = pt_model(**UpperCamelCase_ ).to_tuple() lowercase__ = fx_model(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCamelCase_ ) lowercase__ = model_class.from_pretrained(UpperCamelCase_ , from_pt=UpperCamelCase_ ) lowercase__ = fx_model_loaded(**UpperCamelCase_ ).to_tuple() self.assertEqual( len(UpperCamelCase_ ) , len(UpperCamelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output_loaded, pt_output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def lowerCamelCase_ ( self: Dict ) -> str: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowercase__ = model_class.__name__[4:] # Skip the "Flax" at the beginning lowercase__ = getattr(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = pt_model_class(UpperCamelCase_ ).eval() lowercase__ = model_class(UpperCamelCase_ , dtype=jnp.floataa ) lowercase__ = load_flax_weights_in_pytorch_model(UpperCamelCase_ , fx_model.params ) lowercase__ , lowercase__ = pt_inputs['''input_ids'''].shape lowercase__ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCamelCase_ ): lowercase__ = 0 lowercase__ = 1 lowercase__ = 0 lowercase__ = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): lowercase__ = pt_model(**UpperCamelCase_ ).to_tuple() lowercase__ = fx_model(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCamelCase_ ) lowercase__ = pt_model_class.from_pretrained(UpperCamelCase_ , from_flax=UpperCamelCase_ ) with torch.no_grad(): lowercase__ = pt_model_loaded(**UpperCamelCase_ ).to_tuple() self.assertEqual( len(UpperCamelCase_ ) , len(UpperCamelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def lowerCamelCase_ ( self: Optional[Any] ) -> int: """simple docstring""" for model_class_name in self.all_model_classes: lowercase__ = model_class_name.from_pretrained('''EleutherAI/gpt-j-6B''' ) lowercase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCamelCase_ )
110
from __future__ import annotations def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = 0 lowercase__ = len(SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: lowercase__ = i + 1 else: lowercase__ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
110
1
from math import factorial, radians def _UpperCamelCase (a__ :float , a__ :int = 18 , a__ :int = 10 ): """simple docstring""" UpperCamelCase__ = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians UpperCamelCase__ = radians(a__ ) UpperCamelCase__ = angle_in_radians UpperCamelCase__ = 3 UpperCamelCase__ = -1 for _ in range(a__ ): result += (b * (angle_in_radians**a)) / factorial(a__ ) UpperCamelCase__ = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(a__ , a__ ) if __name__ == "__main__": __import__("doctest").testmod()
87
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase__ = { "configuration_swiftformer": [ "SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SwiftFormerConfig", "SwiftFormerOnnxConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ "SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "SwiftFormerForImageClassification", "SwiftFormerModel", "SwiftFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
87
1
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin A__: Any = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : List[str] = ReformerTokenizer __UpperCamelCase : Any = ReformerTokenizerFast __UpperCamelCase : str = True __UpperCamelCase : Dict = False __UpperCamelCase : Any = True def __UpperCAmelCase ( self :Any ) -> Any: '''simple docstring''' super().setUp() _a : Union[str, Any] =ReformerTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self :Optional[int] ) -> Dict: '''simple docstring''' _a : List[str] ="""<s>""" _a : List[str] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 1_0_0_0 ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0 ) def __UpperCAmelCase ( self :Tuple ) -> Optional[Any]: '''simple docstring''' if not self.test_rust_tokenizer: return _a : Tuple =self.get_tokenizer() _a : List[str] =self.get_rust_tokenizer() _a : List[Any] ="""I was born in 92000, and this is falsé.""" _a : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) _a : str =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Dict =tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : str =self.get_rust_tokenizer() _a : int =tokenizer.encode(SCREAMING_SNAKE_CASE ) _a : Optional[int] =rust_tokenizer.encode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :str=1_5 ) -> Union[str, Any]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _a : Dict =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # Simple input _a : List[Any] ="""This is a simple input""" _a : Union[str, Any] =["""This is a simple input 1""", """This is a simple input 2"""] _a : Tuple =("""This is a simple input""", """This is a pair""") _a : str =[ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' pass def __UpperCAmelCase ( self :Any ) -> Union[str, Any]: '''simple docstring''' _a : List[str] =ReformerTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =tokenizer.tokenize("""This is a test""" ) self.assertListEqual(SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] , ) _a : Tuple =tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _a : List[Any] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) self.assertListEqual( SCREAMING_SNAKE_CASE , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] , ) _a : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) self.assertListEqual( SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __UpperCAmelCase ( self :Optional[int] ) -> List[str]: '''simple docstring''' return ReformerTokenizer.from_pretrained("""google/reformer-crime-and-punishment""" ) @slow def __UpperCAmelCase ( self :Any ) -> int: '''simple docstring''' _a : Any ="""Hello World!""" _a : List[str] =[1_2_6, 3_2, 2_6_2, 1_5_2, 3_8, 7_2, 2_8_7] self.assertListEqual(SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE ) ) @slow def __UpperCAmelCase ( self :Optional[Any] ) -> List[Any]: '''simple docstring''' _a : Tuple =( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) _a : Optional[Any] =[ 1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 3_5, 2_8, 2_7_5, 3, 2_5_9, 2_9_7, 2_6_0, 8_4, 4, 3_5, 1_1_0, 4_4, 8, 2_5_9, 9_1, 2_6_8, 2_1, 1_1, 2_0_9, 2_7_4, 1_0_9, 2_6_6, 2_7_7, 1_1_7, 8_6, 9_3, 3_1_5, 2_5_8, 2_7_8, 2_5_8, 2_7_7, 2_5_8, 0, 2_5_8, 2_8_8, 2_5_8, 3_1_9, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 2_8_7, 2_5_8, 3_1_5, 2_5_8, 2_8_9, 2_5_8, 2_7_8, 9_9, 2_6_9, 2_6_6, 2_6_2, 8, 2_5_9, 2_4_1, 4, 2_1_7, 2_3_0, 2_6_8, 2_6_6, 5_5, 1_6_8, 1_0_6, 7_5, 1_9_3, 2_6_6, 2_2_3, 2_7, 4_9, 2_6, 2_8_2, 2_5, 2_6_4, 2_9_9, 1_9, 2_6, 0, 2_5_8, 2_7_7, 1_1_7, 8_6, 9_3, 1_7_6, 1_8_3, 2_7_0, 1_1, 2_6_2, 4_2, 6_1, 2_6_5, ] self.assertListEqual(SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE ) ) @require_torch @slow def __UpperCAmelCase ( self :str ) -> List[str]: '''simple docstring''' import torch from transformers import ReformerConfig, ReformerModel # Build sequence _a : Dict =list(self.big_tokenizer.get_vocab().keys() )[:1_0] _a : Dict =""" """.join(SCREAMING_SNAKE_CASE ) _a : Optional[int] =self.big_tokenizer.encode_plus(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) _a : Optional[int] =self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="""pt""" ) _a : str =ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) _a : Union[str, Any] =encoded_sequence["""input_ids"""].shape _a : List[str] =ReformerModel(SCREAMING_SNAKE_CASE ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**SCREAMING_SNAKE_CASE ) model(**SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :int ) -> str: '''simple docstring''' # fmt: off _a : Any ={"""input_ids""": [[1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 7, 5_1, 2_7_9, 5_8, 7, 7_6, 2_5, 6_9, 2_7_8], [1_4_0, 2_4_3, 2_6_4, 1_3_4, 1_7, 2_6_7, 7_7, 2_6_3, 2_2, 2_6_2, 2_9_7, 2_5_8, 3_0_4, 1_7_7, 2_7_9, 2_6_6, 1_4, 8_9, 1_3, 3_5, 2_6_1, 2_9_9, 2_7_2, 1_3_7, 2_7_5, 2_7_8]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 _a : str =[ """This is a very simple sentence.""", """The quick brown fox jumps over the lazy dog.""", ] self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE , model_name="""google/reformer-crime-and-punishment""" , revision="""0e6c3decb8211d49bf881013425dc8b0448b3f5a""" , padding=SCREAMING_SNAKE_CASE , sequences=SCREAMING_SNAKE_CASE , )
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
"""simple docstring""" import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCAmelCase_ ( unittest.TestCase): @require_torch def _UpperCamelCase ( self : List[str] ) -> Dict: _UpperCamelCase = pipeline( task='''zero-shot-audio-classification''' , model='''hf-internal-testing/tiny-clap-htsat-unfused''' ) _UpperCamelCase = load_dataset('''ashraq/esc50''' ) _UpperCamelCase = dataset['train']['audio'][-1]['array'] _UpperCamelCase = audio_classifier(__UpperCamelCase , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(__UpperCamelCase ) , [{'''score''': 0.5_0_1, '''label''': '''Sound of a dog'''}, {'''score''': 0.4_9_9, '''label''': '''Sound of vaccum cleaner'''}] , ) @unittest.skip('''No models are available in TF''' ) def _UpperCamelCase ( self : int ) -> Optional[int]: pass @slow @require_torch def _UpperCamelCase ( self : int ) -> Union[str, Any]: _UpperCamelCase = pipeline( task='''zero-shot-audio-classification''' , model='''laion/clap-htsat-unfused''' , ) # This is an audio of a dog _UpperCamelCase = load_dataset('''ashraq/esc50''' ) _UpperCamelCase = dataset['train']['audio'][-1]['array'] _UpperCamelCase = audio_classifier(__UpperCamelCase , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(__UpperCamelCase ) , [ {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''}, {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''}, ] , ) _UpperCamelCase = audio_classifier([audio] * 5 , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(__UpperCamelCase ) , [ [ {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''}, {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 , ) _UpperCamelCase = audio_classifier( [audio] * 5 , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] , batch_size=5 ) self.assertEqual( nested_simplify(__UpperCamelCase ) , [ [ {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''}, {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 , ) @unittest.skip('''No models are available in TF''' ) def _UpperCamelCase ( self : str ) -> int: pass
367
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) def lowercase ( a__ : str ) -> int: _UpperCamelCase = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: _UpperCamelCase = [144, 192, 240] _UpperCamelCase = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: _UpperCamelCase = [96, 120, 144] _UpperCamelCase = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: _UpperCamelCase = [64, 80, 96] _UpperCamelCase = [16, 16, 24, 48, 64, 80, 320] _UpperCamelCase = 0.05 _UpperCamelCase = 2.0 if mobilevit_name.startswith('''deeplabv3_''' ): _UpperCamelCase = 512 _UpperCamelCase = 16 _UpperCamelCase = 21 _UpperCamelCase = '''pascal-voc-id2label.json''' else: _UpperCamelCase = 1000 _UpperCamelCase = '''imagenet-1k-id2label.json''' _UpperCamelCase = '''huggingface/label-files''' _UpperCamelCase = json.load(open(hf_hub_download(a__ , a__ , repo_type='''dataset''' ) , '''r''' ) ) _UpperCamelCase = {int(a__ ): v for k, v in idalabel.items()} _UpperCamelCase = idalabel _UpperCamelCase = {v: k for k, v in idalabel.items()} return config def lowercase ( a__ : Union[str, Any] , a__ : Optional[int]=False ) -> int: for i in range(1 , 6 ): if F'''layer_{i}.''' in name: _UpperCamelCase = name.replace(F'''layer_{i}.''' , F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: _UpperCamelCase = name.replace('''conv_1.''' , '''conv_stem.''' ) if ".block." in name: _UpperCamelCase = name.replace('''.block.''' , '''.''' ) if "exp_1x1" in name: _UpperCamelCase = name.replace('''exp_1x1''' , '''expand_1x1''' ) if "red_1x1" in name: _UpperCamelCase = name.replace('''red_1x1''' , '''reduce_1x1''' ) if ".local_rep.conv_3x3." in name: _UpperCamelCase = name.replace('''.local_rep.conv_3x3.''' , '''.conv_kxk.''' ) if ".local_rep.conv_1x1." in name: _UpperCamelCase = name.replace('''.local_rep.conv_1x1.''' , '''.conv_1x1.''' ) if ".norm." in name: _UpperCamelCase = name.replace('''.norm.''' , '''.normalization.''' ) if ".conv." in name: _UpperCamelCase = name.replace('''.conv.''' , '''.convolution.''' ) if ".conv_proj." in name: _UpperCamelCase = name.replace('''.conv_proj.''' , '''.conv_projection.''' ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: _UpperCamelCase = name.replace(F'''.{i}.{j}.''' , F'''.{i}.layer.{j}.''' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: _UpperCamelCase = name.replace(F'''.{i}.{j}.''' , F'''.{i}.''' ) if "expand_1x1" in name: _UpperCamelCase = name.replace('''expand_1x1''' , '''downsampling_layer.expand_1x1''' ) if "conv_3x3" in name: _UpperCamelCase = name.replace('''conv_3x3''' , '''downsampling_layer.conv_3x3''' ) if "reduce_1x1" in name: _UpperCamelCase = name.replace('''reduce_1x1''' , '''downsampling_layer.reduce_1x1''' ) for i in range(2 , 5 ): if F'''.global_rep.{i}.weight''' in name: _UpperCamelCase = name.replace(F'''.global_rep.{i}.weight''' , '''.layernorm.weight''' ) if F'''.global_rep.{i}.bias''' in name: _UpperCamelCase = name.replace(F'''.global_rep.{i}.bias''' , '''.layernorm.bias''' ) if ".global_rep." in name: _UpperCamelCase = name.replace('''.global_rep.''' , '''.transformer.''' ) if ".pre_norm_mha.0." in name: _UpperCamelCase = name.replace('''.pre_norm_mha.0.''' , '''.layernorm_before.''' ) if ".pre_norm_mha.1.out_proj." in name: _UpperCamelCase = name.replace('''.pre_norm_mha.1.out_proj.''' , '''.attention.output.dense.''' ) if ".pre_norm_ffn.0." in name: _UpperCamelCase = name.replace('''.pre_norm_ffn.0.''' , '''.layernorm_after.''' ) if ".pre_norm_ffn.1." in name: _UpperCamelCase = name.replace('''.pre_norm_ffn.1.''' , '''.intermediate.dense.''' ) if ".pre_norm_ffn.4." in name: _UpperCamelCase = name.replace('''.pre_norm_ffn.4.''' , '''.output.dense.''' ) if ".transformer." in name: _UpperCamelCase = name.replace('''.transformer.''' , '''.transformer.layer.''' ) if ".aspp_layer." in name: _UpperCamelCase = name.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in name: _UpperCamelCase = name.replace('''.aspp_pool.''' , '''.''' ) if "seg_head." in name: _UpperCamelCase = name.replace('''seg_head.''' , '''segmentation_head.''' ) if "segmentation_head.classifier.classifier." in name: _UpperCamelCase = name.replace('''segmentation_head.classifier.classifier.''' , '''segmentation_head.classifier.''' ) if "classifier.fc." in name: _UpperCamelCase = name.replace('''classifier.fc.''' , '''classifier.''' ) elif (not base_model) and ("segmentation_head." not in name): _UpperCamelCase = '''mobilevit.''' + name return name def lowercase ( a__ : Union[str, Any] , a__ : List[Any] , a__ : Tuple=False ) -> Optional[Any]: if base_model: _UpperCamelCase = '''''' else: _UpperCamelCase = '''mobilevit.''' for key in orig_state_dict.copy().keys(): _UpperCamelCase = orig_state_dict.pop(a__ ) if key[:8] == "encoder.": _UpperCamelCase = key[8:] if "qkv" in key: _UpperCamelCase = key.split('''.''' ) _UpperCamelCase = int(key_split[0][6:] ) - 1 _UpperCamelCase = int(key_split[3] ) _UpperCamelCase = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) _UpperCamelCase = layer.transformer.layer[transformer_num].attention.attention.all_head_size _UpperCamelCase = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: _UpperCamelCase = val[:dim, :] _UpperCamelCase = val[dim : dim * 2, :] _UpperCamelCase = val[-dim:, :] else: _UpperCamelCase = val[:dim] _UpperCamelCase = val[dim : dim * 2] _UpperCamelCase = val[-dim:] else: _UpperCamelCase = val return orig_state_dict def lowercase ( ) -> Dict: _UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _UpperCamelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) return im @torch.no_grad() def lowercase ( a__ : Dict , a__ : Optional[int] , a__ : Any , a__ : Tuple=False ) -> Any: _UpperCamelCase = get_mobilevit_config(a__ ) # load original state_dict _UpperCamelCase = torch.load(a__ , map_location='''cpu''' ) # load 🤗 model if mobilevit_name.startswith('''deeplabv3_''' ): _UpperCamelCase = MobileViTForSemanticSegmentation(a__ ).eval() else: _UpperCamelCase = MobileViTForImageClassification(a__ ).eval() _UpperCamelCase = convert_state_dict(a__ , a__ ) model.load_state_dict(a__ ) # Check outputs on an image, prepared by MobileViTImageProcessor _UpperCamelCase = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) _UpperCamelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) _UpperCamelCase = model(**a__ ) _UpperCamelCase = outputs.logits if mobilevit_name.startswith('''deeplabv3_''' ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": _UpperCamelCase = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": _UpperCamelCase = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": _UpperCamelCase = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] , a__ , atol=1e-4 ) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": _UpperCamelCase = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": _UpperCamelCase = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": _UpperCamelCase = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] , a__ , atol=1e-4 ) Path(a__ ).mkdir(exist_ok=a__ ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(a__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(a__ ) if push_to_hub: _UpperCamelCase = { '''mobilevit_s''': '''mobilevit-small''', '''mobilevit_xs''': '''mobilevit-x-small''', '''mobilevit_xxs''': '''mobilevit-xx-small''', '''deeplabv3_mobilevit_s''': '''deeplabv3-mobilevit-small''', '''deeplabv3_mobilevit_xs''': '''deeplabv3-mobilevit-x-small''', '''deeplabv3_mobilevit_xxs''': '''deeplabv3-mobilevit-xx-small''', } print('''Pushing to the hub...''' ) _UpperCamelCase = model_mapping[mobilevit_name] image_processor.push_to_hub(a__ , organization='''apple''' ) model.push_to_hub(a__ , organization='''apple''' ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) UpperCAmelCase = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
54
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class A_ ( lowerCAmelCase_ ): @staticmethod @abstractmethod def lowercase ( snake_case_ : ArgumentParser ): raise NotImplementedError() @abstractmethod def lowercase ( self : Optional[Any] ): raise NotImplementedError()
22
import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList A__ = ['''\nclass''', '''\ndef''', '''\n#''', '''\n@''', '''\nprint''', '''\nif'''] class a ( __lowerCamelCase ): def __init__( self :str ,__lowercase :Dict ,__lowercase :str ,__lowercase :Any=None ,__lowercase :Union[str, Any]=1 ): snake_case__ : Optional[int] = tokenizer snake_case__ : List[Any] = dataset snake_case__ : Any = len(__lowercase ) if n_tasks is None else n_tasks snake_case__ : List[Any] = n_copies def __iter__( self :Tuple ): snake_case__ : Union[str, Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip() ) snake_case__ : Optional[int] = self.tokenizer(__lowercase ,padding=__lowercase ,return_tensors='''pt''' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a ( __lowerCamelCase ): def __init__( self :Union[str, Any] ,__lowercase :List[Any] ,__lowercase :int ,__lowercase :List[str] ): snake_case__ : List[str] = start_length snake_case__ : Any = eof_strings snake_case__ : Optional[Any] = tokenizer def __call__( self :str ,__lowercase :str ,__lowercase :Any ,**__lowercase :Optional[int] ): snake_case__ : Tuple = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) snake_case__ : Union[str, Any] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__lowercase ) def _lowerCAmelCase ( __lowerCAmelCase ) -> List[Any]: """simple docstring""" snake_case__ : List[Any] = re.split('''(%s)''' % '''|'''.join(__lowerCAmelCase ) , __lowerCAmelCase ) # last string should be "" return "".join(string_list[:-2] ) def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=20 , **__lowerCAmelCase ) -> List[Any]: """simple docstring""" snake_case__ : Optional[int] = defaultdict(__lowerCAmelCase ) # dict of list of generated tokens for step, batch in tqdm(enumerate(__lowerCAmelCase ) ): with torch.no_grad(): snake_case__ : List[Any] = batch['''ids'''].shape[-1] snake_case__ : str = accelerator.unwrap_model(__lowerCAmelCase ).generate( input_ids=batch['''ids'''][:, : batch['''input_len''']] , num_return_sequences=__lowerCAmelCase , **__lowerCAmelCase ) # each task is generated batch_size times snake_case__ : str = batch['''task_id'''].repeat(__lowerCAmelCase ) snake_case__ : Optional[int] = accelerator.pad_across_processes( __lowerCAmelCase , dim=1 , pad_index=tokenizer.pad_token_id ) snake_case__ , snake_case__ : Any = accelerator.gather((generated_tokens, generated_tasks) ) snake_case__ : Union[str, Any] = generated_tokens.cpu().numpy() snake_case__ : Optional[Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(__lowerCAmelCase , __lowerCAmelCase ): gen_token_dict[task].append(__lowerCAmelCase ) snake_case__ : List[Any] = [[] for _ in range(__lowerCAmelCase )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: snake_case__ : int = tokenizer.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) code_gens[task].append(remove_last_block(__lowerCAmelCase ) ) return code_gens def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" snake_case__ : List[str] = HfArgumentParser(__lowerCAmelCase ) snake_case__ : Optional[Any] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric snake_case__ : Union[str, Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing snake_case__ : Union[str, Any] = '''false''' if args.num_workers is None: snake_case__ : Union[str, Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate snake_case__ : Dict = Accelerator() set_seed(args.seed , device_specific=__lowerCAmelCase ) # Load model and tokenizer snake_case__ : str = AutoTokenizer.from_pretrained(args.model_ckpt ) snake_case__ : List[str] = tokenizer.eos_token snake_case__ : Optional[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings snake_case__ : List[Any] = { '''do_sample''': args.do_sample, '''temperature''': args.temperature, '''max_new_tokens''': args.max_new_tokens, '''top_p''': args.top_p, '''top_k''': args.top_k, '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0 , __lowerCAmelCase , __lowerCAmelCase )] ), } # Load evaluation dataset and metric snake_case__ : List[str] = load_dataset('''openai_humaneval''' ) snake_case__ : str = load_metric('''code_eval''' ) snake_case__ : List[Any] = args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] ) snake_case__ : str = args.n_samples // args.batch_size snake_case__ : Tuple = TokenizedDataset(__lowerCAmelCase , human_eval['''test'''] , n_copies=__lowerCAmelCase , n_tasks=__lowerCAmelCase ) # do not confuse args.batch_size, which is actually the num_return_sequences snake_case__ : Tuple = DataLoader(__lowerCAmelCase , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: snake_case__ : Optional[Any] = code_eval_metric.compute(references=[''''''] , predictions=[['''''']] ) except ValueError as exception: print( '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`''' ''' flag to enable code evaluation.''' ) raise exception snake_case__ , snake_case__ : Optional[Any] = accelerator.prepare(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ : Dict = complete_code( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , n_tasks=__lowerCAmelCase , batch_size=args.batch_size , **__lowerCAmelCase , ) if accelerator.is_main_process: snake_case__ : Optional[Any] = [] for task in tqdm(range(__lowerCAmelCase ) ): snake_case__ : str = human_eval['''test'''][task]['''test'''] snake_case__ : int = f"""check({human_eval['test'][task]['entry_point']})""" references.append('''\n''' + test_func + '''\n''' + entry_point ) # Evaluate completions with "code_eval" metric snake_case__ , snake_case__ : Any = code_eval_metric.compute( references=__lowerCAmelCase , predictions=__lowerCAmelCase , num_workers=args.num_workers ) print(f"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , '''w''' ) as fp: json.dump(__lowerCAmelCase , __lowerCAmelCase ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
230
0
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL _A : str = logging.get_logger(__name__) def _a ( UpperCAmelCase ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(UpperCAmelCase , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(UpperCAmelCase , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(UpperCAmelCase ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): _UpperCAmelCase : Optional[int] = ["pixel_values"] def __init__( self : int , A : bool = True , A : Dict[str, int] = None , A : PILImageResampling = PILImageResampling.BILINEAR , A : bool = True , A : Dict[str, int] = None , A : bool = True , A : Union[int, float] = 1 / 2_5_5 , A : bool = True , A : bool = True , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , **A : List[str] , ) ->None: super().__init__(**A ) lowerCamelCase__ : str = size if size is not None else {'''shortest_edge''': 2_5_6} lowerCamelCase__ : Optional[Any] = get_size_dict(A , default_to_square=A ) lowerCamelCase__ : Dict = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} lowerCamelCase__ : Union[str, Any] = get_size_dict(A , param_name='''crop_size''' ) lowerCamelCase__ : int = do_resize lowerCamelCase__ : int = size lowerCamelCase__ : Tuple = do_center_crop lowerCamelCase__ : int = crop_size lowerCamelCase__ : List[Any] = resample lowerCamelCase__ : Any = do_rescale lowerCamelCase__ : Any = rescale_factor lowerCamelCase__ : str = offset lowerCamelCase__ : Optional[int] = do_normalize lowerCamelCase__ : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase__ : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __lowerCamelCase ( self : Optional[Any] , A : np.ndarray , A : Dict[str, int] , A : PILImageResampling = PILImageResampling.BILINEAR , A : Optional[Union[str, ChannelDimension]] = None , **A : str , ) ->np.ndarray: lowerCamelCase__ : Any = get_size_dict(A , default_to_square=A ) if "shortest_edge" in size: lowerCamelCase__ : Dict = get_resize_output_image_size(A , size['''shortest_edge'''] , default_to_square=A ) elif "height" in size and "width" in size: lowerCamelCase__ : List[Any] = (size['''height'''], size['''width''']) else: raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(A , size=A , resample=A , data_format=A , **A ) def __lowerCamelCase ( self : Optional[int] , A : np.ndarray , A : Dict[str, int] , A : Optional[Union[str, ChannelDimension]] = None , **A : Dict , ) ->np.ndarray: lowerCamelCase__ : Optional[Any] = get_size_dict(A ) if "height" not in size or "width" not in size: raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(A , size=(size['''height'''], size['''width''']) , data_format=A , **A ) def __lowerCamelCase ( self : List[str] , A : np.ndarray , A : Union[int, float] , A : bool = True , A : Optional[Union[str, ChannelDimension]] = None , **A : List[Any] , ) ->Optional[Any]: lowerCamelCase__ : Optional[int] = image.astype(np.floataa ) if offset: lowerCamelCase__ : int = image - (scale / 2) return rescale(A , scale=A , data_format=A , **A ) def __lowerCamelCase ( self : List[str] , A : np.ndarray , A : Union[float, List[float]] , A : Union[float, List[float]] , A : Optional[Union[str, ChannelDimension]] = None , **A : List[str] , ) ->np.ndarray: return normalize(A , mean=A , std=A , data_format=A , **A ) def __lowerCamelCase ( self : Any , A : ImageInput , A : bool = None , A : Dict[str, int] = None , A : PILImageResampling = None , A : bool = None , A : Dict[str, int] = None , A : bool = None , A : float = None , A : bool = None , A : bool = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , A : Optional[ChannelDimension] = ChannelDimension.FIRST , ) ->np.ndarray: if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. lowerCamelCase__ : Optional[int] = to_numpy_array(A ) if do_resize: lowerCamelCase__ : Union[str, Any] = self.resize(image=A , size=A , resample=A ) if do_center_crop: lowerCamelCase__ : int = self.center_crop(A , size=A ) if do_rescale: lowerCamelCase__ : Tuple = self.rescale(image=A , scale=A , offset=A ) if do_normalize: lowerCamelCase__ : Dict = self.normalize(image=A , mean=A , std=A ) lowerCamelCase__ : Dict = to_channel_dimension_format(A , A ) return image def __lowerCamelCase ( self : List[str] , A : ImageInput , A : bool = None , A : Dict[str, int] = None , A : PILImageResampling = None , A : bool = None , A : Dict[str, int] = None , A : bool = None , A : float = None , A : bool = None , A : bool = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[str, TensorType]] = None , A : ChannelDimension = ChannelDimension.FIRST , **A : Optional[int] , ) ->PIL.Image.Image: lowerCamelCase__ : List[Any] = do_resize if do_resize is not None else self.do_resize lowerCamelCase__ : str = resample if resample is not None else self.resample lowerCamelCase__ : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase__ : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase__ : Any = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase__ : Dict = offset if offset is not None else self.offset lowerCamelCase__ : List[str] = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase__ : str = image_mean if image_mean is not None else self.image_mean lowerCamelCase__ : Dict = image_std if image_std is not None else self.image_std lowerCamelCase__ : int = size if size is not None else self.size lowerCamelCase__ : Union[str, Any] = get_size_dict(A , default_to_square=A ) lowerCamelCase__ : List[Any] = crop_size if crop_size is not None else self.crop_size lowerCamelCase__ : int = get_size_dict(A , param_name='''crop_size''' ) if not valid_images(A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) lowerCamelCase__ : Union[str, Any] = make_batched(A ) lowerCamelCase__ : Optional[Any] = [ [ self._preprocess_image( image=A , do_resize=A , size=A , resample=A , do_center_crop=A , crop_size=A , do_rescale=A , rescale_factor=A , offset=A , do_normalize=A , image_mean=A , image_std=A , data_format=A , ) for img in video ] for video in videos ] lowerCamelCase__ : List[str] = {'''pixel_values''': videos} return BatchFeature(data=A , tensor_type=A )
265
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _A : Tuple = logging.get_logger(__name__) _A : List[str] = { '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 __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,lowerCAmelCase_ ): _UpperCAmelCase : Dict = "nat" _UpperCAmelCase : Tuple = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : List[Any] , A : Union[str, Any]=4 , A : str=3 , A : List[Any]=6_4 , A : Optional[Any]=[3, 4, 6, 5] , A : int=[2, 4, 8, 1_6] , A : Optional[int]=7 , A : List[Any]=3.0 , A : str=True , A : str=0.0 , A : Any=0.0 , A : int=0.1 , A : Tuple="gelu" , A : List[Any]=0.02 , A : str=1e-5 , A : Optional[int]=0.0 , A : Optional[Any]=None , A : Dict=None , **A : str , ) ->Union[str, Any]: super().__init__(**A ) lowerCamelCase__ : Any = patch_size lowerCamelCase__ : Optional[Any] = num_channels lowerCamelCase__ : Any = embed_dim lowerCamelCase__ : str = depths lowerCamelCase__ : Union[str, Any] = len(A ) lowerCamelCase__ : int = num_heads lowerCamelCase__ : Optional[int] = kernel_size lowerCamelCase__ : Optional[int] = mlp_ratio lowerCamelCase__ : List[Any] = qkv_bias lowerCamelCase__ : Tuple = hidden_dropout_prob lowerCamelCase__ : List[str] = attention_probs_dropout_prob lowerCamelCase__ : List[Any] = drop_path_rate lowerCamelCase__ : Union[str, Any] = hidden_act lowerCamelCase__ : Union[str, Any] = layer_norm_eps lowerCamelCase__ : List[Any] = 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 lowerCamelCase__ : str = int(embed_dim * 2 ** (len(A ) - 1) ) lowerCamelCase__ : Dict = layer_scale_init_value lowerCamelCase__ : Dict = ['''stem'''] + [F"stage{idx}" for idx in range(1 , len(A ) + 1 )] lowerCamelCase__ , lowerCamelCase__ : str = get_aligned_output_features_output_indices( out_features=A , out_indices=A , stage_names=self.stage_names )
265
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase : Tuple = { '''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 lowerCAmelCase ( __a ): '''simple docstring''' _A : int = '''roberta''' def __init__( self : Union[str, Any] , __a : Optional[Any]=50265 , __a : int=768 , __a : Optional[int]=12 , __a : int=12 , __a : List[Any]=3072 , __a : int="gelu" , __a : List[Any]=0.1 , __a : str=0.1 , __a : Optional[int]=512 , __a : str=2 , __a : str=0.02 , __a : Dict=1E-12 , __a : int=1 , __a : Union[str, Any]=0 , __a : Union[str, Any]=2 , __a : List[str]="absolute" , __a : Tuple=True , __a : Any=None , **__a : Optional[int] , ) -> Optional[int]: """simple docstring""" super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __lowercase : Any = vocab_size __lowercase : int = hidden_size __lowercase : Dict = num_hidden_layers __lowercase : List[str] = num_attention_heads __lowercase : int = hidden_act __lowercase : int = intermediate_size __lowercase : Union[str, Any] = hidden_dropout_prob __lowercase : str = attention_probs_dropout_prob __lowercase : Dict = max_position_embeddings __lowercase : Optional[int] = type_vocab_size __lowercase : List[Any] = initializer_range __lowercase : Optional[int] = layer_norm_eps __lowercase : str = position_embedding_type __lowercase : str = use_cache __lowercase : int = classifier_dropout class lowerCAmelCase ( __a ): '''simple docstring''' @property def lowerCAmelCase ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": __lowercase : Any = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __lowercase : List[str] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
233
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def snake_case_ ( lowerCAmelCase_ : int = 8 ): __lowercase : str = ascii_letters + digits + punctuation return "".join(secrets.choice(lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ ) ) def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : int ): # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(lowerCAmelCase_ ) __lowercase : List[Any] = i // 3 __lowercase : int = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) __lowercase : str = ( chars_incl + random(lowerCAmelCase_ , quotient + remainder ) + random(lowerCAmelCase_ , lowerCAmelCase_ ) + random(lowerCAmelCase_ , lowerCAmelCase_ ) ) __lowercase : int = list(lowerCAmelCase_ ) shuffle(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) # random is a generalised function for letters, characters and numbers def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : int ): return "".join(secrets.choice(lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ ) ) def snake_case_ ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int ): pass # Put your code here... def snake_case_ ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[Any] ): pass # Put your code here... def snake_case_ ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[int] ): pass # Put your code here... def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : int = 8 ): if len(lowerCAmelCase_ ) < min_length: # Your Password must be at least 8 characters long return False __lowercase : Tuple = any(char in ascii_uppercase for char in password ) __lowercase : Union[str, Any] = any(char in ascii_lowercase for char in password ) __lowercase : Dict = any(char in digits for char in password ) __lowercase : Tuple = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def snake_case_ ( ): __lowercase : Union[str, Any] = int(input("""Please indicate the max length of your password: """ ).strip() ) __lowercase : List[str] = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(lowerCAmelCase_ ) ) print( """Alternative Password generated:""" , alternative_password_generator(lowerCAmelCase_ , lowerCAmelCase_ ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
233
1
from __future__ import annotations def __lowerCAmelCase ( a__ , a__ , a__ ) -> float: if days_between_payments <= 0: raise ValueError('''days_between_payments must be > 0''' ) if daily_interest_rate < 0: raise ValueError('''daily_interest_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * daily_interest_rate * days_between_payments def __lowerCAmelCase ( a__ , a__ , a__ , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('''number_of_compounding_periods must be > 0''' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('''nominal_annual_interest_rate_percentage must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def __lowerCAmelCase ( a__ , a__ , a__ , ) -> float: if number_of_years <= 0: raise ValueError('''number_of_years must be > 0''' ) if nominal_annual_percentage_rate < 0: raise ValueError('''nominal_annual_percentage_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return compound_interest( a__ , nominal_annual_percentage_rate / 365 , number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
363
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 A : str = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) A : int = logging.get_logger(__name__) # pylint: disable=invalid-name def __lowerCAmelCase ( ) -> Tuple: __a = '''https://pypi.org/pypi/diffusers/json''' __a = json.loads(request.urlopen(a__ ).read() )['''releases'''].keys() return sorted(a__ , key=lambda a__ : version.Version(a__ ) ) def __lowerCAmelCase ( ) -> List[Any]: # This function has already been executed if HF_MODULES_CACHE already is in the Python path. if HF_MODULES_CACHE in sys.path: return sys.path.append(a__ ) os.makedirs(a__ , exist_ok=a__ ) __a = Path(a__ ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def __lowerCAmelCase ( a__ ) -> Dict: init_hf_modules() __a = Path(a__ ) / 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(a__ , exist_ok=a__ ) __a = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def __lowerCAmelCase ( a__ ) -> Dict: with open(a__ , '''r''' , encoding='''utf-8''' ) as f: __a = f.read() # Imports of the form `import .xxx` __a = re.findall('''^\s*import\s+\.(\S+)\s*$''' , a__ , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , a__ , flags=re.MULTILINE ) # Unique-ify return list(set(a__ ) ) def __lowerCAmelCase ( a__ ) -> Any: __a = False __a = [module_file] __a = [] # Let's recurse through all relative imports while not no_change: __a = [] for f in files_to_check: new_imports.extend(get_relative_imports(a__ ) ) __a = Path(a__ ).parent __a = [str(module_path / m ) for m in new_imports] __a = [f for f in new_import_files if f not in all_relative_imports] __a = [F"""{f}.py""" for f in new_import_files] __a = len(a__ ) == 0 all_relative_imports.extend(a__ ) return all_relative_imports def __lowerCAmelCase ( a__ ) -> str: with open(a__ , '''r''' , encoding='''utf-8''' ) as f: __a = f.read() # Imports of the form `import xxx` __a = re.findall('''^\s*import\s+(\S+)\s*$''' , a__ , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , a__ , flags=re.MULTILINE ) # Only keep the top-level module __a = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __a = list(set(a__ ) ) __a = [] for imp in imports: try: importlib.import_module(a__ ) except ImportError: missing_packages.append(a__ ) if len(a__ ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F"""{', '.join(a__ )}. Run `pip install {' '.join(a__ )}`""" ) return get_relative_imports(a__ ) def __lowerCAmelCase ( a__ , a__ ) -> Dict: __a = module_path.replace(os.path.sep , '''.''' ) __a = importlib.import_module(a__ ) if class_name is None: return find_pipeline_class(a__ ) return getattr(a__ , a__ ) def __lowerCAmelCase ( a__ ) -> Optional[Any]: from ..pipelines import DiffusionPipeline __a = dict(inspect.getmembers(a__ , inspect.isclass ) ) __a = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , a__ ) 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}.""" ) __a = cls return pipeline_class def __lowerCAmelCase ( a__ , a__ , a__ = None , a__ = False , a__ = False , a__ = None , a__ = None , a__ = None , a__ = False , ) -> Tuple: __a = str(a__ ) __a = os.path.join(a__ , a__ ) if os.path.isfile(a__ ): __a = module_file_or_url __a = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __a = get_diffusers_versions() # cut ".dev0" __a = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __a = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F"""Defaulting to latest_version: {revision}.""" ) elif revision in available_versions: __a = F"""v{revision}""" elif revision == "main": __a = 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 __a = COMMUNITY_PIPELINES_URL.format(revision=a__ , pipeline=a__ ) try: __a = cached_download( a__ , cache_dir=a__ , force_download=a__ , proxies=a__ , resume_download=a__ , local_files_only=a__ , use_auth_token=a__ , ) __a = '''git''' __a = 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 __a = hf_hub_download( a__ , a__ , cache_dir=a__ , force_download=a__ , proxies=a__ , resume_download=a__ , local_files_only=a__ , use_auth_token=a__ , ) __a = 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 __a = check_imports(a__ ) # Now we move the module inside our cached dynamic modules. __a = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(a__ ) __a = Path(a__ ) / 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(a__ , submodule_path / module_file ) for module_needed in modules_needed: __a = F"""{module_needed}.py""" shutil.copy(os.path.join(a__ , a__ ) , 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(a__ , a__ ): __a = use_auth_token elif use_auth_token is True: __a = HfFolder.get_token() else: __a = None __a = model_info(a__ , revision=a__ , token=a__ ).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. __a = submodule_path / commit_hash __a = full_submodule + os.path.sep + commit_hash create_dynamic_module(a__ ) if not (submodule_path / module_file).exists(): shutil.copy(a__ , 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( a__ , F"""{module_needed}.py""" , cache_dir=a__ , force_download=a__ , resume_download=a__ , proxies=a__ , use_auth_token=a__ , revision=a__ , local_files_only=a__ , ) return os.path.join(a__ , a__ ) def __lowerCAmelCase ( a__ , a__ , a__ = None , a__ = None , a__ = False , a__ = False , a__ = None , a__ = None , a__ = None , a__ = False , **a__ , ) -> Tuple: __a = get_cached_module_file( a__ , a__ , cache_dir=a__ , force_download=a__ , resume_download=a__ , proxies=a__ , use_auth_token=a__ , revision=a__ , local_files_only=a__ , ) return get_class_in_module(a__ , final_module.replace('''.py''' , '''''' ) )
33
0
'''simple docstring''' import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case ( lowercase_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ) -> List[Any]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = num_choices snake_case_ = relative_attention snake_case_ = position_biased_input snake_case_ = pos_att_type snake_case_ = scope def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.get_config() snake_case_ = 300 return config def lowerCAmelCase__ ( self , a__ ) -> List[str]: '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = DebertaModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] snake_case_ = model(a__ , token_type_ids=a__ )[0] snake_case_ = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = DebertaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = DebertaForSequenceClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = DebertaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = DebertaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model( a__ , attention_mask=a__ , token_type_ids=a__ , start_positions=a__ , end_positions=a__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : Optional[int] = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase_ : Dict = ( { "feature-extraction": DebertaModel, "fill-mask": DebertaForMaskedLM, "question-answering": DebertaForQuestionAnswering, "text-classification": DebertaForSequenceClassification, "token-classification": DebertaForTokenClassification, "zero-shot": DebertaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ : Optional[int] = True lowerCAmelCase_ : Union[str, Any] = False lowerCAmelCase_ : Tuple = False lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Tuple = False def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = DebertaModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , hidden_size=37 ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) @slow def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = DebertaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' pass @slow def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = DebertaModel.from_pretrained("microsoft/deberta-base" ) snake_case_ = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) snake_case_ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case_ = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. snake_case_ = torch.tensor( [[[-0.5_9_8_6, -0.8_0_5_5, -0.8_4_6_2], [1.4_4_8_4, -0.9_3_4_8, -0.8_0_5_9], [0.3_1_2_3, 0.0_0_3_2, -1.4_1_3_1]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F'{output[:, 1:4, 1:4]}' )
85
'''simple docstring''' import unittest from typing import Dict, List, Optional, Union import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BridgeTowerImageProcessor class A ( unittest.TestCase ): '''simple docstring''' def __init__(self , _UpperCAmelCase , _UpperCAmelCase = True , _UpperCAmelCase = None , _UpperCAmelCase = 3_2 , _UpperCAmelCase = True , _UpperCAmelCase = 1 / 2_5_5 , _UpperCAmelCase = True , _UpperCAmelCase = True , _UpperCAmelCase = [0.48_145_466, 0.4_578_275, 0.40_821_073] , _UpperCAmelCase = [0.26_862_954, 0.26_130_258, 0.27_577_711] , _UpperCAmelCase = True , _UpperCAmelCase=7 , _UpperCAmelCase=3_0 , _UpperCAmelCase=4_0_0 , _UpperCAmelCase=3 , ) -> Dict: __UpperCamelCase : Dict = parent __UpperCamelCase : Any = do_resize __UpperCamelCase : Union[str, Any] = size if size is not None else {"shortest_edge": 2_8_8} __UpperCamelCase : Any = size_divisor __UpperCamelCase : Optional[int] = do_rescale __UpperCamelCase : Union[str, Any] = rescale_factor __UpperCamelCase : int = do_normalize __UpperCamelCase : List[Any] = do_center_crop __UpperCamelCase : Optional[int] = image_mean __UpperCamelCase : Tuple = image_std __UpperCamelCase : Tuple = do_pad __UpperCamelCase : Tuple = batch_size __UpperCamelCase : Dict = num_channels __UpperCamelCase : Dict = min_resolution __UpperCamelCase : Optional[Any] = max_resolution def a_ (self ) -> Optional[int]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def a_ (self , _UpperCAmelCase , _UpperCAmelCase=False ) -> Optional[Any]: if not batched: __UpperCamelCase : List[str] = self.size["shortest_edge"] __UpperCamelCase : Optional[int] = image_inputs[0] if isinstance(_UpperCAmelCase , Image.Image ): __UpperCamelCase , __UpperCamelCase : Optional[Any] = image.size else: __UpperCamelCase , __UpperCamelCase : Union[str, Any] = image.shape[1], image.shape[2] __UpperCamelCase : Dict = size / min(_UpperCAmelCase , _UpperCAmelCase ) if h < w: __UpperCamelCase , __UpperCamelCase : Tuple = size, scale * w else: __UpperCamelCase , __UpperCamelCase : List[Any] = scale * h, size __UpperCamelCase : List[Any] = int((1_3_3_3 / 8_0_0) * size ) if max(_UpperCAmelCase , _UpperCAmelCase ) > max_size: __UpperCamelCase : str = max_size / max(_UpperCAmelCase , _UpperCAmelCase ) __UpperCamelCase : Dict = newh * scale __UpperCamelCase : Union[str, Any] = neww * scale __UpperCamelCase , __UpperCamelCase : Optional[int] = int(newh + 0.5 ), int(neww + 0.5 ) __UpperCamelCase , __UpperCamelCase : Optional[int] = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: __UpperCamelCase : int = [] for image in image_inputs: __UpperCamelCase , __UpperCamelCase : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __UpperCamelCase : Tuple = max(_UpperCAmelCase , key=lambda _UpperCAmelCase : item[0] )[0] __UpperCamelCase : Union[str, Any] = max(_UpperCAmelCase , key=lambda _UpperCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' A = BridgeTowerImageProcessor if is_vision_available() else None def a_ (self ) -> Dict: __UpperCamelCase : Optional[Any] = BridgeTowerImageProcessingTester(self ) @property def a_ (self ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def a_ (self ) -> Union[str, Any]: __UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_UpperCAmelCase , "image_mean" ) ) self.assertTrue(hasattr(_UpperCAmelCase , "image_std" ) ) self.assertTrue(hasattr(_UpperCAmelCase , "do_normalize" ) ) self.assertTrue(hasattr(_UpperCAmelCase , "do_resize" ) ) self.assertTrue(hasattr(_UpperCAmelCase , "size" ) ) self.assertTrue(hasattr(_UpperCAmelCase , "size_divisor" ) ) def a_ (self ) -> List[str]: pass def a_ (self ) -> List[Any]: # Initialize image processor __UpperCamelCase : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __UpperCamelCase : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , Image.Image ) # Test not batched input __UpperCamelCase : List[str] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __UpperCamelCase , __UpperCamelCase : List[str] = self.image_processor_tester.get_expected_values(_UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase : Optional[int] = image_processing(_UpperCAmelCase , return_tensors="pt" ).pixel_values __UpperCamelCase , __UpperCamelCase : List[str] = self.image_processor_tester.get_expected_values(_UpperCAmelCase , batched=_UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a_ (self ) -> Tuple: # Initialize image processor __UpperCamelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __UpperCamelCase : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase , numpify=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , np.ndarray ) # Test not batched input __UpperCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __UpperCamelCase , __UpperCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(_UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase : List[Any] = image_processing(_UpperCAmelCase , return_tensors="pt" ).pixel_values __UpperCamelCase , __UpperCamelCase : int = self.image_processor_tester.get_expected_values(_UpperCAmelCase , batched=_UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a_ (self ) -> int: # Initialize image processor __UpperCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __UpperCamelCase : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase , torchify=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , torch.Tensor ) # Test not batched input __UpperCamelCase : List[str] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __UpperCamelCase , __UpperCamelCase : int = self.image_processor_tester.get_expected_values(_UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase : Optional[Any] = image_processing(_UpperCAmelCase , return_tensors="pt" ).pixel_values __UpperCamelCase , __UpperCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(_UpperCAmelCase , batched=_UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
298
0
"""simple docstring""" import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class _UpperCamelCase ( lowerCAmelCase__ ,unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] =RoFormerTokenizer __UpperCAmelCase : List[Any] =RoFormerTokenizerFast __UpperCAmelCase : int =True __UpperCAmelCase : Union[str, Any] =True def snake_case ( self ): super().setUp() def snake_case ( self , **__a ): return self.tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **__a ) def snake_case ( self , **__a ): return self.rust_tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **__a ) def snake_case ( self ): __lowerCAmelCase = "永和服装饰品有限公司,今天天气非常好" __lowerCAmelCase = "永和 服装 饰品 有限公司 , 今 天 天 气 非常 好" return input_text, output_text def snake_case ( self ): __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase , __lowerCAmelCase = self.get_chinese_input_output_texts() __lowerCAmelCase = tokenizer.tokenize(__a ) self.assertListEqual(__a , output_text.split() ) __lowerCAmelCase = tokens + [tokenizer.unk_token] __lowerCAmelCase = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase , __lowerCAmelCase = self.get_chinese_input_output_texts() __lowerCAmelCase = tokenizer.tokenize(__a ) self.assertListEqual(__a , output_text.split() ) __lowerCAmelCase = tokens + [tokenizer.unk_token] __lowerCAmelCase = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a ) def snake_case ( self ): pass def snake_case ( self ): pass def snake_case ( self ): pass
365
"""simple docstring""" import random def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = False ): '''simple docstring''' __lowerCAmelCase = {i: [] for i in range(_UpperCamelCase )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(_UpperCamelCase ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(_UpperCamelCase ): for j in range(i + 1 , _UpperCamelCase ): if random.random() < probability: graph[i].append(_UpperCamelCase ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(_UpperCamelCase ) return graph def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return { i: [j for j in range(_UpperCamelCase ) if i != j] for i in range(_UpperCamelCase ) } if __name__ == "__main__": import doctest doctest.testmod()
259
0
from string import ascii_uppercase _UpperCAmelCase : List[Any] = {str(ord(c) - 55): c for c in ascii_uppercase} def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError('int() can\'t convert non-string with explicit base' ) if num < 0: raise ValueError('parameter must be positive int' ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError('\'str\' object cannot be interpreted as an integer' ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError('\'float\' object cannot be interpreted as an integer' ) if base in (0, 1): raise ValueError('base must be >= 2' ) if base > 36: raise ValueError('base must be <= 36' ) snake_case_ = '' snake_case_ = 0 snake_case_ = 0 while div != 1: snake_case_ = divmod(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if base >= 11 and 9 < mod < 36: snake_case_ = ALPHABET_VALUES[str(_SCREAMING_SNAKE_CASE )] else: snake_case_ = str(_SCREAMING_SNAKE_CASE ) new_value += actual_value snake_case_ = num // base snake_case_ = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(_SCREAMING_SNAKE_CASE ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
285
'''simple docstring''' import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): @property def __UpperCAmelCase ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ort.SessionOptions() __a : Dict = False return options def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) __a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) __a : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default __a : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__a , feature_extractor=__a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__a ) __a : Tuple = 'A red cat sitting on a park bench' __a : int = np.random.RandomState(0 ) __a : Tuple = pipe( prompt=__a , image=__a , mask_image=__a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=__a , output_type='np' , ) __a : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
27
0
"""simple docstring""" import re import string import numpy as np import datasets UpperCAmelCase = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' UpperCAmelCase = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' UpperCAmelCase = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): def __snake_case ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , reference_urls=[] , ) def __snake_case ( self : Optional[Any] , snake_case__ : Union[str, Any] , snake_case__ : Optional[Any] , snake_case__ : Tuple=None , snake_case__ : Dict=False , snake_case__ : Optional[int]=False , snake_case__ : List[Any]=False , ): '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: lowercase :Union[str, Any] = np.array([re.sub(snake_case__ , '''''' , snake_case__ ) for x in predictions] ) lowercase :str = np.array([re.sub(snake_case__ , '''''' , snake_case__ ) for x in references] ) else: lowercase :List[Any] = np.asarray(snake_case__ ) lowercase :int = np.asarray(snake_case__ ) if ignore_case: lowercase :Any = np.char.lower(snake_case__ ) lowercase :int = np.char.lower(snake_case__ ) if ignore_punctuation: lowercase :Optional[int] = string.punctuation.maketrans('''''' , '''''' , string.punctuation ) lowercase :List[str] = np.char.translate(snake_case__ , table=snake_case__ ) lowercase :str = np.char.translate(snake_case__ , table=snake_case__ ) if ignore_numbers: lowercase :str = string.digits.maketrans('''''' , '''''' , string.digits ) lowercase :str = np.char.translate(snake_case__ , table=snake_case__ ) lowercase :Tuple = np.char.translate(snake_case__ , table=snake_case__ ) lowercase :Dict = predictions == references return {"exact_match": np.mean(snake_case__ ) * 1_0_0}
172
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class __magic_name__ ( __UpperCAmelCase ): __A : Tuple = "layoutlmv3" def __init__( self : int , snake_case__ : Any=5_0_2_6_5 , snake_case__ : int=7_6_8 , snake_case__ : Dict=1_2 , snake_case__ : Optional[Any]=1_2 , snake_case__ : Union[str, Any]=3_0_7_2 , snake_case__ : Tuple="gelu" , snake_case__ : List[str]=0.1 , snake_case__ : List[str]=0.1 , snake_case__ : int=5_1_2 , snake_case__ : int=2 , snake_case__ : Optional[int]=0.02 , snake_case__ : Union[str, Any]=1e-5 , snake_case__ : Optional[int]=1 , snake_case__ : Any=0 , snake_case__ : Optional[int]=2 , snake_case__ : int=1_0_2_4 , snake_case__ : str=1_2_8 , snake_case__ : Tuple=1_2_8 , snake_case__ : Optional[Any]=True , snake_case__ : Union[str, Any]=3_2 , snake_case__ : Any=1_2_8 , snake_case__ : List[Any]=6_4 , snake_case__ : List[Any]=2_5_6 , snake_case__ : Any=True , snake_case__ : Optional[Any]=True , snake_case__ : Tuple=True , snake_case__ : List[Any]=2_2_4 , snake_case__ : Optional[int]=3 , snake_case__ : Union[str, Any]=1_6 , snake_case__ : str=None , **snake_case__ : List[str] , ): '''simple docstring''' super().__init__( vocab_size=snake_case__ , hidden_size=snake_case__ , num_hidden_layers=snake_case__ , num_attention_heads=snake_case__ , intermediate_size=snake_case__ , hidden_act=snake_case__ , hidden_dropout_prob=snake_case__ , attention_probs_dropout_prob=snake_case__ , max_position_embeddings=snake_case__ , type_vocab_size=snake_case__ , initializer_range=snake_case__ , layer_norm_eps=snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ , ) lowercase :Optional[int] = max_ad_position_embeddings lowercase :Tuple = coordinate_size lowercase :Any = shape_size lowercase :Union[str, Any] = has_relative_attention_bias lowercase :Optional[Any] = rel_pos_bins lowercase :Tuple = max_rel_pos lowercase :Any = has_spatial_attention_bias lowercase :Any = rel_ad_pos_bins lowercase :str = max_rel_ad_pos lowercase :int = text_embed lowercase :Optional[int] = visual_embed lowercase :str = input_size lowercase :List[str] = num_channels lowercase :str = patch_size lowercase :Any = classifier_dropout class __magic_name__ ( __UpperCAmelCase ): __A : Tuple = version.parse("1.12" ) @property def __snake_case ( self : Any ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __snake_case ( self : int ): '''simple docstring''' return 1e-5 @property def __snake_case ( self : Union[str, Any] ): '''simple docstring''' return 1_2 def __snake_case ( self : str , snake_case__ : "ProcessorMixin" , snake_case__ : int = -1 , snake_case__ : int = -1 , snake_case__ : bool = False , snake_case__ : Optional["TensorType"] = None , snake_case__ : int = 3 , snake_case__ : int = 4_0 , snake_case__ : int = 4_0 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , snake_case__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowercase :Dict = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX lowercase :Union[str, Any] = processor.tokenizer.num_special_tokens_to_add(snake_case__ ) lowercase :List[str] = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case__ ) # Generate dummy inputs according to compute batch and sequence lowercase :Tuple = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes lowercase :List[str] = [[[4_8, 8_4, 7_3, 1_2_8]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) lowercase :List[Any] = self._generate_dummy_images(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) lowercase :Dict = dict( processor( snake_case__ , text=snake_case__ , boxes=snake_case__ , return_tensors=snake_case__ , ) ) return inputs
172
1
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> "list[int]": if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) snake_case_ = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 snake_case_ = 1 if upper_limit > 0: snake_case_ = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(_SCREAMING_SNAKE_CASE ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('\n********* Catalan Numbers Using Dynamic Programming ************\n') print('\n*** Enter -1 at any time to quit ***') print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='') try: while True: __SCREAMING_SNAKE_CASE : List[str] = int(input().strip()) if N < 0: print('\n********* Goodbye!! ************') break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print('Try another upper limit for the sequence: ', end='') except (NameError, ValueError): print('\n********* Invalid input, goodbye! ************\n') import doctest doctest.testmod()
347
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
347
1
'''simple docstring''' import math class _lowerCAmelCase : """simple docstring""" def __init__( self , _lowerCamelCase=0 ) -> int: # a graph with Node 0,1,...,N-1 A_ : List[str] = n A_ : Any = [ [math.inf for j in range(0 , _a )] for i in range(0 , _a ) ] # adjacency matrix for weight A_ : Tuple = [ [math.inf for j in range(0 , _a )] for i in range(0 , _a ) ] # dp[i][j] stores minimum distance from i to j def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Optional[Any]: A_ : int = w def UpperCAmelCase_ ( self ) -> str: for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): A_ : Optional[int] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase ) -> Union[str, Any]: return self.dp[u][v] if __name__ == "__main__": UpperCamelCase__ : Union[str, Any] = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
365
'''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 UpperCamelCase__ : Optional[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) UpperCamelCase__ : Tuple = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} UpperCamelCase__ : Optional[Any] = 'zero2' UpperCamelCase__ : Optional[int] = 'zero3' UpperCamelCase__ : Dict = [ZEROa, ZEROa] def UpperCAmelCase ( a_ , a_ , a_ ) -> int: """simple docstring""" A_ : int = parameterized.to_safe_name("""_""".join(str(a_ ) for x in param.args ) ) return F"{func.__name__}_{param_based_name}" # Cartesian-product of zero stages with models to test UpperCamelCase__ : Tuple = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class _lowerCAmelCase ( __A ): """simple docstring""" @parameterized.expand(_lowerCamelCase , name_func=_lowerCamelCase ) def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase ) -> Tuple: self.run_and_check( stage=_lowerCamelCase , model=_lowerCamelCase , distributed=_lowerCamelCase , fpaa=_lowerCamelCase , ) @require_torch_multi_gpu @parameterized.expand(_lowerCamelCase , name_func=_lowerCamelCase ) def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase ) -> Optional[int]: self.run_and_check( stage=_lowerCamelCase , model=_lowerCamelCase , distributed=_lowerCamelCase , fpaa=_lowerCamelCase , ) @parameterized.expand(_lowerCamelCase , name_func=_lowerCamelCase ) def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase ) -> Dict: self.run_and_check( stage=_lowerCamelCase , model=_lowerCamelCase , distributed=_lowerCamelCase , fpaa=_lowerCamelCase , ) @require_torch_multi_gpu @parameterized.expand(_lowerCamelCase , name_func=_lowerCamelCase ) def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase ) -> int: self.run_and_check( stage=_lowerCamelCase , model=_lowerCamelCase , distributed=_lowerCamelCase , fpaa=_lowerCamelCase , ) def UpperCAmelCase_ ( self , _lowerCamelCase ) -> Optional[Any]: # 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 UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 10 , _lowerCamelCase = True , _lowerCamelCase = True , _lowerCamelCase = True , ) -> List[str]: A_ : Union[str, Any] = models[model] A_ : Tuple = self.run_trainer( stage=_lowerCamelCase , model_name=_lowerCamelCase , eval_steps=_lowerCamelCase , num_train_epochs=1 , distributed=_lowerCamelCase , fpaa=_lowerCamelCase , ) self.do_checks(_lowerCamelCase ) return output_dir def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 10 , _lowerCamelCase = 1 , _lowerCamelCase = True , _lowerCamelCase = True , ) -> Any: A_ : Dict = self.get_auto_remove_tmp_dir("""./xxx""" , after=_lowerCamelCase ) A_ : str = F"\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(_lowerCamelCase )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n ".split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files A_ : List[str] = F"--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json".split() A_ : Union[str, Any] = [F"{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"] A_ : Tuple = self.get_launcher(_lowerCamelCase ) A_ : Optional[int] = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(_lowerCamelCase , env=self.get_env() ) return output_dir def UpperCAmelCase_ ( self , _lowerCamelCase=False ) -> Any: # 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) A_ : int = min(2 , get_gpu_count() ) if distributed else 1 return F"deepspeed --num_nodes 1 --num_gpus {num_gpus}".split()
164
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase : int = logging.get_logger(__name__) lowerCAmelCase : List[str] = { """microsoft/resnet-50""": """https://huggingface.co/microsoft/resnet-50/blob/main/config.json""", } class __lowercase ( UpperCAmelCase_ , UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[int] = '''resnet''' _UpperCAmelCase : Optional[Any] = ['''basic''', '''bottleneck'''] def __init__( self : str , lowerCAmelCase__ : Any=3 , lowerCAmelCase__ : Optional[int]=64 , lowerCAmelCase__ : Dict=[256, 512, 1024, 2048] , lowerCAmelCase__ : List[str]=[3, 4, 6, 3] , lowerCAmelCase__ : Optional[Any]="bottleneck" , lowerCAmelCase__ : int="relu" , lowerCAmelCase__ : Optional[Any]=False , lowerCAmelCase__ : Dict=None , lowerCAmelCase__ : Optional[int]=None , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) if layer_type not in self.layer_types: raise ValueError(F"layer_type={layer_type} is not one of {','.join(self.layer_types)}") SCREAMING_SNAKE_CASE_: Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_: Optional[int] = embedding_size SCREAMING_SNAKE_CASE_: Dict = hidden_sizes SCREAMING_SNAKE_CASE_: List[Any] = depths SCREAMING_SNAKE_CASE_: List[Any] = layer_type SCREAMING_SNAKE_CASE_: Any = hidden_act SCREAMING_SNAKE_CASE_: Any = downsample_in_first_stage SCREAMING_SNAKE_CASE_: Tuple = ["stem"] + [F"stage{idx}" for idx in range(1 , len(lowerCAmelCase__) + 1)] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict = get_aligned_output_features_output_indices( out_features=lowerCAmelCase__ , out_indices=lowerCAmelCase__ , stage_names=self.stage_names) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Dict = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): return 1E-3
13
def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): SCREAMING_SNAKE_CASE_: Optional[int] = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_: int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_: Dict = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_: Any = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCAmelCase : List[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
13
1
# Algorithm for the pigeonhole sorting def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[Any]: """simple docstring""" snake_case__ : str = min(__lowerCAmelCase ) # min() finds the minimum value snake_case__ : Optional[int] = max(__lowerCAmelCase ) # max() finds the maximum value snake_case__ : Tuple = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size snake_case__ : Dict = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. snake_case__ : Dict = 0 for count in range(__lowerCAmelCase ): while holes[count] > 0: holes[count] -= 1 snake_case__ : List[str] = count + min_val i += 1 def _lowerCAmelCase ( ) -> List[Any]: """simple docstring""" snake_case__ : Any = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(__lowerCAmelCase ) print('''Sorted order is:''' , ''' '''.join(__lowerCAmelCase ) ) if __name__ == "__main__": main()
44
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: """simple docstring""" snake_case__ : Optional[int] = len(__lowerCAmelCase ) + 1 snake_case__ : Tuple = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. snake_case__ : str = [[0 for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] # since string of zero length match pattern of zero length snake_case__ : int = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowerCAmelCase ): snake_case__ : Dict = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowerCAmelCase ): snake_case__ : str = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowerCAmelCase ): for j in range(1 , __lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": snake_case__ : Dict = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: snake_case__ : Union[str, Any] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): snake_case__ : List[str] = dp[i - 1][j] else: snake_case__ : Union[str, Any] = 0 else: snake_case__ : Tuple = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") A__ = '''aab''' A__ = '''c*a*b''' # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f"""{input_string} matches the given pattern {pattern}""") else: print(f"""{input_string} does not match with the given pattern {pattern}""")
44
1
def __UpperCamelCase ( _A ): if num < 0: return False lowerCAmelCase_ = num lowerCAmelCase_ = 0 while num > 0: lowerCAmelCase_ = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
278
def lowerCAmelCase__ ( lowerCamelCase_ : str): '''simple docstring''' lowerCAmelCase__ : str = [int(lowerCamelCase_) for i in ip_va_address.split('''.''') if i.isdigit()] return len(lowerCamelCase_) == 4 and all(0 <= int(lowerCamelCase_) <= 254 for octet in octets) if __name__ == "__main__": __snake_case : List[Any] =input().strip() __snake_case : Optional[Any] ='valid' if is_ip_va_address_valid(ip) else 'invalid' print(f"""{ip} is a {valid_or_invalid} IP v4 address.""")
129
0
'''simple docstring''' import argparse UpperCAmelCase : Optional[Any] = 'docs/source/_static/js/custom.js' def a__ ( a__ ): """simple docstring""" with open(__lowerCAmelCase , encoding="""utf-8""" , newline="""\n""" ) as f: __SCREAMING_SNAKE_CASE = f.readlines() __SCREAMING_SNAKE_CASE = 0 # First let's put the right version while not lines[index].startswith("""const stableVersion =""" ): index += 1 __SCREAMING_SNAKE_CASE = F'const stableVersion = "v{version}"\n' # Then update the dictionary while not lines[index].startswith("""const versionMapping = {""" ): index += 1 # We go until the end while not lines[index].startswith("""}""" ): index += 1 # We add the new version at the end lines[index - 1] += F' "v{version}": "v{version}",\n' with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(__lowerCAmelCase ) if __name__ == "__main__": UpperCAmelCase : List[Any] = argparse.ArgumentParser() parser.add_argument('--version', help='Release version.') UpperCAmelCase : Tuple = parser.parse_args() update_custom_js(args.version)
353
'''simple docstring''' import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Optional[Any]=7 , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : Optional[int]=99 , __SCREAMING_SNAKE_CASE : int=32 , __SCREAMING_SNAKE_CASE : Any=5 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : Optional[int]=37 , __SCREAMING_SNAKE_CASE : str="gelu" , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : Optional[int]=0.1 , __SCREAMING_SNAKE_CASE : Tuple=512 , __SCREAMING_SNAKE_CASE : Tuple=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=2 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : List[str]="None" , __SCREAMING_SNAKE_CASE : List[str]=3 , __SCREAMING_SNAKE_CASE : int=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = relative_attention __SCREAMING_SNAKE_CASE = position_biased_input __SCREAMING_SNAKE_CASE = pos_att_type __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_config() __SCREAMING_SNAKE_CASE = 300 return config def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any ) -> Union[str, Any]: """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = DebertaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = DebertaForMaskedLM(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DebertaForSequenceClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DebertaForTokenClassification(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = DebertaForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase__ ( self : List[str] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase__ = ( { "feature-extraction": DebertaModel, "fill-mask": DebertaForMaskedLM, "question-answering": DebertaForQuestionAnswering, "text-classification": DebertaForSequenceClassification, "token-classification": DebertaForTokenClassification, "zero-shot": DebertaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = DebertaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : str ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = DebertaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason="""Model not available yet""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: """simple docstring""" pass @slow def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = DebertaModel.from_pretrained("""microsoft/deberta-base""" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. __SCREAMING_SNAKE_CASE = torch.tensor( [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) , f'{output[:, 1:4, 1:4]}' )
331
0
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black __A = 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 BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. __A = """ def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states """ class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , 'models/bert/' ) ) lowerCAmelCase__ :Tuple = self.transformer_dir shutil.copy( os.path.join(__UpperCAmelCase , 'src/transformers/models/bert/modeling_bert.py' ) , os.path.join(self.transformer_dir , 'models/bert/modeling_bert.py' ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = 'src/transformers' shutil.rmtree(self.transformer_dir ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = comment + F"\nclass {class_name}(nn.Module):\n" + class_code if overwrite_result is not None: lowerCAmelCase__ :int = comment + F"\nclass {class_name}(nn.Module):\n" + overwrite_result lowerCAmelCase__ :int = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 ) lowerCAmelCase__ :Union[str, Any] = black.format_str(__UpperCAmelCase , mode=__UpperCAmelCase ) lowerCAmelCase__ :Any = os.path.join(self.transformer_dir , 'new_code.py' ) with open(__UpperCAmelCase , 'w' , newline='\n' ) as f: f.write(__UpperCAmelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__UpperCAmelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__UpperCAmelCase ) with open(__UpperCAmelCase , 'r' ) as f: self.assertTrue(f.read() , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = check_copies.find_code_in_transformers('models.bert.modeling_bert.BertLMPredictionHead' ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead' , 'BertLMPredictionHead' , REFERENCE_CODE + '\n' , ) # With no empty line at the end self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead' , 'BertLMPredictionHead' , __UpperCAmelCase , ) # Copy consistency with rename self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel' , 'TestModelLMPredictionHead' , re.sub('Bert' , 'TestModel' , __UpperCAmelCase ) , ) # Copy consistency with a really long name lowerCAmelCase__ :Dict = 'TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason' self.check_copy_consistency( F"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}" , F"{long_class_name}LMPredictionHead" , re.sub('Bert' , __UpperCAmelCase , __UpperCAmelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel' , 'TestModelLMPredictionHead' , __UpperCAmelCase , overwrite_result=re.sub('Bert' , 'TestModel' , __UpperCAmelCase ) , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = check_copies.LOCALIZED_READMES['README_zh-hans.md'] lowerCAmelCase__ :Dict = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the' ' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for' ' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong' ' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.' ' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),' ' released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and' ' lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same' ' method has been applied to compress GPT2 into' ' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into' ' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),' ' Multilingual BERT into' ' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German' ' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**' ' (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders' ' as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang' ' Luong, Quoc V. Le, Christopher D. Manning.' ) lowerCAmelCase__ :Any = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the' ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n' ) lowerCAmelCase__ :Optional[Any] = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the' ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.' ' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文' ' [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and' ' lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same' ' method has been applied to compress GPT2 into' ' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into' ' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),' ' Multilingual BERT into' ' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German' ' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自' ' Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather' ' than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,' ' Christopher D. Manning 发布。\n' ) lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = check_copies.convert_to_localized_md( __UpperCAmelCase , __UpperCAmelCase , localized_readme['format_model_list'] ) self.assertFalse(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ :Dict = check_copies.convert_to_localized_md( __UpperCAmelCase , __UpperCAmelCase , localized_readme['format_model_list'] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the' ' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for' ' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong' ' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.' ) lowerCAmelCase__ :str = ( '1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and' ' the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n' ) lowerCAmelCase__ :Dict = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the' ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n' ) lowerCAmelCase__ , lowerCAmelCase__ :Optional[Any] = check_copies.convert_to_localized_md( __UpperCAmelCase , __UpperCAmelCase , localized_readme['format_model_list'] ) # Check if the model link is synchronized. self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
293
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
293
1
from __future__ import annotations def lowercase_ ( A__ , A__ , A__ ) -> int | float: """simple docstring""" if len(A__ ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(A__ ) or left < -len(A__ ) or right >= len(A__ ) or right < -len(A__ ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] snake_case = (left + right) >> 1 # the middle snake_case = find_max(A__ , A__ , A__ ) # find max in range[left, mid] snake_case = find_max(A__ , mid + 1 , A__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
137
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, )
137
1
"""simple docstring""" import argparse import os import re import packaging.version lowerCAmelCase = """examples/""" lowerCAmelCase = { """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""), """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } lowerCAmelCase = { """init""": """src/diffusers/__init__.py""", """setup""": """setup.py""", } lowerCAmelCase = """README.md""" def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : int , snake_case_ : Dict ) ->List[Any]: with open(snake_case__ , 'r' , encoding='utf-8' , newline='\n' ) as f: lowerCamelCase__ : int =f.read() lowerCamelCase__ , lowerCamelCase__ : List[Any] =REPLACE_PATTERNS[pattern] lowerCamelCase__ : Union[str, Any] =replace.replace('VERSION' , snake_case__ ) lowerCamelCase__ : Optional[int] =re_pattern.sub(snake_case__ , snake_case__ ) with open(snake_case__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(snake_case__ ) def lowerCAmelCase_ ( snake_case_ : Tuple ) ->Any: for folder, directories, fnames in os.walk(snake_case__ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects' ) if "legacy" in directories: directories.remove('legacy' ) for fname in fnames: if fname.endswith('.py' ): update_version_in_file(os.path.join(snake_case__ , snake_case__ ) , snake_case__ , pattern='examples' ) def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : List[Any]=False ) ->List[str]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(snake_case__ , snake_case__ , snake_case__ ) if not patch: update_version_in_examples(snake_case__ ) def lowerCAmelCase_ ( ) ->Tuple: lowerCamelCase__ : List[str] ='🤗 Transformers currently provides the following architectures' lowerCamelCase__ : Optional[Any] ='1. Want to contribute a new model?' with open(snake_case__ , 'r' , encoding='utf-8' , newline='\n' ) as f: lowerCamelCase__ : Any =f.readlines() # Find the start of the list. lowerCamelCase__ : List[str] =0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowerCamelCase__ : List[str] =start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('1.' ): lowerCamelCase__ : Tuple =lines[index].replace( 'https://huggingface.co/docs/diffusers/main/model_doc' , 'https://huggingface.co/docs/diffusers/model_doc' , ) index += 1 with open(snake_case__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(snake_case__ ) def lowerCAmelCase_ ( ) ->Optional[int]: with open(REPLACE_FILES['init'] , 'r' ) as f: lowerCamelCase__ : int =f.read() lowerCamelCase__ : Optional[Any] =REPLACE_PATTERNS['init'][0].search(snake_case__ ).groups()[0] return packaging.version.parse(snake_case__ ) def lowerCAmelCase_ ( snake_case_ : Dict=False ) ->Optional[int]: lowerCamelCase__ : List[str] =get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!' ) if default_version.is_devrelease: lowerCamelCase__ : List[str] =default_version.base_version elif patch: lowerCamelCase__ : str =f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: lowerCamelCase__ : Any =f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. lowerCamelCase__ : str =input(f"""Which version are you releasing? [{default_version}]""" ) if len(snake_case__ ) == 0: lowerCamelCase__ : List[Any] =default_version print(f"""Updating version to {version}.""" ) global_version_update(snake_case__ , patch=snake_case__ ) def lowerCAmelCase_ ( ) ->str: lowerCamelCase__ : int =get_version() lowerCamelCase__ : str =f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" lowerCamelCase__ : Dict =current_version.base_version # Check with the user we got that right. lowerCamelCase__ : int =input(f"""Which version are we developing now? [{dev_version}]""" ) if len(snake_case__ ) == 0: lowerCamelCase__ : Tuple =dev_version print(f"""Updating version to {version}.""" ) global_version_update(snake_case__ ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") lowerCAmelCase = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
126
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
0
import math def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> float: """simple docstring""" if ( not isinstance(__lowerCAmelCase , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * power_factor def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> float: """simple docstring""" if ( not isinstance(__lowerCAmelCase , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
44
def _lowerCAmelCase ( __lowerCAmelCase = 50 ) -> int: """simple docstring""" snake_case__ : Optional[int] = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f"""{solution() = }""")
44
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
127
"""simple docstring""" lowerCAmelCase__ = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = set() # keep track of all the paths to be checked UpperCamelCase = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue UpperCamelCase = queue.pop(0 ) # get the last node from the path UpperCamelCase = path[-1] if node not in explored: UpperCamelCase = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: UpperCamelCase = list(_SCREAMING_SNAKE_CASE ) new_path.append(_SCREAMING_SNAKE_CASE ) queue.append(_SCREAMING_SNAKE_CASE ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_SCREAMING_SNAKE_CASE ) # in case there's no path between the 2 nodes return [] def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 UpperCamelCase = [start] UpperCamelCase = set(_SCREAMING_SNAKE_CASE ) # Keep tab on distances from `start` node. UpperCamelCase = {start: 0, target: -1} while queue: UpperCamelCase = queue.pop(0 ) if node == target: UpperCamelCase = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_SCREAMING_SNAKE_CASE ) queue.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
153
0
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch _a : int= True except ImportError: _a : List[Any]= False try: from torch.hub import _get_torch_home _a : Tuple= _get_torch_home() except ImportError: _a : Optional[int]= os.path.expanduser( os.getenv("TORCH_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "torch")) ) _a : Optional[Any]= os.path.join(torch_cache_home, "transformers") _a : int= "https://cdn.huggingface.co" _a : Dict= "https://s3.amazonaws.com/models.huggingface.co/bert" _a : Dict= "/".join(str(Path(__file__).resolve()).split("/")[:-1]) _a : Dict= os.path.join(PATH, "config.yaml") _a : str= os.path.join(PATH, "attributes.txt") _a : str= os.path.join(PATH, "objects.txt") _a : Optional[int]= os.getenv("PYTORCH_PRETRAINED_BERT_CACHE", default_cache_path) _a : List[str]= os.getenv("PYTORCH_TRANSFORMERS_CACHE", PYTORCH_PRETRAINED_BERT_CACHE) _a : str= os.getenv("TRANSFORMERS_CACHE", PYTORCH_TRANSFORMERS_CACHE) _a : Tuple= "pytorch_model.bin" _a : Dict= "config.yaml" def __UpperCAmelCase ( UpperCAmelCase_ : Union[str, Any]=OBJECTS , UpperCAmelCase_ : Tuple=ATTRIBUTES ) -> List[str]: '''simple docstring''' __snake_case : str = [] with open(UpperCAmelCase_ ) as f: for object in f.readlines(): vg_classes.append(object.split(',' )[0].lower().strip() ) __snake_case : List[Any] = [] with open(UpperCAmelCase_ ) as f: for object in f.readlines(): vg_attrs.append(object.split(',' )[0].lower().strip() ) return vg_classes, vg_attrs def __UpperCAmelCase ( UpperCAmelCase_ : List[Any] ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = OrderedDict() with open(UpperCAmelCase_ , 'rb' ) as f: __snake_case : int = pkl.load(UpperCAmelCase_ )['model'] for k in copy.deepcopy(list(ckp.keys() ) ): __snake_case : Dict = ckp.pop(UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , np.ndarray ): __snake_case : List[str] = torch.tensor(UpperCAmelCase_ ) else: assert isinstance(UpperCAmelCase_ , torch.tensor ), type(UpperCAmelCase_ ) __snake_case : int = v return r class UpperCamelCase : UpperCAmelCase : List[str] = {} def __init__(self : List[str] , _A : dict , _A : str = "root" , _A : int=0) -> Dict: __snake_case : Union[str, Any] = name __snake_case : int = level __snake_case : Optional[int] = {} for k, v in dictionary.items(): if v is None: raise ValueError() __snake_case : Optional[Any] = copy.deepcopy(_A) __snake_case : Any = copy.deepcopy(_A) if isinstance(_A , _A): __snake_case : Tuple = Config(_A , name=_A , level=level + 1) __snake_case : Tuple = v setattr(self , _A , _A) __snake_case : Any = d def __repr__(self : Dict) -> Union[str, Any]: return str(list((self._pointer.keys()))) def __setattr__(self : int , _A : str , _A : str) -> Optional[Any]: __snake_case : List[str] = val __snake_case : Optional[Any] = val __snake_case : Optional[Any] = key.split('.') __snake_case : Dict = len(_A) - 1 __snake_case : Union[str, Any] = self._pointer if len(_A) > 1: for i, l in enumerate(_A): if hasattr(self , _A) and isinstance(getattr(self , _A) , _A): setattr(getattr(self , _A) , '.'.join(levels[i:]) , _A) if l == last_level: __snake_case : Optional[Any] = val else: __snake_case : Tuple = pointer[l] def _lowercase (self : Dict) -> Optional[Any]: return self._pointer def _lowercase (self : Dict , _A : str , _A : Optional[int]) -> List[Any]: with open(f"{file_name}" , 'w') as stream: dump(_A , _A) def _lowercase (self : Union[str, Any] , _A : Optional[int] , _A : Dict) -> Tuple: with open(f"{file_name}" , 'w') as stream: json.dump(_A , _A) @staticmethod def _lowercase (_A : int) -> str: with open(_A) as stream: __snake_case : Any = load(_A , Loader=_A) return data def __str__(self : List[str]) -> Union[str, Any]: __snake_case : str = ' ' if self._name != "root": __snake_case : Any = f"{t * (self._level-1)}{self._name}:\n" else: __snake_case : Optional[Any] = '' __snake_case : Tuple = self._level for i, (k, v) in enumerate(self._pointer.items()): if isinstance(_A , _A): r += f"{t * (self._level)}{v}\n" self._level += 1 else: r += f"{t * (self._level)}{k}: {v} ({type(_A).__name__})\n" __snake_case : Tuple = level return r[:-1] @classmethod def _lowercase (cls : Optional[int] , _A : str , **_A : Dict) -> List[str]: __snake_case , __snake_case : List[str] = cls.get_config_dict(_A , **_A) return cls(_A) @classmethod def _lowercase (cls : List[Any] , _A : str , **_A : List[Any]) -> Dict: __snake_case : str = kwargs.pop('cache_dir' , _A) __snake_case : List[Any] = kwargs.pop('force_download' , _A) __snake_case : List[str] = kwargs.pop('resume_download' , _A) __snake_case : int = kwargs.pop('proxies' , _A) __snake_case : Dict = kwargs.pop('local_files_only' , _A) if os.path.isdir(_A): __snake_case : Dict = os.path.join(_A , _A) elif os.path.isfile(_A) or is_remote_url(_A): __snake_case : Union[str, Any] = pretrained_model_name_or_path else: __snake_case : int = hf_bucket_url(_A , filename=_A , use_cdn=_A) try: # Load from URL or cache if already cached __snake_case : Optional[Any] = cached_path( _A , cache_dir=_A , force_download=_A , proxies=_A , resume_download=_A , local_files_only=_A , ) # Load config dict if resolved_config_file is None: raise EnvironmentError __snake_case : Union[str, Any] = Config.load_yaml(_A) except EnvironmentError: __snake_case : List[Any] = 'Can\'t load config for' raise EnvironmentError(_A) if resolved_config_file == config_file: print('loading configuration file from path') else: print('loading configuration file cache') return Config.load_yaml(_A), kwargs def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = torch.load('dump.pt' , map_location=in_tensor.device ) __snake_case : List[str] = in_tensor.numpy() __snake_case : List[str] = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(UpperCAmelCase_ , UpperCAmelCase_ , rtol=0.01 , atol=0.1 ), ( F"{sum([1 for x in np.isclose(UpperCAmelCase_ , UpperCAmelCase_ , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*1_00:.4f} %" " element-wise mismatch" ) raise Exception('tensors are all good' ) # Hugging face functions below def __UpperCAmelCase ( UpperCAmelCase_ : Union[str, Any] ) -> Any: '''simple docstring''' __snake_case : str = urlparse(UpperCAmelCase_ ) return parsed.scheme in ("http", "https") def __UpperCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]=True ) -> str: '''simple docstring''' __snake_case : List[Any] = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX __snake_case : Optional[Any] = '/' not in model_id if legacy_format: return F"{endpoint}/{model_id}-{filename}" else: return F"{endpoint}/{model_id}/{filename}" def __UpperCAmelCase ( UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[Any]=0 , UpperCAmelCase_ : Any=None , ) -> Optional[Any]: '''simple docstring''' __snake_case : str = 'python/{}'.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): ua += "; " + "; ".join('{}/{}'.format(UpperCAmelCase_ , UpperCAmelCase_ ) for k, v in user_agent.items() ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): ua += "; " + user_agent __snake_case : Dict = {'user-agent': ua} if resume_size > 0: __snake_case : Optional[int] = 'bytes=%d-' % (resume_size,) __snake_case : Optional[Any] = requests.get(UpperCAmelCase_ , stream=UpperCAmelCase_ , proxies=UpperCAmelCase_ , headers=UpperCAmelCase_ ) if response.status_code == 4_16: # Range not satisfiable return __snake_case : Optional[Any] = response.headers.get('Content-Length' ) __snake_case : Dict = resume_size + int(UpperCAmelCase_ ) if content_length is not None else None __snake_case : str = tqdm( unit='B' , unit_scale=UpperCAmelCase_ , total=UpperCAmelCase_ , initial=UpperCAmelCase_ , desc='Downloading' , ) for chunk in response.iter_content(chunk_size=10_24 ): if chunk: # filter out keep-alive new chunks progress.update(len(UpperCAmelCase_ ) ) temp_file.write(UpperCAmelCase_ ) progress.close() def __UpperCAmelCase ( UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=10 , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : List[Any]=False , ) -> List[str]: '''simple docstring''' if cache_dir is None: __snake_case : str = TRANSFORMERS_CACHE if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): __snake_case : Dict = str(UpperCAmelCase_ ) os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) __snake_case : Optional[Any] = None if not local_files_only: try: __snake_case : int = requests.head(UpperCAmelCase_ , allow_redirects=UpperCAmelCase_ , proxies=UpperCAmelCase_ , timeout=UpperCAmelCase_ ) if response.status_code == 2_00: __snake_case : Union[str, Any] = response.headers.get('ETag' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass __snake_case : Optional[Any] = url_to_filename(UpperCAmelCase_ , UpperCAmelCase_ ) # get cache path to put the file __snake_case : Any = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(UpperCAmelCase_ ): return cache_path else: __snake_case : Union[str, Any] = [ file for file in fnmatch.filter(os.listdir(UpperCAmelCase_ ) , filename + '.*' ) if not file.endswith('.json' ) and not file.endswith('.lock' ) ] if len(UpperCAmelCase_ ) > 0: return os.path.join(UpperCAmelCase_ , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( 'Cannot find the requested files in the cached path and outgoing traffic has been' ' disabled. To enable model look-ups and downloads online, set \'local_files_only\'' ' to False.' ) return None # From now on, etag is not None. if os.path.exists(UpperCAmelCase_ ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. __snake_case : str = cache_path + '.lock' with FileLock(UpperCAmelCase_ ): # If the download just completed while the lock was activated. if os.path.exists(UpperCAmelCase_ ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: __snake_case : int = cache_path + '.incomplete' @contextmanager def _resumable_file_manager(): with open(UpperCAmelCase_ , 'a+b' ) as f: yield f __snake_case : List[Any] = _resumable_file_manager if os.path.exists(UpperCAmelCase_ ): __snake_case : Tuple = os.stat(UpperCAmelCase_ ).st_size else: __snake_case : Optional[Any] = 0 else: __snake_case : str = partial(tempfile.NamedTemporaryFile , dir=UpperCAmelCase_ , delete=UpperCAmelCase_ ) __snake_case : int = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( '%s not found in cache or force_download set to True, downloading to %s' , UpperCAmelCase_ , temp_file.name , ) http_get( UpperCAmelCase_ , UpperCAmelCase_ , proxies=UpperCAmelCase_ , resume_size=UpperCAmelCase_ , user_agent=UpperCAmelCase_ , ) os.replace(temp_file.name , UpperCAmelCase_ ) __snake_case : List[str] = {'url': url, 'etag': etag} __snake_case : Any = cache_path + '.json' with open(UpperCAmelCase_ , 'w' ) as meta_file: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) return cache_path def __UpperCAmelCase ( UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str]=None ) -> List[str]: '''simple docstring''' __snake_case : Dict = url.encode('utf-8' ) __snake_case : int = shaaaa(UpperCAmelCase_ ) __snake_case : Dict = url_hash.hexdigest() if etag: __snake_case : Tuple = etag.encode('utf-8' ) __snake_case : Optional[Any] = shaaaa(UpperCAmelCase_ ) filename += "." + etag_hash.hexdigest() if url.endswith('.h5' ): filename += ".h5" return filename def __UpperCAmelCase ( UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : str=False , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , ) -> Optional[int]: '''simple docstring''' if cache_dir is None: __snake_case : Dict = TRANSFORMERS_CACHE if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): __snake_case : List[Any] = str(UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): __snake_case : Optional[Any] = str(UpperCAmelCase_ ) if is_remote_url(UpperCAmelCase_ ): # URL, so get it from the cache (downloading if necessary) __snake_case : int = get_from_cache( UpperCAmelCase_ , cache_dir=UpperCAmelCase_ , force_download=UpperCAmelCase_ , proxies=UpperCAmelCase_ , resume_download=UpperCAmelCase_ , user_agent=UpperCAmelCase_ , local_files_only=UpperCAmelCase_ , ) elif os.path.exists(UpperCAmelCase_ ): # File, and it exists. __snake_case : Optional[Any] = url_or_filename elif urlparse(UpperCAmelCase_ ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('file {} not found'.format(UpperCAmelCase_ ) ) else: # Something unknown raise ValueError('unable to parse {} as a URL or as a local path'.format(UpperCAmelCase_ ) ) if extract_compressed_file: if not is_zipfile(UpperCAmelCase_ ) and not tarfile.is_tarfile(UpperCAmelCase_ ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" __snake_case , __snake_case : Optional[Any] = os.path.split(UpperCAmelCase_ ) __snake_case : Union[str, Any] = output_file.replace('.' , '-' ) + '-extracted' __snake_case : Optional[Any] = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) if os.path.isdir(UpperCAmelCase_ ) and os.listdir(UpperCAmelCase_ ) and not force_extract: return output_path_extracted # Prevent parallel extractions __snake_case : Optional[Any] = output_path + '.lock' with FileLock(UpperCAmelCase_ ): shutil.rmtree(UpperCAmelCase_ , ignore_errors=UpperCAmelCase_ ) os.makedirs(UpperCAmelCase_ ) if is_zipfile(UpperCAmelCase_ ): with ZipFile(UpperCAmelCase_ , 'r' ) as zip_file: zip_file.extractall(UpperCAmelCase_ ) zip_file.close() elif tarfile.is_tarfile(UpperCAmelCase_ ): __snake_case : Dict = tarfile.open(UpperCAmelCase_ ) tar_file.extractall(UpperCAmelCase_ ) tar_file.close() else: raise EnvironmentError('Archive format of {} could not be identified'.format(UpperCAmelCase_ ) ) return output_path_extracted return output_path def __UpperCAmelCase ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any="," ) -> Optional[Any]: '''simple docstring''' assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) if os.path.isfile(UpperCAmelCase_ ): with open(UpperCAmelCase_ ) as f: __snake_case : Dict = eval(f.read() ) else: __snake_case : str = requests.get(UpperCAmelCase_ ) try: __snake_case : Dict = requests.json() except Exception: __snake_case : int = req.content.decode() assert data is not None, "could not connect" try: __snake_case : str = eval(UpperCAmelCase_ ) except Exception: __snake_case : Union[str, Any] = data.split('\n' ) req.close() return data def __UpperCAmelCase ( UpperCAmelCase_ : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Any = requests.get(UpperCAmelCase_ ) __snake_case : int = np.array(Image.open(BytesIO(response.content ) ) ) return img def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = url.split('/' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(UpperCAmelCase_ ) with open(UpperCAmelCase_ , 'rb' ) as stream: __snake_case : str = pkl.load(UpperCAmelCase_ ) __snake_case : Optional[int] = weights.pop('model' ) __snake_case : List[Any] = {} for k, v in model.items(): __snake_case : int = torch.from_numpy(UpperCAmelCase_ ) if "running_var" in k: __snake_case : int = torch.tensor([0] ) __snake_case : int = k.replace('running_var' , 'num_batches_tracked' ) __snake_case : Optional[int] = zero return new def __UpperCAmelCase ( ) -> Optional[int]: '''simple docstring''' print(F"{os.path.abspath(os.path.join(UpperCAmelCase_ , os.pardir ) )}/demo.ipynb" ) def __UpperCAmelCase ( UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int="RGB" ) -> List[Any]: '''simple docstring''' assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) if os.path.isfile(UpperCAmelCase_ ): __snake_case : int = cva.imread(UpperCAmelCase_ ) else: __snake_case : Union[str, Any] = get_image_from_url(UpperCAmelCase_ ) assert img is not None, F"could not connect to: {im}" __snake_case : str = cva.cvtColor(UpperCAmelCase_ , cva.COLOR_BGR2RGB ) if input_format == "RGB": __snake_case : List[str] = img[:, :, ::-1] return img def __UpperCAmelCase ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=1 ) -> List[Any]: '''simple docstring''' return (images[i : i + batch] for i in range(0 , len(UpperCAmelCase_ ) , UpperCAmelCase_ ))
95
"""simple docstring""" from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase ( lowercase ): UpperCAmelCase : Optional[int] = """new-model""" if is_tf_available(): class UpperCamelCase ( lowercase ): UpperCAmelCase : List[str] = NewModelConfig @require_tf class UpperCamelCase ( unittest.TestCase ): @slow def _lowercase (self : List[str]) -> Dict: __snake_case : Any = 'bert-base-cased' __snake_case : Optional[Any] = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow def _lowercase (self : List[Any]) -> str: __snake_case : Optional[int] = 'bert-base-cased' __snake_case : List[Any] = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : Dict = TFAutoModelForPreTraining.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow def _lowercase (self : Any) -> List[str]: for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : str = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : List[str] = TFAutoModelForCausalLM.from_pretrained(_A) __snake_case , __snake_case : List[str] = TFAutoModelForCausalLM.from_pretrained(_A , output_loading_info=_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow def _lowercase (self : Tuple) -> Dict: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Union[str, Any] = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : Union[str, Any] = TFAutoModelWithLMHead.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow def _lowercase (self : Union[str, Any]) -> Optional[int]: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Union[str, Any] = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(_A) __snake_case , __snake_case : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_A , output_loading_info=_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow def _lowercase (self : str) -> Union[str, Any]: for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Dict = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : str = TFAutoModelForSeqaSeqLM.from_pretrained(_A) __snake_case , __snake_case : Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(_A , output_loading_info=_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow def _lowercase (self : str) -> str: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __snake_case : Tuple = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : Tuple = TFAutoModelForSequenceClassification.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow def _lowercase (self : Optional[Any]) -> Optional[int]: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __snake_case : List[str] = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : Any = TFAutoModelForQuestionAnswering.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) @slow @require_tensorflow_probability def _lowercase (self : List[Any]) -> List[str]: for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: __snake_case : Optional[Any] = AutoConfig.from_pretrained(_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) __snake_case : int = TFAutoModelForTableQuestionAnswering.from_pretrained(_A) __snake_case , __snake_case : Dict = TFAutoModelForTableQuestionAnswering.from_pretrained( _A , output_loading_info=_A) self.assertIsNotNone(_A) self.assertIsInstance(_A , _A) def _lowercase (self : Optional[Any]) -> Optional[Any]: __snake_case : Optional[int] = TFAutoModelWithLMHead.from_pretrained(_A) self.assertIsInstance(_A , _A) self.assertEqual(model.num_parameters() , 1_44_10) self.assertEqual(model.num_parameters(only_trainable=_A) , 1_44_10) def _lowercase (self : Any) -> List[str]: __snake_case : List[Any] = TFAutoModelWithLMHead.from_pretrained(_A) self.assertIsInstance(_A , _A) self.assertEqual(model.num_parameters() , 1_44_10) self.assertEqual(model.num_parameters(only_trainable=_A) , 1_44_10) def _lowercase (self : Optional[Any]) -> str: # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel __snake_case : Optional[Any] = TFAutoModel.from_pretrained('sgugger/funnel-random-tiny') self.assertIsInstance(_A , _A) __snake_case : int = copy.deepcopy(model.config) __snake_case : int = ['FunnelBaseModel'] __snake_case : int = TFAutoModel.from_config(_A) self.assertIsInstance(_A , _A) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A) __snake_case : List[Any] = TFAutoModel.from_pretrained(_A) self.assertIsInstance(_A , _A) def _lowercase (self : List[Any]) -> int: try: AutoConfig.register('new-model' , _A) __snake_case : int = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__): # Wrong config class will raise an error with self.assertRaises(_A): auto_class.register(_A , _A) auto_class.register(_A , _A) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A): auto_class.register(_A , _A) # Now that the config is registered, it can be used as any other config with the auto-API __snake_case : Union[str, Any] = BertModelTester(self).get_config() __snake_case : Optional[int] = NewModelConfig(**tiny_config.to_dict()) __snake_case : List[str] = auto_class.from_config(_A) self.assertIsInstance(_A , _A) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A) __snake_case : Tuple = auto_class.from_pretrained(_A) self.assertIsInstance(_A , _A) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def _lowercase (self : Optional[int]) -> Union[str, Any]: with self.assertRaisesRegex( _A , 'bert-base is not a local folder and is not a valid model identifier'): __snake_case : Any = TFAutoModel.from_pretrained('bert-base') def _lowercase (self : str) -> str: with self.assertRaisesRegex( _A , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'): __snake_case : Optional[Any] = TFAutoModel.from_pretrained(_A , revision='aaaaaa') def _lowercase (self : int) -> Any: with self.assertRaisesRegex( _A , 'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin' , ): __snake_case : List[str] = TFAutoModel.from_pretrained('hf-internal-testing/config-no-model') def _lowercase (self : Optional[Any]) -> Any: with self.assertRaisesRegex(_A , 'Use `from_pt=True` to load this model'): __snake_case : List[str] = TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only') def _lowercase (self : str) -> Any: # Make sure we have cached the model. __snake_case : str = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert') with RequestCounter() as counter: __snake_case : List[str] = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert') self.assertEqual(counter.get_request_count , 0) self.assertEqual(counter.head_request_count , 1) self.assertEqual(counter.other_request_count , 0) # With a sharded checkpoint __snake_case : Optional[int] = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded') with RequestCounter() as counter: __snake_case : Any = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded') self.assertEqual(counter.get_request_count , 0) self.assertEqual(counter.head_request_count , 1) self.assertEqual(counter.other_request_count , 0)
95
1