code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
from __future__ import annotations def __UpperCamelCase ( _A : Union[str, Any] ) ->float: """simple docstring""" if not nums: raise ValueError("""List is empty""" ) return sum(a__ ) / len(a__ ) if __name__ == "__main__": import doctest doctest.testmod()
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
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 __A : List[str] = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __lowerCAmelCase): _UpperCamelCase:List[Any] = ['''pixel_values'''] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**lowerCAmelCase_ ) lowerCamelCase_ =size if size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(lowerCAmelCase_ ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(lowerCAmelCase_ , default_to_square=lowerCAmelCase_ , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =do_rescale lowerCamelCase_ =do_normalize lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =rescale_factor lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(lowerCAmelCase_ ) if "shortest_edge" in size: lowerCamelCase_ =get_resize_output_image_size(lowerCAmelCase_ , size=size["""shortest_edge"""] , default_to_square=lowerCAmelCase_ ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: lowerCamelCase_ =(size["""height"""], size["""width"""]) else: raise ValueError(f'Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}' ) return resize(lowerCAmelCase_ , size=lowerCAmelCase_ , resample=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(lowerCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(lowerCAmelCase_ , size=(size["""height"""], size["""width"""]) , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE )-> np.ndarray: return rescale(lowerCAmelCase_ , scale=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(lowerCAmelCase_ , mean=lowerCAmelCase_ , std=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: lowerCamelCase_ =do_resize if do_resize is not None else self.do_resize lowerCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(lowerCAmelCase_ , param_name="""crop_size""" , default_to_square=lowerCAmelCase_ ) lowerCamelCase_ =resample if resample is not None else self.resample lowerCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor 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_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(lowerCAmelCase_ ) if not is_batched(lowerCAmelCase_ ): lowerCamelCase_ =[images] if not valid_images(lowerCAmelCase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(lowerCAmelCase_ ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(image=lowerCAmelCase_ , size=lowerCAmelCase_ , resample=lowerCAmelCase_ ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(image=lowerCAmelCase_ , size=lowerCAmelCase_ ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(image=lowerCAmelCase_ , scale=lowerCAmelCase_ ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(image=lowerCAmelCase_ , mean=lowerCAmelCase_ , std=lowerCAmelCase_ ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(lowerCAmelCase_ , lowerCAmelCase_ ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=lowerCAmelCase_ , tensor_type=lowerCAmelCase_ )
716
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def __UpperCamelCase ( _A : np.ndarray ) ->np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.mean(1 ) # Centralize the data of class i lowerCamelCase_ =data - column_reshape(_A ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_A , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =np.dot(_A , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =features.mean(1 ) lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.shape[1] lowerCamelCase_ =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" # Check if the features have been loaded if features.any(): lowerCamelCase_ =features.mean(1 ) # Center the dataset lowerCamelCase_ =features - np.reshape(_A , (data_mean.size, 1) ) lowerCamelCase_ =np.dot(_A , centered_data.T ) / features.shape[1] lowerCamelCase_ , lowerCamelCase_ =np.linalg.eigh(_A ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCamelCase_ =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCamelCase_ =np.dot(filtered_eigenvectors.T , _A ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: lowerCamelCase_ , lowerCamelCase_ =eigh( covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , ) lowerCamelCase_ =eigenvectors[:, ::-1][:, :dimensions] lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =np.linalg.svd(_A ) lowerCamelCase_ =svd_matrix[:, 0:dimensions] lowerCamelCase_ =np.dot(filtered_svd_matrix.T , _A ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" # Create dummy dataset with 2 classes and 3 features lowerCamelCase_ =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCamelCase_ =np.array([0, 0, 0, 1, 1] ) lowerCamelCase_ =2 lowerCamelCase_ =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_A ) as error_info: lowerCamelCase_ =linear_discriminant_analysis( _A , _A , _A , _A ) if isinstance(_A , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCamelCase_ =2 lowerCamelCase_ =np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_A ) as error_info: lowerCamelCase_ =principal_component_analysis(_A , _A ) if not np.allclose(_A , _A ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
75
0
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType __A : Optional[List[str]] = None __A : Tuple = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image __A : int = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class _SCREAMING_SNAKE_CASE : _UpperCamelCase:bool = True _UpperCamelCase:Optional[str] = None # Automatically constructed _UpperCamelCase:ClassVar[str] = "PIL.Image.Image" _UpperCamelCase:ClassVar[Any] = pa.struct({"bytes": pa.binary(), "path": pa.string()}) _UpperCamelCase:str = field(default="Image" , init=lowerCAmelCase__ , repr=lowerCAmelCase__) def __call__( self )-> Any: return self.pa_type def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> int: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): lowerCamelCase_ =np.array(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return {"path": value, "bytes": None} elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return {"path": None, "bytes": value} elif isinstance(UpperCAmelCase__ , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(UpperCAmelCase__ ) elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> List[str]: if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install \'Pillow\'.""" ) if token_per_repo_id is None: lowerCamelCase_ ={} lowerCamelCase_ =value['''path'''], value['''bytes'''] if bytes_ is None: if path is None: raise ValueError(f'An image should have one of \'path\' or \'bytes\' but both are None in {value}.' ) else: if is_local_path(UpperCAmelCase__ ): lowerCamelCase_ =PIL.Image.open(UpperCAmelCase__ ) else: lowerCamelCase_ =path.split("""::""" )[-1] try: lowerCamelCase_ =string_to_dict(UpperCAmelCase__ , config.HUB_DATASETS_URL )['''repo_id'''] lowerCamelCase_ =token_per_repo_id.get(UpperCAmelCase__ ) except ValueError: lowerCamelCase_ =None with xopen(UpperCAmelCase__ , """rb""" , use_auth_token=UpperCAmelCase__ ) as f: lowerCamelCase_ =BytesIO(f.read() ) lowerCamelCase_ =PIL.Image.open(bytes_ ) else: lowerCamelCase_ =PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def _snake_case ( self )-> Tuple: from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> str: if pa.types.is_string(storage.type ): lowerCamelCase_ =pa.array([None] * len(UpperCAmelCase__ ) , type=pa.binary() ) lowerCamelCase_ =pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): lowerCamelCase_ =pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) lowerCamelCase_ =pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: lowerCamelCase_ =storage.field("""bytes""" ) else: lowerCamelCase_ =pa.array([None] * len(UpperCAmelCase__ ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: lowerCamelCase_ =storage.field("""path""" ) else: lowerCamelCase_ =pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) lowerCamelCase_ =pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): lowerCamelCase_ =pa.array( [encode_np_array(np.array(UpperCAmelCase__ ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) lowerCamelCase_ =pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) lowerCamelCase_ =pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase__ , self.pa_type ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: @no_op_if_value_is_null def path_to_bytes(_SCREAMING_SNAKE_CASE ): with xopen(UpperCAmelCase__ , """rb""" ) as f: lowerCamelCase_ =f.read() return bytes_ lowerCamelCase_ =pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) lowerCamelCase_ =pa.array( [os.path.basename(UpperCAmelCase__ ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) lowerCamelCase_ =pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase__ , self.pa_type ) def __UpperCamelCase ( ) ->List[str]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() lowerCamelCase_ =list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def __UpperCamelCase ( _A : int ) ->bytes: """simple docstring""" lowerCamelCase_ =BytesIO() if image.format in list_image_compression_formats(): lowerCamelCase_ =image.format else: lowerCamelCase_ ='''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF''' image.save(_A , format=_A ) return buffer.getvalue() def __UpperCamelCase ( _A : int ) ->dict: """simple docstring""" if hasattr(_A , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(_A )} def __UpperCamelCase ( _A : Union[str, Any] ) ->dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) lowerCamelCase_ =array.dtype lowerCamelCase_ =dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER lowerCamelCase_ =dtype.kind lowerCamelCase_ =dtype.itemsize lowerCamelCase_ =None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: lowerCamelCase_ =np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( f'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.' ) if dtype is not dest_dtype: warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: lowerCamelCase_ =dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: lowerCamelCase_ =dtype_byteorder + dtype_kind + str(_A ) lowerCamelCase_ =np.dtype(_A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}' ) lowerCamelCase_ =PIL.Image.fromarray(array.astype(_A ) ) return {"path": None, "bytes": image_to_bytes(_A )} def __UpperCamelCase ( _A : Dict ) ->List[dict]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) if objs: lowerCamelCase_ =first_non_null_value(_A ) if isinstance(_A , _A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(_A , np.ndarray ): lowerCamelCase_ =no_op_if_value_is_null(_A ) return [obj_to_image_dict_func(_A ) for obj in objs] elif isinstance(_A , PIL.Image.Image ): lowerCamelCase_ =no_op_if_value_is_null(_A ) return [obj_to_image_dict_func(_A ) for obj in objs] else: return objs else: return objs
717
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
75
0
import requests __A : Union[str, Any] = """YOUR API KEY""" def __UpperCamelCase ( _A : Dict , _A : Dict = giphy_api_key ) ->list: """simple docstring""" lowerCamelCase_ ="+".join(query.split() ) lowerCamelCase_ =f'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' lowerCamelCase_ =requests.get(_A ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
718
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
0
def __UpperCamelCase ( _A : list , _A : int , _A : int = 0 , _A : int = 0 ) ->Any: """simple docstring""" lowerCamelCase_ =right or len(__a ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(__a , __a , left + 1 , right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
719
from collections import namedtuple import requests from lxml import html # type: ignore __A : Dict = namedtuple('covid_data', 'cases deaths recovered') def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data: """simple docstring""" lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) ) __A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
75
0
'''simple docstring''' from collections.abc import Generator from math import sin def __UpperCamelCase ( _A : bytes ) ->Dict: """simple docstring""" if len(_A ) != 32: raise ValueError("""Input must be of length 32""" ) lowerCamelCase_ =b"" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def __UpperCamelCase ( _A : int ) ->Union[str, Any]: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) lowerCamelCase_ =format(_A , """08x""" )[-8:] lowerCamelCase_ =b"" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def __UpperCamelCase ( _A : bytes ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ =b"" for char in message: bit_string += format(_A , """08b""" ).encode("""utf-8""" ) lowerCamelCase_ =format(len(_A ) , """064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(_A ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def __UpperCamelCase ( _A : bytes ) ->List[Any]: """simple docstring""" if len(_A ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 , len(_A ) , 512 ): lowerCamelCase_ =bit_string[pos : pos + 512] lowerCamelCase_ =[] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def __UpperCamelCase ( _A : int ) ->Optional[int]: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) lowerCamelCase_ =format(_A , """032b""" ) lowerCamelCase_ ="" for c in i_str: new_str += "1" if c == "0" else "0" return int(_A , 2 ) def __UpperCamelCase ( _A : int , _A : int ) ->Union[str, Any]: """simple docstring""" return (a + b) % 2**32 def __UpperCamelCase ( _A : int , _A : int ) ->Union[str, Any]: """simple docstring""" if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def __UpperCamelCase ( _A : bytes ) ->List[Any]: """simple docstring""" lowerCamelCase_ =preprocess(_A ) lowerCamelCase_ =[int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states lowerCamelCase_ =0X67452301 lowerCamelCase_ =0XEFCDAB89 lowerCamelCase_ =0X98BADCFE lowerCamelCase_ =0X10325476 lowerCamelCase_ =[ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(_A ): lowerCamelCase_ =aa lowerCamelCase_ =ba lowerCamelCase_ =ca lowerCamelCase_ =da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f lowerCamelCase_ =d ^ (b & (c ^ d)) lowerCamelCase_ =i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f lowerCamelCase_ =c ^ (d & (b ^ c)) lowerCamelCase_ =(5 * i + 1) % 16 elif i <= 47: lowerCamelCase_ =b ^ c ^ d lowerCamelCase_ =(3 * i + 5) % 16 else: lowerCamelCase_ =c ^ (b | not_aa(_A )) lowerCamelCase_ =(7 * i) % 16 lowerCamelCase_ =(f + a + added_consts[i] + block_words[g]) % 2**32 lowerCamelCase_ =d lowerCamelCase_ =c lowerCamelCase_ =b lowerCamelCase_ =sum_aa(_A , left_rotate_aa(_A , shift_amounts[i] ) ) # Add hashed chunk to running total lowerCamelCase_ =sum_aa(_A , _A ) lowerCamelCase_ =sum_aa(_A , _A ) lowerCamelCase_ =sum_aa(_A , _A ) lowerCamelCase_ =sum_aa(_A , _A ) lowerCamelCase_ =reformat_hex(_A ) + reformat_hex(_A ) + reformat_hex(_A ) + reformat_hex(_A ) return digest if __name__ == "__main__": import doctest doctest.testmod()
720
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Union[str, Any] = logging.get_logger(__name__) __A : Any = { 'facebook/data2vec-text-base': 'https://huggingface.co/data2vec/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowercase__): _UpperCamelCase:Tuple = "data2vec-text" def __init__( self , _SCREAMING_SNAKE_CASE=3_0522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , )-> Union[str, Any]: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) lowerCamelCase_ =vocab_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =position_embedding_type lowerCamelCase_ =use_cache lowerCamelCase_ =classifier_dropout class _SCREAMING_SNAKE_CASE ( lowercase__): @property def _snake_case ( self )-> Tuple: if self.task == "multiple-choice": lowerCamelCase_ ={0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowerCamelCase_ ={0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
721
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
75
0
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING __A : Dict = logging.get_logger(__name__) @add_end_docstrings(__UpperCAmelCase) class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase): def __init__( self , **_SCREAMING_SNAKE_CASE )-> Any: super().__init__(**_lowerCamelCase ) if self.framework == "tf": raise ValueError(f'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type(_lowerCamelCase ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> Union[str, Any]: if "text_queries" in kwargs: lowerCamelCase_ =kwargs.pop("""text_queries""" ) if isinstance(_lowerCamelCase , (str, Image.Image) ): lowerCamelCase_ ={"""image""": image, """candidate_labels""": candidate_labels} else: lowerCamelCase_ =image lowerCamelCase_ =super().__call__(_lowerCamelCase , **_lowerCamelCase ) return results def _snake_case ( self , **_SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ ={} if "threshold" in kwargs: lowerCamelCase_ =kwargs["""threshold"""] if "top_k" in kwargs: lowerCamelCase_ =kwargs["""top_k"""] return {}, {}, postprocess_params def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =load_image(inputs["""image"""] ) lowerCamelCase_ =inputs["""candidate_labels"""] if isinstance(_lowerCamelCase , _lowerCamelCase ): lowerCamelCase_ =candidate_labels.split(""",""" ) lowerCamelCase_ =torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(_lowerCamelCase ): lowerCamelCase_ =self.tokenizer(_lowerCamelCase , return_tensors=self.framework ) lowerCamelCase_ =self.image_processor(_lowerCamelCase , return_tensors=self.framework ) yield { "is_last": i == len(_lowerCamelCase ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: lowerCamelCase_ =model_inputs.pop("""target_size""" ) lowerCamelCase_ =model_inputs.pop("""candidate_label""" ) lowerCamelCase_ =model_inputs.pop("""is_last""" ) lowerCamelCase_ =self.model(**_lowerCamelCase ) lowerCamelCase_ ={"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs} return model_outputs def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=None )-> str: lowerCamelCase_ =[] for model_output in model_outputs: lowerCamelCase_ =model_output["""candidate_label"""] lowerCamelCase_ =BaseModelOutput(_lowerCamelCase ) lowerCamelCase_ =self.image_processor.post_process_object_detection( outputs=_lowerCamelCase , threshold=_lowerCamelCase , target_sizes=model_output["""target_size"""] )[0] for index in outputs["scores"].nonzero(): lowerCamelCase_ =outputs["""scores"""][index].item() lowerCamelCase_ =self._get_bounding_box(outputs["""boxes"""][index][0] ) lowerCamelCase_ ={"""score""": score, """label""": label, """box""": box} results.append(_lowerCamelCase ) lowerCamelCase_ =sorted(_lowerCamelCase , key=lambda _SCREAMING_SNAKE_CASE : x["score"] , reverse=_lowerCamelCase ) if top_k: lowerCamelCase_ =results[:top_k] return results def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Any: if self.framework != "pt": raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch.""" ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =box.int().tolist() lowerCamelCase_ ={ """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
700
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "deta" _UpperCamelCase:int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , **_SCREAMING_SNAKE_CASE , )-> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase_ =CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =backbone_config.pop("""model_type""" ) lowerCamelCase_ =CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ =config_class.from_dict(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone_config lowerCamelCase_ =num_queries lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =d_model lowerCamelCase_ =encoder_ffn_dim lowerCamelCase_ =encoder_layers lowerCamelCase_ =encoder_attention_heads lowerCamelCase_ =decoder_ffn_dim lowerCamelCase_ =decoder_layers lowerCamelCase_ =decoder_attention_heads lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =activation_dropout lowerCamelCase_ =activation_function lowerCamelCase_ =init_std lowerCamelCase_ =init_xavier_std lowerCamelCase_ =encoder_layerdrop lowerCamelCase_ =auxiliary_loss lowerCamelCase_ =position_embedding_type # deformable attributes lowerCamelCase_ =num_feature_levels lowerCamelCase_ =encoder_n_points lowerCamelCase_ =decoder_n_points lowerCamelCase_ =two_stage lowerCamelCase_ =two_stage_num_proposals lowerCamelCase_ =with_box_refine lowerCamelCase_ =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =mask_loss_coefficient lowerCamelCase_ =dice_loss_coefficient lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient lowerCamelCase_ =focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> int: return self.encoder_attention_heads @property def _snake_case ( self )-> int: return self.d_model def _snake_case ( self )-> str: lowerCamelCase_ =copy.deepcopy(self.__dict__ ) lowerCamelCase_ =self.backbone_config.to_dict() lowerCamelCase_ =self.__class__.model_type return output
75
0
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run __A : Tuple = True except (ImportError, AttributeError): __A : Optional[Any] = object def __UpperCamelCase ( *_A : Tuple , **_A : Tuple ) ->Tuple: """simple docstring""" pass __A : List[Any] = False __A : List[Any] = logging.get_logger('transformers-cli/serving') def __UpperCamelCase ( _A : Namespace ) ->int: """simple docstring""" lowerCamelCase_ =pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) return ServeCommand(lowerCamelCase_ , args.host , args.port , args.workers ) class _SCREAMING_SNAKE_CASE ( lowerCamelCase__): _UpperCamelCase:Any = 42 class _SCREAMING_SNAKE_CASE ( lowerCamelCase__): _UpperCamelCase:List[str] = 42 _UpperCamelCase:Dict = 42 class _SCREAMING_SNAKE_CASE ( lowerCamelCase__): _UpperCamelCase:Optional[Any] = 42 class _SCREAMING_SNAKE_CASE ( lowerCamelCase__): _UpperCamelCase:Dict = 42 class _SCREAMING_SNAKE_CASE ( lowerCamelCase__): @staticmethod def _snake_case ( _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =parser.add_parser( """serve""" , help="""CLI tool to run inference requests through REST and GraphQL endpoints.""" ) serve_parser.add_argument( """--task""" , type=__lowerCamelCase , choices=get_supported_tasks() , help="""The task to run the pipeline on""" , ) serve_parser.add_argument("""--host""" , type=__lowerCamelCase , default="""localhost""" , help="""Interface the server will listen on.""" ) serve_parser.add_argument("""--port""" , type=__lowerCamelCase , default=8888 , help="""Port the serving will listen to.""" ) serve_parser.add_argument("""--workers""" , type=__lowerCamelCase , default=1 , help="""Number of http workers""" ) serve_parser.add_argument("""--model""" , type=__lowerCamelCase , help="""Model\'s name or path to stored model.""" ) serve_parser.add_argument("""--config""" , type=__lowerCamelCase , help="""Model\'s config name or path to stored model.""" ) serve_parser.add_argument("""--tokenizer""" , type=__lowerCamelCase , help="""Tokenizer name to use.""" ) serve_parser.add_argument( """--device""" , type=__lowerCamelCase , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) serve_parser.set_defaults(func=__lowerCamelCase ) def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =pipeline lowerCamelCase_ =host lowerCamelCase_ =port lowerCamelCase_ =workers if not _serve_dependencies_installed: raise RuntimeError( """Using serve command requires FastAPI and uvicorn. """ """Please install transformers with [serving]: pip install \"transformers[serving]\".""" """Or install FastAPI and uvicorn separately.""" ) else: logger.info(f'Serving model over {host}:{port}' ) lowerCamelCase_ =FastAPI( routes=[ APIRoute( """/""" , self.model_info , response_model=__lowerCamelCase , response_class=__lowerCamelCase , methods=["""GET"""] , ), APIRoute( """/tokenize""" , self.tokenize , response_model=__lowerCamelCase , response_class=__lowerCamelCase , methods=["""POST"""] , ), APIRoute( """/detokenize""" , self.detokenize , response_model=__lowerCamelCase , response_class=__lowerCamelCase , methods=["""POST"""] , ), APIRoute( """/forward""" , self.forward , response_model=__lowerCamelCase , response_class=__lowerCamelCase , methods=["""POST"""] , ), ] , timeout=600 , ) def _snake_case ( self )-> Optional[Any]: run(self._app , host=self.host , port=self.port , workers=self.workers ) def _snake_case ( self )-> List[str]: return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE = Body(__lowerCamelCase , embed=__lowerCamelCase ) , _SCREAMING_SNAKE_CASE = Body(__lowerCamelCase , embed=__lowerCamelCase ) )-> Any: try: lowerCamelCase_ =self._pipeline.tokenizer.tokenize(__lowerCamelCase ) if return_ids: lowerCamelCase_ =self._pipeline.tokenizer.convert_tokens_to_ids(__lowerCamelCase ) return ServeTokenizeResult(tokens=__lowerCamelCase , tokens_ids=__lowerCamelCase ) else: return ServeTokenizeResult(tokens=__lowerCamelCase ) except Exception as e: raise HTTPException(status_code=500 , detail={"""model""": """""", """error""": str(__lowerCamelCase )} ) def _snake_case ( self , _SCREAMING_SNAKE_CASE = Body(__lowerCamelCase , embed=__lowerCamelCase ) , _SCREAMING_SNAKE_CASE = Body(__lowerCamelCase , embed=__lowerCamelCase ) , _SCREAMING_SNAKE_CASE = Body(__lowerCamelCase , embed=__lowerCamelCase ) , )-> List[str]: try: lowerCamelCase_ =self._pipeline.tokenizer.decode(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return ServeDeTokenizeResult(model="""""" , text=__lowerCamelCase ) except Exception as e: raise HTTPException(status_code=500 , detail={"""model""": """""", """error""": str(__lowerCamelCase )} ) async def _snake_case ( self , _SCREAMING_SNAKE_CASE=Body(__lowerCamelCase , embed=__lowerCamelCase ) )-> Optional[Any]: if len(__lowerCamelCase ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model lowerCamelCase_ =self._pipeline(__lowerCamelCase ) return ServeForwardResult(output=__lowerCamelCase ) except Exception as e: raise HTTPException(500 , {"""error""": str(__lowerCamelCase )} )
701
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __A : int = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Any = "albert" def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =vocab_size lowerCamelCase_ =embedding_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_hidden_groups lowerCamelCase_ =num_attention_heads lowerCamelCase_ =inner_group_num lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =position_embedding_type class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
75
0
import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( UpperCAmelCase_ , unittest.TestCase): _UpperCamelCase:Any = BlenderbotSmallTokenizer _UpperCamelCase:Tuple = False def _snake_case ( self )-> List[Any]: super().setUp() lowerCamelCase_ =["""__start__""", """adapt""", """act""", """ap@@""", """te""", """__end__""", """__unk__"""] lowerCamelCase_ =dict(zip(_lowercase , range(len(_lowercase ) ) ) ) lowerCamelCase_ =["""#version: 0.2""", """a p""", """t e</w>""", """ap t</w>""", """a d""", """ad apt</w>""", """a c""", """ac t</w>""", """"""] lowerCamelCase_ ={"""unk_token""": """__unk__""", """bos_token""": """__start__""", """eos_token""": """__end__"""} lowerCamelCase_ =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCamelCase_ =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(_lowercase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_lowercase ) ) def _snake_case ( self , **_SCREAMING_SNAKE_CASE )-> List[Any]: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **_lowercase ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Any: lowerCamelCase_ ="""adapt act apte""" lowerCamelCase_ ="""adapt act apte""" return input_text, output_text def _snake_case ( self )-> Dict: lowerCamelCase_ =BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCamelCase_ ="""adapt act apte""" lowerCamelCase_ =["""adapt""", """act""", """ap@@""", """te"""] lowerCamelCase_ =tokenizer.tokenize(_lowercase ) self.assertListEqual(_lowercase , _lowercase ) lowerCamelCase_ =[tokenizer.bos_token] + tokens + [tokenizer.eos_token] lowerCamelCase_ =[0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase ) , _lowercase ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) assert tok("""sam""" ).input_ids == [1384] lowerCamelCase_ ="""I am a small frog.""" lowerCamelCase_ =tok([src_text] , padding=_lowercase , truncation=_lowercase )["""input_ids"""] lowerCamelCase_ =tok.batch_decode(_lowercase , skip_special_tokens=_lowercase , clean_up_tokenization_spaces=_lowercase )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _snake_case ( self )-> str: lowerCamelCase_ =BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) lowerCamelCase_ ="""I am a small frog .""" lowerCamelCase_ =""".""" lowerCamelCase_ =tok(_lowercase )["""input_ids"""] lowerCamelCase_ =tok(_lowercase )["""input_ids"""] assert encoded[-1] == encoded_dot[0]
702
from collections import deque from math import floor from random import random from time import time class _SCREAMING_SNAKE_CASE : def __init__( self )-> List[str]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[Any]: if self.graph.get(_SCREAMING_SNAKE_CASE ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase_ =[[w, v]] if not self.graph.get(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[] def _snake_case ( self )-> str: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> Optional[Any]: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Any: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return len(self.graph[u] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Union[str, Any]: lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =[] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return sorted_nodes def _snake_case ( self )-> str: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> List[str]: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin class _SCREAMING_SNAKE_CASE : def __init__( self )-> Optional[Any]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[str]: # check if the u exists if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase_ =[[w, v]] # add the other way if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase_ =[[w, u]] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) # the other way round if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> int: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return len(self.graph[u] ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self )-> Optional[Any]: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> str: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Dict: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin
75
0
import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger __A : Union[str, Any] = '<<<<<<< This should probably be modified because it mentions: ' __A : Optional[Any] = '=======\n>>>>>>>\n' __A : int = [ 'TextEncoderConfig', 'ByteTextEncoder', 'SubwordTextEncoder', 'encoder_config', 'maybe_build_from_corpus', 'manual_dir', ] __A : Optional[int] = [ # (pattern, replacement) # Order is important here for some replacements (R'tfds\.core', R'datasets'), (R'tf\.io\.gfile\.GFile', R'open'), (R'tf\.([\w\d]+)', R'datasets.Value(\'\1\')'), (R'tfds\.features\.Text\(\)', R'datasets.Value(\'string\')'), (R'tfds\.features\.Text\(', R'datasets.Value(\'string\'),'), (R'features\s*=\s*tfds.features.FeaturesDict\(', R'features=datasets.Features('), (R'tfds\.features\.FeaturesDict\(', R'dict('), (R'The TensorFlow Datasets Authors', R'The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'), (R'tfds\.', R'datasets.'), (R'dl_manager\.manual_dir', R'self.config.data_dir'), (R'self\.builder_config', R'self.config'), ] def __UpperCamelCase ( _A : Tuple ) ->List[Any]: """simple docstring""" return ConvertCommand(args.tfds_path , args.datasets_directory ) class _SCREAMING_SNAKE_CASE ( snake_case__): @staticmethod def _snake_case ( _SCREAMING_SNAKE_CASE )-> Union[str, Any]: lowerCamelCase_ =parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=lowercase_ , required=lowercase_ , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=lowercase_ , required=lowercase_ , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=lowercase_ ) def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =get_logger("""datasets-cli/converting""" ) lowerCamelCase_ =tfds_path lowerCamelCase_ =datasets_directory def _snake_case ( self )-> Any: if os.path.isdir(self._tfds_path ): lowerCamelCase_ =os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): lowerCamelCase_ =os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) lowerCamelCase_ =os.path.abspath(self._datasets_directory ) self._logger.info(f'Converting datasets from {abs_tfds_path} to {abs_datasets_path}' ) lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ ={} if os.path.isdir(self._tfds_path ): lowerCamelCase_ =os.listdir(lowercase_ ) else: lowerCamelCase_ =[os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'Looking at file {f_name}' ) lowerCamelCase_ =os.path.join(lowercase_ , lowercase_ ) lowerCamelCase_ =os.path.join(lowercase_ , lowercase_ ) if not os.path.isfile(lowercase_ ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(lowercase_ , encoding="""utf-8""" ) as f: lowerCamelCase_ =f.readlines() lowerCamelCase_ =[] lowerCamelCase_ =False lowerCamelCase_ =False lowerCamelCase_ =[] for line in lines: lowerCamelCase_ =line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: lowerCamelCase_ ="import datasets\n" elif "import tensorflow" in out_line: # order is important here lowerCamelCase_ ="" continue elif "from absl import logging" in out_line: lowerCamelCase_ ="from datasets import logging\n" elif "getLogger" in out_line: lowerCamelCase_ =out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): lowerCamelCase_ =True lowerCamelCase_ =list(filter(lambda _SCREAMING_SNAKE_CASE : e in out_line , lowercase_ ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowercase_ ) + """\n""" ) out_lines.append(lowercase_ ) out_lines.append(lowercase_ ) continue else: for pattern, replacement in TO_CONVERT: lowerCamelCase_ =re.sub(lowercase_ , lowercase_ , lowercase_ ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: lowerCamelCase_ =re.match(R"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , lowercase_ ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) lowerCamelCase_ ="from . import " + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'Error converting {out_line.strip()}' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: lowerCamelCase_ =True out_lines.append(lowercase_ ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset lowerCamelCase_ =f_name.replace(""".py""" , """""" ) lowerCamelCase_ =os.path.join(lowercase_ , lowercase_ ) lowerCamelCase_ =os.path.join(lowercase_ , lowercase_ ) os.makedirs(lowercase_ , exist_ok=lowercase_ ) self._logger.info(f'Adding directory {output_dir}' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(lowercase_ ) if needs_manual_update: with_manual_update.append(lowercase_ ) with open(lowercase_ , """w""" , encoding="""utf-8""" ) as f: f.writelines(lowercase_ ) self._logger.info(f'Converted in {output_file}' ) for utils_file in utils_files: try: lowerCamelCase_ =os.path.basename(lowercase_ ) lowerCamelCase_ =imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'Moving {dest_folder} to {utils_file}' ) shutil.copy(lowercase_ , lowercase_ ) except KeyError: self._logger.error(f'Cannot find destination folder for {utils_file}. Please copy manually.' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.' )
703
import os from datetime import datetime as dt from github import Github __A : Optional[int] = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase_ =g.get_repo("""huggingface/diffusers""" ) lowerCamelCase_ =repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase_ =sorted(issue.get_comments() , key=lambda _A : i.created_at , reverse=_A ) lowerCamelCase_ =comments[0] if len(_A ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
75
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : List[Any] = {"configuration_sew": ["SEW_PRETRAINED_CONFIG_ARCHIVE_MAP", "SEWConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ "SEW_PRETRAINED_MODEL_ARCHIVE_LIST", "SEWForCTC", "SEWForSequenceClassification", "SEWModel", "SEWPreTrainedModel", ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys __A : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
704
import argparse import os import re __A : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. __A : int = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. __A : int = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Optional[Any] = re.compile(R'\[([^\]]+)\]') def __UpperCamelCase ( _A : int ) ->Dict: """simple docstring""" lowerCamelCase_ =_re_indent.search(_A ) return "" if search is None else search.groups()[0] def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 lowerCamelCase_ =["""\n""".join(lines[:index] )] else: lowerCamelCase_ =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ =[lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_A ) ) if index < len(_A ) - 1: lowerCamelCase_ =[lines[index + 1]] index += 1 else: lowerCamelCase_ =[] else: blocks.append("""\n""".join(_A ) ) lowerCamelCase_ =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append("""\n""".join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def __UpperCamelCase ( _A : Optional[int] ) ->Optional[int]: """simple docstring""" def _inner(_A : Optional[Any] ): return key(_A ).lower().replace("""_""" , """""" ) return _inner def __UpperCamelCase ( _A : int , _A : List[Any]=None ) ->List[str]: """simple docstring""" # If no key is provided, we use a noop. def noop(_A : List[str] ): return x if key is None: lowerCamelCase_ =noop # Constants are all uppercase, they go first. lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()] lowerCamelCase_ =ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def __UpperCamelCase ( _A : List[str] ) ->List[str]: """simple docstring""" # This inner function sort imports between [ ]. def _replace(_A : Optional[Any] ): lowerCamelCase_ =match.groups()[0] if "," not in imports: return f'[{imports}]' lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" lowerCamelCase_ =import_statement.split("""\n""" ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase_ =2 if lines[1].strip() == """[""" else 1 lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] ) lowerCamelCase_ =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase_ =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] lowerCamelCase_ =get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase_ =_re_bracket_content.sub(_replace , _A ) return import_statement def __UpperCamelCase ( _A : List[Any] , _A : Optional[Any]=True ) ->str: """simple docstring""" with open(_A , """r""" ) as f: lowerCamelCase_ =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ =split_code_in_indented_blocks( _A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ =main_blocks[block_idx] lowerCamelCase_ =block.split("""\n""" ) # Get to the start of the imports. lowerCamelCase_ =0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase_ =len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] ) lowerCamelCase_ =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ =_re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase_ =[(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase_ =[(i, key) for i, key in enumerate(_A ) if key is not None] lowerCamelCase_ =[x[0] for x in sorted(_A , key=lambda _A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase_ =0 lowerCamelCase_ =[] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , """w""" ) as f: f.write("""\n""".join(_A ) ) def __UpperCamelCase ( _A : str=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A ) if result: lowerCamelCase_ =[os.path.join(_A , """__init__.py""" )] if len(_A ) > 0: raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') __A : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
75
0
def __UpperCamelCase ( _A : int = 1000 ) ->int: """simple docstring""" lowerCamelCase_ =2**power lowerCamelCase_ =str(_lowerCamelCase ) lowerCamelCase_ =list(_lowerCamelCase ) lowerCamelCase_ =0 for i in list_num: sum_of_num += int(_lowerCamelCase ) return sum_of_num if __name__ == "__main__": __A : Any = int(input('Enter the power of 2: ').strip()) print('2 ^ ', power, ' = ', 2**power) __A : Optional[int] = solution(power) print('Sum of the digits is: ', result)
705
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : str = {'vocab_file': 'sentencepiece.model'} __A : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } __A : int = { 'google/rembert': 2_56, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Dict: return len(self.sp_model ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> Optional[Any]: lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =d lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
75
0
import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_COMMIT_HASH from huggingface_hub.utils import ( EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError, is_jinja_available, ) from packaging import version from requests import HTTPError from .. import __version__ from .constants import ( DEPRECATED_REVISION_ARGS, DIFFUSERS_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, ) from .import_utils import ( ENV_VARS_TRUE_VALUES, _flax_version, _jax_version, _onnxruntime_version, _torch_version, is_flax_available, is_onnx_available, is_torch_available, ) from .logging import get_logger __A : Any = get_logger(__name__) __A : Union[str, Any] = Path(__file__).parent / "model_card_template.md" __A : int = uuida().hex __A : Optional[Any] = os.getenv('HF_HUB_OFFLINE', '').upper() in ENV_VARS_TRUE_VALUES __A : Union[str, Any] = os.getenv('DISABLE_TELEMETRY', '').upper() in ENV_VARS_TRUE_VALUES __A : Union[str, Any] = HUGGINGFACE_CO_RESOLVE_ENDPOINT + "/api/telemetry/" def __UpperCamelCase ( _A : Union[Dict, str, None] = None ) ->List[str]: """simple docstring""" lowerCamelCase_ =f'diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}' if DISABLE_TELEMETRY or HF_HUB_OFFLINE: return ua + "; telemetry/off" if is_torch_available(): ua += f'; torch/{_torch_version}' if is_flax_available(): ua += f'; jax/{_jax_version}' ua += f'; flax/{_flax_version}' if is_onnx_available(): ua += f'; onnxruntime/{_onnxruntime_version}' # CI will set this value to True if os.environ.get("""DIFFUSERS_IS_CI""" , """""" ).upper() in ENV_VARS_TRUE_VALUES: ua += "; is_ci/true" if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): ua += "; " + "; ".join(f'{k}/{v}' for k, v in user_agent.items() ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): ua += "; " + user_agent return ua def __UpperCamelCase ( _A : str , _A : Optional[str] = None , _A : Optional[str] = None ) ->str: """simple docstring""" if token is None: lowerCamelCase_ =HfFolder.get_token() if organization is None: lowerCamelCase_ =whoami(_SCREAMING_SNAKE_CASE )["""name"""] return f'{username}/{model_id}' else: return f'{organization}/{model_id}' def __UpperCamelCase ( _A : int , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" if not is_jinja_available(): raise ValueError( """Modelcard rendering is based on Jinja templates.""" """ Please make sure to have `jinja` installed before using `create_model_card`.""" """ To install it, please run `pip install Jinja2`.""" ) if hasattr(_SCREAMING_SNAKE_CASE , """local_rank""" ) and args.local_rank not in [-1, 0]: return lowerCamelCase_ =args.hub_token if hasattr(_SCREAMING_SNAKE_CASE , """hub_token""" ) else None lowerCamelCase_ =get_full_repo_name(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =ModelCard.from_template( card_data=ModelCardData( # Card metadata object that will be converted to YAML block language="""en""" , license="""apache-2.0""" , library_name="""diffusers""" , tags=[] , datasets=args.dataset_name , metrics=[] , ) , template_path=_SCREAMING_SNAKE_CASE , model_name=_SCREAMING_SNAKE_CASE , repo_name=_SCREAMING_SNAKE_CASE , dataset_name=args.dataset_name if hasattr(_SCREAMING_SNAKE_CASE , """dataset_name""" ) else None , learning_rate=args.learning_rate , train_batch_size=args.train_batch_size , eval_batch_size=args.eval_batch_size , gradient_accumulation_steps=( args.gradient_accumulation_steps if hasattr(_SCREAMING_SNAKE_CASE , """gradient_accumulation_steps""" ) else None ) , adam_betaa=args.adam_betaa if hasattr(_SCREAMING_SNAKE_CASE , """adam_beta1""" ) else None , adam_betaa=args.adam_betaa if hasattr(_SCREAMING_SNAKE_CASE , """adam_beta2""" ) else None , adam_weight_decay=args.adam_weight_decay if hasattr(_SCREAMING_SNAKE_CASE , """adam_weight_decay""" ) else None , adam_epsilon=args.adam_epsilon if hasattr(_SCREAMING_SNAKE_CASE , """adam_epsilon""" ) else None , lr_scheduler=args.lr_scheduler if hasattr(_SCREAMING_SNAKE_CASE , """lr_scheduler""" ) else None , lr_warmup_steps=args.lr_warmup_steps if hasattr(_SCREAMING_SNAKE_CASE , """lr_warmup_steps""" ) else None , ema_inv_gamma=args.ema_inv_gamma if hasattr(_SCREAMING_SNAKE_CASE , """ema_inv_gamma""" ) else None , ema_power=args.ema_power if hasattr(_SCREAMING_SNAKE_CASE , """ema_power""" ) else None , ema_max_decay=args.ema_max_decay if hasattr(_SCREAMING_SNAKE_CASE , """ema_max_decay""" ) else None , mixed_precision=args.mixed_precision , ) lowerCamelCase_ =os.path.join(args.output_dir , """README.md""" ) model_card.save(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( _A : Optional[str] , _A : Optional[str] = None ) ->Dict: """simple docstring""" if resolved_file is None or commit_hash is not None: return commit_hash lowerCamelCase_ =str(Path(_SCREAMING_SNAKE_CASE ).as_posix() ) lowerCamelCase_ =re.search(R"""snapshots/([^/]+)/""" , _SCREAMING_SNAKE_CASE ) if search is None: return None lowerCamelCase_ =search.groups()[0] return commit_hash if REGEX_COMMIT_HASH.match(_SCREAMING_SNAKE_CASE ) else None # Old default cache path, potentially to be migrated. # This logic was more or less taken from `transformers`, with the following differences: # - Diffusers doesn't use custom environment variables to specify the cache path. # - There is no need to migrate the cache format, just move the files to the new location. __A : Dict = os.path.expanduser( os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface')) ) __A : Optional[int] = os.path.join(hf_cache_home, 'diffusers') def __UpperCamelCase ( _A : Optional[str] = None , _A : Optional[str] = None ) ->Tuple: """simple docstring""" if new_cache_dir is None: lowerCamelCase_ =DIFFUSERS_CACHE if old_cache_dir is None: lowerCamelCase_ =old_diffusers_cache lowerCamelCase_ =Path(_SCREAMING_SNAKE_CASE ).expanduser() lowerCamelCase_ =Path(_SCREAMING_SNAKE_CASE ).expanduser() for old_blob_path in old_cache_dir.glob("""**/blobs/*""" ): if old_blob_path.is_file() and not old_blob_path.is_symlink(): lowerCamelCase_ =new_cache_dir / old_blob_path.relative_to(_SCREAMING_SNAKE_CASE ) new_blob_path.parent.mkdir(parents=_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) os.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) try: os.symlink(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) except OSError: logger.warning( """Could not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded.""" ) # At this point, old_cache_dir contains symlinks to the new cache (it can still be used). __A : Optional[Any] = os.path.join(DIFFUSERS_CACHE, 'version_diffusers_cache.txt') if not os.path.isfile(cache_version_file): __A : Optional[Any] = 0 else: with open(cache_version_file) as f: try: __A : Tuple = int(f.read()) except ValueError: __A : int = 0 if cache_version < 1: __A : List[Any] = os.path.isdir(old_diffusers_cache) and len(os.listdir(old_diffusers_cache)) > 0 if old_cache_is_not_empty: logger.warning( 'The cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your ' 'existing cached models. This is a one-time operation, you can interrupt it or run it ' 'later by calling `diffusers.utils.hub_utils.move_cache()`.' ) try: move_cache() except Exception as e: __A : Optional[int] = "\n".join(traceback.format_tb(e.__traceback__)) logger.error( F"""There was a problem when trying to move your cache:\n\n{trace}\n{e.__class__.__name__}: {e}\n\nPlease """ 'file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole ' 'message and we will do our best to help.' ) if cache_version < 1: try: os.makedirs(DIFFUSERS_CACHE, exist_ok=True) with open(cache_version_file, 'w') as f: f.write('1') except Exception: logger.warning( F"""There was a problem when trying to write in your cache folder ({DIFFUSERS_CACHE}). Please, ensure """ 'the directory exists and can be written to.' ) def __UpperCamelCase ( _A : str , _A : Optional[str] = None ) ->Optional[Any]: """simple docstring""" if variant is not None: lowerCamelCase_ =weights_name.split(""".""" ) lowerCamelCase_ =splits[:-1] + [variant] + splits[-1:] lowerCamelCase_ =""".""".join(_SCREAMING_SNAKE_CASE ) return weights_name def __UpperCamelCase ( _A : str , *, _A : Tuple , _A : Optional[Any] , _A : int , _A : str , _A : Union[str, Any] , _A : Any , _A : str , _A : int , _A : Tuple , _A : str , _A : List[Any]=None , ) ->List[Any]: """simple docstring""" lowerCamelCase_ =str(_SCREAMING_SNAKE_CASE ) if os.path.isfile(_SCREAMING_SNAKE_CASE ): return pretrained_model_name_or_path elif os.path.isdir(_SCREAMING_SNAKE_CASE ): if os.path.isfile(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ): # Load from a PyTorch checkpoint lowerCamelCase_ =os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return model_file elif subfolder is not None and os.path.isfile( os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ): lowerCamelCase_ =os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return model_file else: raise EnvironmentError( f'Error no file named {weights_name} found in directory {pretrained_model_name_or_path}.' ) else: # 1. First check if deprecated way of loading from branches is used if ( revision in DEPRECATED_REVISION_ARGS and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME) and version.parse(version.parse(_SCREAMING_SNAKE_CASE ).base_version ) >= version.parse("""0.20.0""" ) ): try: lowerCamelCase_ =hf_hub_download( _SCREAMING_SNAKE_CASE , filename=_add_variant(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , cache_dir=_SCREAMING_SNAKE_CASE , force_download=_SCREAMING_SNAKE_CASE , proxies=_SCREAMING_SNAKE_CASE , resume_download=_SCREAMING_SNAKE_CASE , local_files_only=_SCREAMING_SNAKE_CASE , use_auth_token=_SCREAMING_SNAKE_CASE , user_agent=_SCREAMING_SNAKE_CASE , subfolder=_SCREAMING_SNAKE_CASE , revision=revision or commit_hash , ) warnings.warn( f'Loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'` is deprecated. Loading instead from `revision=\'main\'` with `variant={revision}`. Loading model variants via `revision=\'{revision}\'` will be removed in diffusers v1. Please use `variant=\'{revision}\'` instead.' , _SCREAMING_SNAKE_CASE , ) return model_file except: # noqa: E722 warnings.warn( f'You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant=\'{revision}\'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} file in the \'main\' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title \'{pretrained_model_name_or_path} is missing {_add_variant(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}\' so that the correct variant file can be added.' , _SCREAMING_SNAKE_CASE , ) try: # 2. Load model file as usual lowerCamelCase_ =hf_hub_download( _SCREAMING_SNAKE_CASE , filename=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , force_download=_SCREAMING_SNAKE_CASE , proxies=_SCREAMING_SNAKE_CASE , resume_download=_SCREAMING_SNAKE_CASE , local_files_only=_SCREAMING_SNAKE_CASE , use_auth_token=_SCREAMING_SNAKE_CASE , user_agent=_SCREAMING_SNAKE_CASE , subfolder=_SCREAMING_SNAKE_CASE , revision=revision or commit_hash , ) return model_file except RepositoryNotFoundError: raise EnvironmentError( f'{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier ' """listed on \'https://huggingface.co/models\'\nIf this is a private repository, make sure to pass a """ """token having permission to this repo with `use_auth_token` or log in with `huggingface-cli """ """login`.""" ) except RevisionNotFoundError: raise EnvironmentError( f'{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for ' """this model name. Check the model page at """ f'\'https://huggingface.co/{pretrained_model_name_or_path}\' for available revisions.' ) except EntryNotFoundError: raise EnvironmentError( f'{pretrained_model_name_or_path} does not appear to have a file named {weights_name}.' ) except HTTPError as err: raise EnvironmentError( f'There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}' ) except ValueError: raise EnvironmentError( f'We couldn\'t connect to \'{HUGGINGFACE_CO_RESOLVE_ENDPOINT}\' to load this model, couldn\'t find it' f' in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a' f' directory containing a file named {weights_name} or' """ \nCheckout your internet connection or see how to run the library in""" """ offline mode at \'https://huggingface.co/docs/diffusers/installation#offline-mode\'.""" ) except EnvironmentError: raise EnvironmentError( f'Can\'t load the model for \'{pretrained_model_name_or_path}\'. If you were trying to load it from ' """\'https://huggingface.co/models\', make sure you don\'t have a local directory with the same name. """ f'Otherwise, make sure \'{pretrained_model_name_or_path}\' is the correct path to a directory ' f'containing a file named {weights_name}' )
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
75
0
from collections.abc import Sequence from queue import Queue class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Tuple: lowerCamelCase_ =start lowerCamelCase_ =end lowerCamelCase_ =val lowerCamelCase_ =(start + end) // 2 lowerCamelCase_ =left lowerCamelCase_ =right def __repr__( self )-> Dict: return f'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =collection lowerCamelCase_ =function if self.collection: lowerCamelCase_ =self._build_tree(0 , len(_SCREAMING_SNAKE_CASE ) - 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Any: self._update_tree(self.root , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self._query_range(self.root , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[Any]: if start == end: return SegmentTreeNode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.collection[start] ) lowerCamelCase_ =(start + end) // 2 lowerCamelCase_ =self._build_tree(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self._build_tree(mid + 1 , _SCREAMING_SNAKE_CASE ) return SegmentTreeNode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.fn(left.val , right.val ) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> str: if node.start == i and node.end == i: lowerCamelCase_ =val return if i <= node.mid: self._update_tree(node.left , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: self._update_tree(node.right , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.fn(node.left.val , node.right.val ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[str]: if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , _SCREAMING_SNAKE_CASE , node.mid ) , self._query_range(node.right , node.mid + 1 , _SCREAMING_SNAKE_CASE ) , ) else: # range in right child tree return self._query_range(node.right , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Dict: if self.root is not None: lowerCamelCase_ =Queue() queue.put(self.root ) while not queue.empty(): lowerCamelCase_ =queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('*' * 50) __A : int = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
707
# 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.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input __A : List[str] = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def __UpperCamelCase ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =_ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase_ =get_sagemaker_input() else: lowerCamelCase_ =get_cluster_input() return config def __UpperCamelCase ( _A : List[str]=None ) ->str: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""config""" , description=_A ) else: lowerCamelCase_ =argparse.ArgumentParser("""Accelerate config command""" , description=_A ) parser.add_argument( """--config_file""" , default=_A , 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=_A ) return parser def __UpperCamelCase ( _A : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =get_user_input() if args.config_file is not None: lowerCamelCase_ =args.config_file else: if not os.path.isdir(_A ): os.makedirs(_A ) lowerCamelCase_ =default_yaml_config_file if config_file.endswith(""".json""" ): config.to_json_file(_A ) else: config.to_yaml_file(_A ) print(f'accelerate configuration saved at {config_file}' ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =config_command_parser() lowerCamelCase_ =parser.parse_args() config_command(_A ) if __name__ == "__main__": main()
75
0
'''simple docstring''' import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def __UpperCamelCase ( _A : Optional[Any] , _A : List[Any] , _A : Optional[Any] , _A : Tuple=1024 ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[], [] lowerCamelCase_ =list(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ) lowerCamelCase_ =sorted_examples[0] def is_too_big(_A : List[str] ): return tok(lowerCAmelCase__ , return_tensors="""pt""" ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): lowerCamelCase_ =new_src + ' ' + src lowerCamelCase_ =new_tgt + ' ' + tgt if is_too_big(lowerCAmelCase__ ) or is_too_big(lowerCAmelCase__ ): # cant fit, finalize example finished_src.append(lowerCAmelCase__ ) finished_tgt.append(lowerCAmelCase__ ) lowerCamelCase_ =src, tgt else: # can fit, keep adding lowerCamelCase_ =cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(lowerCAmelCase__ ) finished_tgt.append(lowerCAmelCase__ ) return finished_src, finished_tgt def __UpperCamelCase ( _A : Dict , _A : Path , _A : List[Any] , _A : Optional[int] ) ->List[str]: """simple docstring""" lowerCamelCase_ =Path(lowerCAmelCase__ ) save_path.mkdir(exist_ok=lowerCAmelCase__ ) for split in ["train"]: lowerCamelCase_ =data_dir / f'{split}.source', data_dir / f'{split}.target' lowerCamelCase_ =[x.rstrip() for x in Path(lowerCAmelCase__ ).open().readlines()] lowerCamelCase_ =[x.rstrip() for x in Path(lowerCAmelCase__ ).open().readlines()] lowerCamelCase_ =pack_examples(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) print(f'packed {split} split from {len(lowerCAmelCase__ )} examples -> {len(lowerCAmelCase__ )}.' ) Path(save_path / f'{split}.source' ).open("""w""" ).write("""\n""".join(lowerCAmelCase__ ) ) Path(save_path / f'{split}.target' ).open("""w""" ).write("""\n""".join(lowerCAmelCase__ ) ) for split in ["val", "test"]: lowerCamelCase_ =data_dir / f'{split}.source', data_dir / f'{split}.target' shutil.copyfile(lowerCAmelCase__ , save_path / f'{split}.source' ) shutil.copyfile(lowerCAmelCase__ , save_path / f'{split}.target' ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =argparse.ArgumentParser() parser.add_argument("""--tok_name""" , type=lowerCAmelCase__ , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""--max_seq_len""" , type=lowerCAmelCase__ , default=128 ) parser.add_argument("""--data_dir""" , type=lowerCAmelCase__ ) parser.add_argument("""--save_path""" , type=lowerCAmelCase__ ) lowerCamelCase_ =parser.parse_args() lowerCamelCase_ =AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(lowerCAmelCase__ , Path(args.data_dir ) , args.max_seq_len , args.save_path ) if __name__ == "__main__": packer_cli()
708
def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[[] for _ in range(_A )] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_A ) <= key: return input_string for position, character in enumerate(_A ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_A ) lowerCamelCase_ =["""""".join(_A ) for row in temp_grid] lowerCamelCase_ ="""""".join(_A ) return output_string def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string lowerCamelCase_ =[[] for _ in range(_A )] # generates template for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) lowerCamelCase_ =0 for row in temp_grid: # fills in the characters lowerCamelCase_ =input_string[counter : counter + len(_A )] grid.append(list(_A ) ) counter += len(_A ) lowerCamelCase_ ="""""" # reads as zigzag for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __UpperCamelCase ( _A : str ) ->dict[int, str]: """simple docstring""" lowerCamelCase_ ={} for key_guess in range(1 , len(_A ) ): # tries every key lowerCamelCase_ =decrypt(_A , _A ) return results if __name__ == "__main__": import doctest doctest.testmod()
75
0
import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging __A : List[Any] = logging.get_logger(__name__) def __lowercase ( ) ->Optional[int]: """simple docstring""" # Get the sagemaker specific mp parameters from smp_options variable. lowerCamelCase_ =os.getenv("""SM_HP_MP_PARAMETERS""" , """{}""" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. lowerCamelCase_ =json.loads(_A ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. lowerCamelCase_ =os.getenv("""SM_FRAMEWORK_PARAMS""" , """{}""" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". lowerCamelCase_ =json.loads(_A ) if not mpi_options.get("""sagemaker_mpi_enabled""" , _A ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("""smdistributed""" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class _SCREAMING_SNAKE_CASE ( a__): _UpperCamelCase:str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def _snake_case ( self )-> Tuple: super().__post_init__() warnings.warn( """`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use """ """`TrainingArguments` instead.""" , lowerCamelCase_ , ) @cached_property def _snake_case ( self )-> "torch.device": logger.info("""PyTorch: setting up devices""" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( """torch.distributed process group is initialized, but local_rank == -1. """ """In order to use Torch DDP, launch your script with `python -m torch.distributed.launch""" ) if self.no_cuda: lowerCamelCase_ =torch.device("""cpu""" ) lowerCamelCase_ =0 elif is_sagemaker_model_parallel_available(): lowerCamelCase_ =smp.local_rank() lowerCamelCase_ =torch.device("""cuda""" , lowerCamelCase_ ) lowerCamelCase_ =1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="""smddp""" , timeout=self.ddp_timeout_delta ) lowerCamelCase_ =int(os.getenv("""SMDATAPARALLEL_LOCAL_RANK""" ) ) lowerCamelCase_ =torch.device("""cuda""" , self.local_rank ) lowerCamelCase_ =1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 lowerCamelCase_ =torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. lowerCamelCase_ =torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="""nccl""" , timeout=self.ddp_timeout_delta ) lowerCamelCase_ =torch.device("""cuda""" , self.local_rank ) lowerCamelCase_ =1 if device.type == "cuda": torch.cuda.set_device(lowerCamelCase_ ) return device @property def _snake_case ( self )-> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def _snake_case ( self )-> int: return not is_sagemaker_model_parallel_available() @property def _snake_case ( self )-> Tuple: return False
709
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =data lowerCamelCase_ =None class _SCREAMING_SNAKE_CASE : def __init__( self )-> Any: lowerCamelCase_ =None def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.head while temp is not None: print(temp.data , end=""" """ ) lowerCamelCase_ =temp.next print() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =Node(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.head lowerCamelCase_ =new_node def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if node_data_a == node_data_a: return else: lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ =node_a.data, node_a.data if __name__ == "__main__": __A : Optional[int] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
75
0
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 __A : List[Any] = get_tests_dir('fixtures') __A : List[Any] = get_tests_dir('fixtures/dummy_feature_extractor_config.json') __A : int = get_tests_dir('fixtures/dummy-config.json') class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =0 def _snake_case ( self )-> List[str]: lowerCamelCase_ =AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) def _snake_case ( self )-> str: lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) def _snake_case ( self )-> Any: with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ =WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(UpperCamelCase__ ).to_dict() config_dict.pop("""feature_extractor_type""" ) lowerCamelCase_ =WavaVecaFeatureExtractor(**UpperCamelCase__ ) # save in new folder model_config.save_pretrained(UpperCamelCase__ ) config.save_pretrained(UpperCamelCase__ ) lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(UpperCamelCase__ ) # make sure private variable is not incorrectly saved lowerCamelCase_ =json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) def _snake_case ( self )-> Any: with self.assertRaisesRegex( UpperCamelCase__ , """bert-base is not a local folder and is not a valid model identifier""" ): lowerCamelCase_ =AutoFeatureExtractor.from_pretrained("""bert-base""" ) def _snake_case ( self )-> Optional[int]: with self.assertRaisesRegex( UpperCamelCase__ , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(UpperCamelCase__ , revision="""aaaaaa""" ) def _snake_case ( self )-> int: with self.assertRaisesRegex( UpperCamelCase__ , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): lowerCamelCase_ =AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model""" ) def _snake_case ( self )-> int: with self.assertRaises(UpperCamelCase__ ): lowerCamelCase_ =AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(UpperCamelCase__ ): lowerCamelCase_ =AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=UpperCamelCase__ ) lowerCamelCase_ =AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=UpperCamelCase__ ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(UpperCamelCase__ ) lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(UpperCamelCase__ , trust_remote_code=UpperCamelCase__ ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) def _snake_case ( self )-> List[str]: try: AutoConfig.register("""custom""" , UpperCamelCase__ ) AutoFeatureExtractor.register(UpperCamelCase__ , UpperCamelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCamelCase__ ): AutoFeatureExtractor.register(UpperCamelCase__ , UpperCamelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API lowerCamelCase_ =CustomFeatureExtractor.from_pretrained(UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(UpperCamelCase__ ) lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def _snake_case ( self )-> Any: class _SCREAMING_SNAKE_CASE ( lowercase_): _UpperCamelCase:Optional[Any] = True try: AutoConfig.register("""custom""" , UpperCamelCase__ ) AutoFeatureExtractor.register(UpperCamelCase__ , UpperCamelCase__ ) # If remote code is not set, the default is to use local lowerCamelCase_ =AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. lowerCamelCase_ =AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=UpperCamelCase__ ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub lowerCamelCase_ =AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=UpperCamelCase__ ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(not hasattr(UpperCamelCase__ , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
710
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "yolos" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=[512, 864] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =qkv_bias lowerCamelCase_ =num_detection_tokens lowerCamelCase_ =use_mid_position_embeddings lowerCamelCase_ =auxiliary_loss # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = version.parse("1.11") @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self )-> float: return 1E-4 @property def _snake_case ( self )-> int: return 12
75
0
import warnings warnings.warn( 'memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: ' '`from accelerate import find_executable_batch_size` to avoid this warning.', FutureWarning, )
711
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py __A : List[Any] = 'src/transformers' __A : Tuple = 'docs/source/en' __A : Optional[int] = '.' def __UpperCamelCase ( _A : Tuple , _A : Tuple , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | __A : Dict = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. __A : Optional[int] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Optional[int] = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : str = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. __A : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def __UpperCamelCase ( _A : List[Any] ) ->str: """simple docstring""" lowerCamelCase_ =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _A ) return [m.group(0 ) for m in matches] def __UpperCamelCase ( _A : Union[str, Any] , _A : List[str] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =2 if text == """✅""" or text == """❌""" else len(_A ) lowerCamelCase_ =(width - text_length) // 2 lowerCamelCase_ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCamelCase_ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCamelCase_ ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) # Let's lookup through all transformers object (once). for attr_name in dir(_A ): lowerCamelCase_ =None if attr_name.endswith("""Tokenizer""" ): lowerCamelCase_ =slow_tokenizers lowerCamelCase_ =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): lowerCamelCase_ =fast_tokenizers lowerCamelCase_ =attr_name[:-13] elif _re_tf_models.match(_A ) is not None: lowerCamelCase_ =tf_models lowerCamelCase_ =_re_tf_models.match(_A ).groups()[0] elif _re_flax_models.match(_A ) is not None: lowerCamelCase_ =flax_models lowerCamelCase_ =_re_flax_models.match(_A ).groups()[0] elif _re_pt_models.match(_A ) is not None: lowerCamelCase_ =pt_models lowerCamelCase_ =_re_pt_models.match(_A ).groups()[0] if lookup_dict is not None: while len(_A ) > 0: if attr_name in model_name_to_prefix.values(): lowerCamelCase_ =True break # Try again after removing the last word in the name lowerCamelCase_ ="""""".join(camel_case_split(_A )[:-1] ) # Let's build that table! lowerCamelCase_ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCamelCase_ =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowerCamelCase_ =[len(_A ) + 2 for c in columns] lowerCamelCase_ =max([len(_A ) for name in model_names] ) + 2 # Build the table per se lowerCamelCase_ ="""|""" + """|""".join([_center_text(_A , _A ) for c, w in zip(_A , _A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" lowerCamelCase_ ={True: """✅""", False: """❌"""} for name in model_names: lowerCamelCase_ =model_name_to_prefix[name] lowerCamelCase_ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_A , _A ) for l, w in zip(_A , _A )] ) + "|\n" return table def __UpperCamelCase ( _A : str=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) lowerCamelCase_ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
75
0
import os def __UpperCamelCase ( ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =os.path.dirname(os.path.realpath(a_ ) ) lowerCamelCase_ =os.path.join(a_ , """triangle.txt""" ) with open(a_ ) as f: lowerCamelCase_ =f.readlines() lowerCamelCase_ =[] for line in triangle: lowerCamelCase_ =[] for number in line.strip().split(""" """ ): numbers_from_line.append(int(a_ ) ) a.append(a_ ) for i in range(1 , len(a_ ) ): for j in range(len(a[i] ) ): lowerCamelCase_ =a[i - 1][j] if j != len(a[i - 1] ) else 0 lowerCamelCase_ =a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(a_ , a_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
712
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =num_stages lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =out_features lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =num_stages def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self )-> Union[str, Any]: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_SCREAMING_SNAKE_CASE , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_SCREAMING_SNAKE_CASE , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCamelCase:Any = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Dict = False _UpperCamelCase:int = False _UpperCamelCase:Any = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> int: lowerCamelCase_ =UperNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( 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 _snake_case ( self )-> Tuple: return def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _snake_case ( self )-> List[Any]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> str: pass def _snake_case ( self )-> Optional[int]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =_config_zero_init(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =_config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ =model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _snake_case ( self )-> Dict: pass @slow def _snake_case ( self )-> Tuple: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Tuple: """simple docstring""" lowerCamelCase_ =hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) lowerCamelCase_ =Image.open(_A ).convert("""RGB""" ) return image @require_torch @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def _snake_case ( self )-> int: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
75
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __A : int = logging.get_logger(__name__) # pylint: disable=invalid-name __A : Optional[int] = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n >>> pipe_prior.to("cuda")\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n >>> pipe.to("cuda")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save("cat.png")\n ```\n' def __UpperCamelCase ( _A : List[Any] , _A : Dict , _A : Any=8 ) ->List[Any]: """simple docstring""" lowerCamelCase_ =height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 lowerCamelCase_ =width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class _SCREAMING_SNAKE_CASE ( _a): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , )-> Dict: super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) lowerCamelCase_ =2 ** (len(self.movq.config.block_out_channels ) - 1) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[Any]: if latents is None: lowerCamelCase_ =randn_tensor(_A , generator=_A , device=_A , dtype=_A ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) lowerCamelCase_ =latents.to(_A ) lowerCamelCase_ =latents * scheduler.init_noise_sigma return latents def _snake_case ( self , _SCREAMING_SNAKE_CASE=0 )-> Any: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) lowerCamelCase_ =torch.device(f'cuda:{gpu_id}' ) lowerCamelCase_ =[ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0 )-> str: if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) lowerCamelCase_ =torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) lowerCamelCase_ =None for cpu_offloaded_model in [self.unet, self.movq]: lowerCamelCase_ , lowerCamelCase_ =cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. lowerCamelCase_ =hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _snake_case ( self )-> List[str]: if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(_A , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 100 , _SCREAMING_SNAKE_CASE = 4.0 , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , )-> Optional[int]: lowerCamelCase_ =self._execution_device lowerCamelCase_ =guidance_scale > 1.0 if isinstance(_A , _A ): lowerCamelCase_ =torch.cat(_A , dim=0 ) lowerCamelCase_ =image_embeds.shape[0] * num_images_per_prompt if isinstance(_A , _A ): lowerCamelCase_ =torch.cat(_A , dim=0 ) if do_classifier_free_guidance: lowerCamelCase_ =image_embeds.repeat_interleave(_A , dim=0 ) lowerCamelCase_ =negative_image_embeds.repeat_interleave(_A , dim=0 ) lowerCamelCase_ =torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) self.scheduler.set_timesteps(_A , device=_A ) lowerCamelCase_ =self.scheduler.timesteps lowerCamelCase_ =self.unet.config.in_channels lowerCamelCase_ , lowerCamelCase_ =downscale_height_and_width(_A , _A , self.movq_scale_factor ) # create initial latent lowerCamelCase_ =self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , _A , _A , _A , self.scheduler , ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase_ =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase_ ={"""image_embeds""": image_embeds} lowerCamelCase_ =self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: lowerCamelCase_ , lowerCamelCase_ =noise_pred.split(latents.shape[1] , dim=1 ) lowerCamelCase_ , lowerCamelCase_ =noise_pred.chunk(2 ) lowerCamelCase_ , lowerCamelCase_ =variance_pred.chunk(2 ) lowerCamelCase_ =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) lowerCamelCase_ =torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): lowerCamelCase_ , lowerCamelCase_ =noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ =self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing lowerCamelCase_ =self.movq.decode(_A , force_not_quantize=_A )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: lowerCamelCase_ =image * 0.5 + 0.5 lowerCamelCase_ =image.clamp(0 , 1 ) lowerCamelCase_ =image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowerCamelCase_ =self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
713
from typing import Dict, Iterable, 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, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_MEAN , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_STD , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ =int((256 / 224) * size["""shortest_edge"""] ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""height""": output_size[0], """width""": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( _SCREAMING_SNAKE_CASE , size=(size_dict["""height"""], size_dict["""width"""]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: 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_center_crop if do_center_crop is not None else self.do_center_crop 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_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_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.""" ) # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
75
0
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A : int = transforms.Compose( [ transforms.Resize((2_56, 2_56)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def __UpperCamelCase ( _A : Dict ) ->Tuple: """simple docstring""" if isinstance(UpperCAmelCase__ , torch.Tensor ): return image elif isinstance(UpperCAmelCase__ , PIL.Image.Image ): lowerCamelCase_ =[image] lowerCamelCase_ =[trans(img.convert("""RGB""" ) ) for img in image] lowerCamelCase_ =torch.stack(UpperCAmelCase__ ) return image class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase_ =DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=__UpperCamelCase , scheduler=__UpperCamelCase ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: if strength < 0 or strength > 1: raise ValueError(f'The value of strength should in [0.0, 1.0] but is {strength}' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[Any]: # get the original timestep using init_timestep lowerCamelCase_ =min(int(num_inference_steps * strength ) , __UpperCamelCase ) lowerCamelCase_ =max(num_inference_steps - init_timestep , 0 ) lowerCamelCase_ =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> Optional[Any]: if not isinstance(__UpperCamelCase , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__UpperCamelCase )}' ) lowerCamelCase_ =image.to(device=__UpperCamelCase , dtype=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) and len(__UpperCamelCase ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(__UpperCamelCase )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) lowerCamelCase_ =init_latents.shape lowerCamelCase_ =randn_tensor(__UpperCamelCase , generator=__UpperCamelCase , device=__UpperCamelCase , dtype=__UpperCamelCase ) # get latents print("""add noise to latents at timestep""" , __UpperCamelCase ) lowerCamelCase_ =self.scheduler.add_noise(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) lowerCamelCase_ =init_latents return latents @torch.no_grad() def __call__( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 0.8 , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , )-> str: self.check_inputs(__UpperCamelCase ) # 2. Preprocess image lowerCamelCase_ =preprocess(__UpperCamelCase ) # 3. set timesteps self.scheduler.set_timesteps(__UpperCamelCase , device=self.device ) lowerCamelCase_ , lowerCamelCase_ =self.get_timesteps(__UpperCamelCase , __UpperCamelCase , self.device ) lowerCamelCase_ =timesteps[:1].repeat(__UpperCamelCase ) # 4. Prepare latent variables lowerCamelCase_ =self.prepare_latents(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , self.unet.dtype , self.device , __UpperCamelCase ) lowerCamelCase_ =latents # 5. Denoising loop for t in self.progress_bar(__UpperCamelCase ): # 1. predict noise model_output lowerCamelCase_ =self.unet(__UpperCamelCase , __UpperCamelCase ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase_ =self.scheduler.step( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , eta=__UpperCamelCase , use_clipped_model_output=__UpperCamelCase , generator=__UpperCamelCase , ).prev_sample lowerCamelCase_ =(image / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase_ =image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ =self.numpy_to_pil(__UpperCamelCase ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=__UpperCamelCase )
714
# Imports import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Any: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: if red is not None: lowerCamelCase_ =red if green is not None: lowerCamelCase_ =green if blue is not None: lowerCamelCase_ =blue if red_edge is not None: lowerCamelCase_ =red_edge if nir is not None: lowerCamelCase_ =nir return True def _snake_case ( self , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def _snake_case ( self )-> Optional[Any]: return -0.1_8 + (1.1_7 * ((self.nir - self.red) / (self.nir + self.red))) def _snake_case ( self )-> Tuple: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _snake_case ( self )-> str: return self.nir * (self.red / (self.green**2)) def _snake_case ( self )-> Optional[int]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _snake_case ( self )-> Tuple: return (self.nir - self.red) / (self.nir + self.red) def _snake_case ( self )-> Dict: return (self.nir - self.blue) / (self.nir + self.blue) def _snake_case ( self )-> List[Any]: return (self.redEdge - self.red) / (self.redEdge + self.red) def _snake_case ( self )-> Tuple: return (self.nir - self.green) / (self.nir + self.green) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.0_8 , _SCREAMING_SNAKE_CASE=1.2_2 , _SCREAMING_SNAKE_CASE=0.0_3 )-> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _snake_case ( self )-> Tuple: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _snake_case ( self )-> Any: return (self.nir / self.green) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.nir / self.redEdge) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.red - self.blue) / self.red def _snake_case ( self )-> Dict: lowerCamelCase_ =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _snake_case ( self )-> int: return self.nir - self.green def _snake_case ( self )-> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.2_5 * n) - (self.red - 0.1_2_5) / (1 - self.red) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.1_6 )-> List[Any]: return (self.nir - self.green) / (self.nir + self.green + y) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.5 )-> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _snake_case ( self )-> int: return np.arctan( ((2 * self.red - self.green - self.blue) / 3_0.5) * (self.green - self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: return (self.nir - b) / (a * self.red) def _snake_case ( self )-> int: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _snake_case ( self )-> Optional[Any]: return (self.red + self.green + self.blue) / 3_0.5 def _snake_case ( self )-> List[str]: return self.nir / self.red def _snake_case ( self )-> List[str]: return (self.rvi() - 1) / (self.rvi() + 1) def _snake_case ( self )-> str: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _snake_case ( self )-> List[Any]: return self.green / (self.nir + self.red + self.green) def _snake_case ( self )-> Dict: return self.nir / (self.nir + self.red + self.green) def _snake_case ( self )-> List[str]: return self.red / (self.nir + self.red + self.green) def _snake_case ( self )-> int: return (self.green - self.red) / (self.green + self.red) def _snake_case ( self )-> str: return (self.red - self.green) / (self.red + self.green) def _snake_case ( self )-> str: lowerCamelCase_ =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCamelCase_ =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _snake_case ( self )-> List[str]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _snake_case ( self )-> List[Any]: return self.nir / self.red def _snake_case ( self )-> Optional[int]: return (self.ndvi() + 0.5) ** (1 / 2) def _snake_case ( self )-> str: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
75
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : int = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Dict = """umt5""" _UpperCamelCase:List[Any] = ["""past_key_values"""] def __init__( self , _SCREAMING_SNAKE_CASE=25_0112 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1E-6 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE="gated-gelu" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="T5Tokenizer" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , **_SCREAMING_SNAKE_CASE , )-> Optional[Any]: super().__init__( is_encoder_decoder=_SCREAMING_SNAKE_CASE , tokenizer_class=_SCREAMING_SNAKE_CASE , tie_word_embeddings=_SCREAMING_SNAKE_CASE , pad_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , decoder_start_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =vocab_size lowerCamelCase_ =d_model lowerCamelCase_ =d_kv lowerCamelCase_ =d_ff lowerCamelCase_ =num_layers lowerCamelCase_ =( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCamelCase_ =num_heads lowerCamelCase_ =relative_attention_num_buckets lowerCamelCase_ =relative_attention_max_distance lowerCamelCase_ =dropout_rate lowerCamelCase_ =layer_norm_epsilon lowerCamelCase_ =initializer_factor lowerCamelCase_ =feed_forward_proj lowerCamelCase_ =use_cache lowerCamelCase_ =self.feed_forward_proj.split("""-""" ) lowerCamelCase_ =act_info[-1] lowerCamelCase_ =act_info[0] == """gated""" if len(_SCREAMING_SNAKE_CASE ) > 1 and act_info[0] != "gated" or len(_SCREAMING_SNAKE_CASE ) > 2: raise ValueError( f'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """\'gated-gelu\' or \'relu\'""" ) if feed_forward_proj == "gated-gelu": lowerCamelCase_ ="""gelu_new""" @property def _snake_case ( self )-> Tuple: return self.d_model @property def _snake_case ( self )-> Tuple: return self.num_heads @property def _snake_case ( self )-> Any: return self.num_layers class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def _snake_case ( self )-> int: lowerCamelCase_ ={ """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: lowerCamelCase_ ="""past_encoder_sequence + sequence""" lowerCamelCase_ ={0: """batch"""} lowerCamelCase_ ={0: """batch""", 1: """past_decoder_sequence + sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """decoder_sequence"""} lowerCamelCase_ ={0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_SCREAMING_SNAKE_CASE , direction="""inputs""" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def _snake_case ( self )-> str: return 13 @property def _snake_case ( self )-> Dict: return 5E-4
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __A : List[Any] = logging.get_logger(__name__) __A : List[str] = """https://openaipublic.azureedge.net/jukebox/models/""" __A : Optional[int] = { """jukebox-1b-lyrics""": [ """5b/vqvae.pth.tar""", """5b/prior_level_0.pth.tar""", """5b/prior_level_1.pth.tar""", """1b_lyrics/prior_level_2.pth.tar""", ], """jukebox-5b-lyrics""": [ """5b/vqvae.pth.tar""", """5b/prior_level_0.pth.tar""", """5b/prior_level_1.pth.tar""", """5b_lyrics/prior_level_2.pth.tar""", ], } def __UpperCamelCase ( _A : Any ) ->Any: """simple docstring""" if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: lowerCamelCase_ =key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: lowerCamelCase_ =key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: lowerCamelCase_ =key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: lowerCamelCase_ =key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: lowerCamelCase_ =key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: lowerCamelCase_ =key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: lowerCamelCase_ =key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: lowerCamelCase_ =key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def __UpperCamelCase ( _A : Optional[Any] , _A : List[Any] , _A : Optional[Any] , _A : List[str] ) ->List[str]: """simple docstring""" lowerCamelCase_ ={} import re lowerCamelCase_ =re.compile(R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) lowerCamelCase_ =re.compile( R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) lowerCamelCase_ =re.compile(R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) lowerCamelCase_ =re.compile(R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) lowerCamelCase_ =re.compile( R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) lowerCamelCase_ =re.compile(R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) lowerCamelCase_ =re.compile(R"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) lowerCamelCase_ =re.compile( R"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) lowerCamelCase_ =re.compile(R"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_A ): lowerCamelCase_ =re_encoder_block_conv_in.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =int(groups[2] ) * 2 + int(groups[3] ) lowerCamelCase_ =f'encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}' lowerCamelCase_ =re_encoder_block_conv_in.sub(_A , _A ) elif re_encoder_block_resnet.fullmatch(_A ): lowerCamelCase_ =re_encoder_block_resnet.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =int(groups[2] ) * 2 + int(groups[3] ) lowerCamelCase_ ={"""1""": 1, """3""": 2}[groups[-2]] lowerCamelCase_ =f'encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.' lowerCamelCase_ =f'resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}' lowerCamelCase_ =prefix + resnet_block lowerCamelCase_ =re_encoder_block_resnet.sub(_A , _A ) elif re_encoder_block_proj_out.fullmatch(_A ): lowerCamelCase_ =re_encoder_block_proj_out.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =f'encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}' lowerCamelCase_ =re_encoder_block_proj_out.sub(_A , _A ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_A ): lowerCamelCase_ =re_decoder_block_conv_out.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =int(groups[2] ) * 2 + int(groups[3] ) - 2 lowerCamelCase_ =f'decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}' lowerCamelCase_ =re_decoder_block_conv_out.sub(_A , _A ) elif re_decoder_block_resnet.fullmatch(_A ): lowerCamelCase_ =re_decoder_block_resnet.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =int(groups[2] ) * 2 + int(groups[3] ) - 2 lowerCamelCase_ ={"""1""": 1, """3""": 2}[groups[-2]] lowerCamelCase_ =f'decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.' lowerCamelCase_ =f'resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}' lowerCamelCase_ =prefix + resnet_block lowerCamelCase_ =re_decoder_block_resnet.sub(_A , _A ) elif re_decoder_block_proj_in.fullmatch(_A ): lowerCamelCase_ =re_decoder_block_proj_in.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =f'decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}' lowerCamelCase_ =re_decoder_block_proj_in.sub(_A , _A ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_A ): lowerCamelCase_ =re_prior_cond_conv_out.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =int(groups[1] ) * 2 + int(groups[2] ) - 2 lowerCamelCase_ =f'conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}' lowerCamelCase_ =re_prior_cond_conv_out.sub(_A , _A ) elif re_prior_cond_resnet.fullmatch(_A ): lowerCamelCase_ =re_prior_cond_resnet.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =int(groups[1] ) * 2 + int(groups[2] ) - 2 lowerCamelCase_ ={"""1""": 1, """3""": 2}[groups[-2]] lowerCamelCase_ =f'conditioner_blocks.upsampler.upsample_block.{block_index}.' lowerCamelCase_ =f'resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}' lowerCamelCase_ =prefix + resnet_block lowerCamelCase_ =re_prior_cond_resnet.sub(_A , _A ) elif re_prior_cond_proj_in.fullmatch(_A ): lowerCamelCase_ =re_prior_cond_proj_in.match(_A ) lowerCamelCase_ =regex_match.groups() lowerCamelCase_ =f'conditioner_blocks.upsampler.proj_in.{groups[-1]}' lowerCamelCase_ =re_prior_cond_proj_in.sub(_A , _A ) # keep original key else: lowerCamelCase_ =original_key lowerCamelCase_ =replace_key(_A ) if f'{key_prefix}.{key}' not in model_state_dict or key is None: print(f'failed converting {original_key} to {key}, does not match' ) # handle missmatched shape elif value.shape != model_state_dict[f'{key_prefix}.{key}'].shape: lowerCamelCase_ =model_state_dict[f'{key_prefix}.{key}'] print(f'{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match' ) lowerCamelCase_ =original_key lowerCamelCase_ =original_key lowerCamelCase_ =value return new_dict @torch.no_grad() def __UpperCamelCase ( _A : Any=None , _A : Union[str, Any]=None ) ->Optional[int]: """simple docstring""" for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f'{pytorch_dump_folder_path}/{file.split("/" )[-1]}' ): lowerCamelCase_ =requests.get(f'{PREFIX}{file}' , allow_redirects=_A ) os.makedirs(f'{pytorch_dump_folder_path}/' , exist_ok=_A ) open(f'{pytorch_dump_folder_path}/{file.split("/" )[-1]}' , """wb""" ).write(r.content ) lowerCamelCase_ =MODEL_MAPPING[model_name.split("""/""" )[-1]] lowerCamelCase_ =JukeboxConfig.from_pretrained(_A ) lowerCamelCase_ =JukeboxModel(_A ) lowerCamelCase_ =[] lowerCamelCase_ ={} for i, dict_name in enumerate(_A ): lowerCamelCase_ =torch.load(f'{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}' )["""model"""] lowerCamelCase_ ={} for k in old_dic.keys(): if k.endswith(""".b""" ): lowerCamelCase_ =old_dic[k] elif k.endswith(""".w""" ): lowerCamelCase_ =old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: lowerCamelCase_ =old_dic[k] else: lowerCamelCase_ =old_dic[k] lowerCamelCase_ ="""vqvae""" if i == 0 else f'priors.{3 - i}' lowerCamelCase_ =fix_jukebox_keys(_A , model.state_dict() , _A , _A ) weight_dict.append(_A ) lowerCamelCase_ =weight_dict.pop(0 ) model.vqvae.load_state_dict(_A ) for i in range(len(_A ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_A ).mkdir(exist_ok=_A ) with open(f'{pytorch_dump_folder_path}/mapping.json' , """w""" ) as txtfile: json.dump(_A , _A ) print(f'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(_A ) return weight_dict if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __A : Any = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
716
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def __UpperCamelCase ( _A : np.ndarray ) ->np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.mean(1 ) # Centralize the data of class i lowerCamelCase_ =data - column_reshape(_A ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_A , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =np.dot(_A , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =features.mean(1 ) lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.shape[1] lowerCamelCase_ =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" # Check if the features have been loaded if features.any(): lowerCamelCase_ =features.mean(1 ) # Center the dataset lowerCamelCase_ =features - np.reshape(_A , (data_mean.size, 1) ) lowerCamelCase_ =np.dot(_A , centered_data.T ) / features.shape[1] lowerCamelCase_ , lowerCamelCase_ =np.linalg.eigh(_A ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCamelCase_ =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCamelCase_ =np.dot(filtered_eigenvectors.T , _A ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: lowerCamelCase_ , lowerCamelCase_ =eigh( covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , ) lowerCamelCase_ =eigenvectors[:, ::-1][:, :dimensions] lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =np.linalg.svd(_A ) lowerCamelCase_ =svd_matrix[:, 0:dimensions] lowerCamelCase_ =np.dot(filtered_svd_matrix.T , _A ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" # Create dummy dataset with 2 classes and 3 features lowerCamelCase_ =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCamelCase_ =np.array([0, 0, 0, 1, 1] ) lowerCamelCase_ =2 lowerCamelCase_ =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_A ) as error_info: lowerCamelCase_ =linear_discriminant_analysis( _A , _A , _A , _A ) if isinstance(_A , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCamelCase_ =2 lowerCamelCase_ =np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_A ) as error_info: lowerCamelCase_ =principal_component_analysis(_A , _A ) if not np.allclose(_A , _A ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
75
0
'''simple docstring''' import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _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=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=4 , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =seq_length lowerCamelCase_ =is_training lowerCamelCase_ =use_attention_mask lowerCamelCase_ =use_token_type_ids lowerCamelCase_ =use_labels lowerCamelCase_ =vocab_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =num_choices def _snake_case ( self )-> Tuple: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ =None if self.use_attention_mask: lowerCamelCase_ =random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_ =None if self.use_token_type_ids: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase_ =RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.prepare_config_and_inputs() lowerCamelCase_ =config_and_inputs lowerCamelCase_ ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def _snake_case ( self )-> List[Any]: lowerCamelCase_ =self.prepare_config_and_inputs() lowerCamelCase_ =config_and_inputs lowerCamelCase_ =True lowerCamelCase_ =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class _SCREAMING_SNAKE_CASE ( __lowerCAmelCase , unittest.TestCase): _UpperCamelCase:List[Any] = True _UpperCamelCase:Optional[Any] = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def _snake_case ( self )-> Any: lowerCamelCase_ =FlaxRobertaPreLayerNormModelTester(self ) @slow def _snake_case ( self )-> List[str]: for model_class_name in self.all_model_classes: lowerCamelCase_ =model_class_name.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=lowerCamelCase__ ) lowerCamelCase_ =model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase__ ) @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @slow def _snake_case ( self )-> str: lowerCamelCase_ =FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=lowerCamelCase__ ) lowerCamelCase_ =np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] , dtype=jnp.intaa ) lowerCamelCase_ =model(lowerCamelCase__ )[0] lowerCamelCase_ =[1, 11, 5_0265] self.assertEqual(list(output.shape ) , lowerCamelCase__ ) # compare the actual values for a slice. lowerCamelCase_ =np.array( [[[4_0.4_8_8_0, 1_8.0_1_9_9, -5.2_3_6_7], [-1.8_8_7_7, -4.0_8_8_5, 1_0.7_0_8_5], [-2.2_6_1_3, -5.6_1_1_0, 7.2_6_6_5]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1E-4 ) ) @slow def _snake_case ( self )-> List[str]: lowerCamelCase_ =FlaxRobertaPreLayerNormModel.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=lowerCamelCase__ ) lowerCamelCase_ =np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] , dtype=jnp.intaa ) lowerCamelCase_ =model(lowerCamelCase__ )[0] # compare the actual values for a slice. lowerCamelCase_ =np.array( [[[0.0_2_0_8, -0.0_3_5_6, 0.0_2_3_7], [-0.1_5_6_9, -0.0_4_1_1, -0.2_6_2_6], [0.1_8_7_9, 0.0_1_2_5, -0.0_0_8_9]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1E-4 ) )
717
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
75
0
def __UpperCamelCase ( _A : Tuple=28123 ) ->Tuple: """simple docstring""" lowerCamelCase_ =[1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i lowerCamelCase_ =set() lowerCamelCase_ =0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(snake_case_ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
718
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
0
def __UpperCamelCase ( _A : Any ) ->Any: """simple docstring""" assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), f'The input value of [n={number}] is not an integer' if number == 1: return 2 elif number < 1: lowerCamelCase_ =f'The input value of [n={number}] has to be > 0' raise ValueError(UpperCamelCase__ ) else: lowerCamelCase_ =sylvester(number - 1 ) lowerCamelCase_ =num - 1 lowerCamelCase_ =num return lower * upper + 1 if __name__ == "__main__": print(F"""The 8th number in Sylvester\'s sequence: {sylvester(8)}""")
719
from collections import namedtuple import requests from lxml import html # type: ignore __A : Dict = namedtuple('covid_data', 'cases deaths recovered') def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data: """simple docstring""" lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) ) __A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
75
0
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets __A : int = '\\n@inproceedings{popovic-2015-chrf,\n title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation",\n author = "Popovi{\'c}, Maja",\n booktitle = "Proceedings of the Tenth Workshop on Statistical Machine Translation",\n month = sep,\n year = "2015",\n address = "Lisbon, Portugal",\n publisher = "Association for Computational Linguistics",\n url = "https://aclanthology.org/W15-3049",\n doi = "10.18653/v1/W15-3049",\n pages = "392--395",\n}\n@inproceedings{popovic-2017-chrf,\n title = "chr{F}++: words helping character n-grams",\n author = "Popovi{\'c}, Maja",\n booktitle = "Proceedings of the Second Conference on Machine Translation",\n month = sep,\n year = "2017",\n address = "Copenhagen, Denmark",\n publisher = "Association for Computational Linguistics",\n url = "https://aclanthology.org/W17-4770",\n doi = "10.18653/v1/W17-4770",\n pages = "612--618",\n}\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' __A : Optional[int] = '\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n' __A : Optional[Any] = '\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n \'score\' (float): The chrF (chrF++) score,\n \'char_order\' (int): The character n-gram order,\n \'word_order\' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n \'beta\' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]\n >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]\n >>> chrf = datasets.load_metric("chrf")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {\'score\': 84.64214891738334, \'char_order\': 6, \'word_order\': 0, \'beta\': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]\n >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]\n >>> chrf = datasets.load_metric("chrf")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {\'score\': 82.87263732906315, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]\n >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]\n >>> chrf = datasets.load_metric("chrf")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {\'score\': 92.12853119829202, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Any: if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/mjpost/sacreBLEU#chrf--chrf""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#chrf--chrf"""] , reference_urls=[ """https://github.com/m-popovic/chrF""", ] , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = CHRF.CHAR_ORDER , _SCREAMING_SNAKE_CASE = CHRF.WORD_ORDER , _SCREAMING_SNAKE_CASE = CHRF.BETA , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , )-> Optional[Any]: lowerCamelCase_ =len(references[0] ) if any(len(_SCREAMING_SNAKE_CASE ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) lowerCamelCase_ =[[refs[i] for refs in references] for i in range(_SCREAMING_SNAKE_CASE )] lowerCamelCase_ =CHRF(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =sb_chrf.corpus_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
720
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , )-> Optional[int]: lowerCamelCase_ =size if size is not None else {"""height""": 18, """width""": 18} lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =num_channels lowerCamelCase_ =image_size lowerCamelCase_ =min_resolution lowerCamelCase_ =max_resolution lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =apply_ocr def _snake_case ( self )-> str: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _SCREAMING_SNAKE_CASE ( snake_case__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =LayoutLMvaImageProcessingTester(self ) @property def _snake_case ( self )-> str: return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """size""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """apply_ocr""" ) ) def _snake_case ( self )-> Any: lowerCamelCase_ =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) lowerCamelCase_ =self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def _snake_case ( self )-> Any: pass def _snake_case ( self )-> int: lowerCamelCase_ =self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase_ =prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input lowerCamelCase_ =image_processing(image_inputs[0] , return_tensors="""pt""" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) self.assertIsInstance(encoding.words , _SCREAMING_SNAKE_CASE ) self.assertIsInstance(encoding.boxes , _SCREAMING_SNAKE_CASE ) # Test batched lowerCamelCase_ =image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase_ =prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , numpify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input lowerCamelCase_ =image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched lowerCamelCase_ =image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ =prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input lowerCamelCase_ =image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched lowerCamelCase_ =image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _snake_case ( self )-> Dict: lowerCamelCase_ =LayoutLMvaImageProcessor() from datasets import load_dataset lowerCamelCase_ =load_dataset("""hf-internal-testing/fixtures_docvqa""" , split="""test""" ) lowerCamelCase_ =Image.open(ds[0]["""file"""] ).convert("""RGB""" ) lowerCamelCase_ =image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCamelCase_ =[["""11:14""", """to""", """11:39""", """a.m""", """11:39""", """to""", """11:44""", """a.m.""", """11:44""", """a.m.""", """to""", """12:25""", """p.m.""", """12:25""", """to""", """12:58""", """p.m.""", """12:58""", """to""", """4:00""", """p.m.""", """2:00""", """to""", """5:00""", """p.m.""", """Coffee""", """Break""", """Coffee""", """will""", """be""", """served""", """for""", """men""", """and""", """women""", """in""", """the""", """lobby""", """adjacent""", """to""", """exhibit""", """area.""", """Please""", """move""", """into""", """exhibit""", """area.""", """(Exhibits""", """Open)""", """TRRF""", """GENERAL""", """SESSION""", """(PART""", """|)""", """Presiding:""", """Lee""", """A.""", """Waller""", """TRRF""", """Vice""", """President""", """“Introductory""", """Remarks”""", """Lee""", """A.""", """Waller,""", """TRRF""", """Vice""", """Presi-""", """dent""", """Individual""", """Interviews""", """with""", """TRRF""", """Public""", """Board""", """Members""", """and""", """Sci-""", """entific""", """Advisory""", """Council""", """Mem-""", """bers""", """Conducted""", """by""", """TRRF""", """Treasurer""", """Philip""", """G.""", """Kuehn""", """to""", """get""", """answers""", """which""", """the""", """public""", """refrigerated""", """warehousing""", """industry""", """is""", """looking""", """for.""", """Plus""", """questions""", """from""", """the""", """floor.""", """Dr.""", """Emil""", """M.""", """Mrak,""", """University""", """of""", """Cal-""", """ifornia,""", """Chairman,""", """TRRF""", """Board;""", """Sam""", """R.""", """Cecil,""", """University""", """of""", """Georgia""", """College""", """of""", """Agriculture;""", """Dr.""", """Stanley""", """Charm,""", """Tufts""", """University""", """School""", """of""", """Medicine;""", """Dr.""", """Robert""", """H.""", """Cotton,""", """ITT""", """Continental""", """Baking""", """Company;""", """Dr.""", """Owen""", """Fennema,""", """University""", """of""", """Wis-""", """consin;""", """Dr.""", """Robert""", """E.""", """Hardenburg,""", """USDA.""", """Questions""", """and""", """Answers""", """Exhibits""", """Open""", """Capt.""", """Jack""", """Stoney""", """Room""", """TRRF""", """Scientific""", """Advisory""", """Council""", """Meeting""", """Ballroom""", """Foyer"""]] # noqa: E231 lowerCamelCase_ =[[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , _SCREAMING_SNAKE_CASE ) self.assertListEqual(encoding.boxes , _SCREAMING_SNAKE_CASE ) # with apply_OCR = False lowerCamelCase_ =LayoutLMvaImageProcessor(apply_ocr=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
721
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
75
0
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __A : Tuple = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' __A : int = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' __A : Dict = R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/hendrycks/math""" , codebase_urls=["""https://github.com/hendrycks/math"""] , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =0.0 for i, j in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): n_correct += 1.0 if math_equivalence.is_equiv(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else 0.0 lowerCamelCase_ =n_correct / len(_SCREAMING_SNAKE_CASE ) return { "accuracy": accuracy, }
700
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "deta" _UpperCamelCase:int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , **_SCREAMING_SNAKE_CASE , )-> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase_ =CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =backbone_config.pop("""model_type""" ) lowerCamelCase_ =CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ =config_class.from_dict(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone_config lowerCamelCase_ =num_queries lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =d_model lowerCamelCase_ =encoder_ffn_dim lowerCamelCase_ =encoder_layers lowerCamelCase_ =encoder_attention_heads lowerCamelCase_ =decoder_ffn_dim lowerCamelCase_ =decoder_layers lowerCamelCase_ =decoder_attention_heads lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =activation_dropout lowerCamelCase_ =activation_function lowerCamelCase_ =init_std lowerCamelCase_ =init_xavier_std lowerCamelCase_ =encoder_layerdrop lowerCamelCase_ =auxiliary_loss lowerCamelCase_ =position_embedding_type # deformable attributes lowerCamelCase_ =num_feature_levels lowerCamelCase_ =encoder_n_points lowerCamelCase_ =decoder_n_points lowerCamelCase_ =two_stage lowerCamelCase_ =two_stage_num_proposals lowerCamelCase_ =with_box_refine lowerCamelCase_ =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =mask_loss_coefficient lowerCamelCase_ =dice_loss_coefficient lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient lowerCamelCase_ =focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> int: return self.encoder_attention_heads @property def _snake_case ( self )-> int: return self.d_model def _snake_case ( self )-> str: lowerCamelCase_ =copy.deepcopy(self.__dict__ ) lowerCamelCase_ =self.backbone_config.to_dict() lowerCamelCase_ =self.__class__.model_type return output
75
0
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=None , )-> Dict: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =seq_length lowerCamelCase_ =is_training lowerCamelCase_ =use_input_mask lowerCamelCase_ =use_labels lowerCamelCase_ =vocab_size lowerCamelCase_ =hidden_size lowerCamelCase_ =projection_dim lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =initializer_range lowerCamelCase_ =scope lowerCamelCase_ =bos_token_id def _snake_case ( self )-> int: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ =None if self.use_input_mask: lowerCamelCase_ =random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: lowerCamelCase_ =input_mask.numpy() lowerCamelCase_ , lowerCamelCase_ =input_mask.shape lowerCamelCase_ =np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =1 lowerCamelCase_ =0 lowerCamelCase_ =self.get_config() return config, input_ids, tf.convert_to_tensor(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[Any]: return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Any: lowerCamelCase_ =TFBlipTextModel(config=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =self.prepare_config_and_inputs() lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =config_and_inputs lowerCamelCase_ ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:List[str] = (TFBlipTextModel,) if is_tf_available() else () _UpperCamelCase:str = False _UpperCamelCase:Tuple = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =BlipTextModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self )-> int: self.config_tester.run_common_tests() def _snake_case ( self )-> List[str]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Optional[int]: pass def _snake_case ( self )-> Optional[int]: pass @unittest.skip(reason="""Blip does not use inputs_embeds""" ) def _snake_case ( self )-> Dict: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def _snake_case ( self )-> List[str]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def _snake_case ( self )-> Any: pass @slow def _snake_case ( self )-> List[str]: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =TFBlipTextModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=True )-> int: super().test_pt_tf_model_equivalence(allow_missing_keys=_SCREAMING_SNAKE_CASE )
701
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __A : int = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Any = "albert" def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =vocab_size lowerCamelCase_ =embedding_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_hidden_groups lowerCamelCase_ =num_attention_heads lowerCamelCase_ =inner_group_num lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =position_embedding_type class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
75
0
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py __A : List[Any] = 'src/transformers' __A : Tuple = 'docs/source/en' __A : Optional[int] = '.' def __UpperCamelCase ( _A : Tuple , _A : Tuple , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | __A : Dict = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. __A : Optional[int] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Optional[int] = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : str = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. __A : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def __UpperCamelCase ( _A : List[Any] ) ->str: """simple docstring""" lowerCamelCase_ =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _A ) return [m.group(0 ) for m in matches] def __UpperCamelCase ( _A : Union[str, Any] , _A : List[str] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =2 if text == """✅""" or text == """❌""" else len(_A ) lowerCamelCase_ =(width - text_length) // 2 lowerCamelCase_ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCamelCase_ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCamelCase_ ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) # Let's lookup through all transformers object (once). for attr_name in dir(_A ): lowerCamelCase_ =None if attr_name.endswith("""Tokenizer""" ): lowerCamelCase_ =slow_tokenizers lowerCamelCase_ =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): lowerCamelCase_ =fast_tokenizers lowerCamelCase_ =attr_name[:-13] elif _re_tf_models.match(_A ) is not None: lowerCamelCase_ =tf_models lowerCamelCase_ =_re_tf_models.match(_A ).groups()[0] elif _re_flax_models.match(_A ) is not None: lowerCamelCase_ =flax_models lowerCamelCase_ =_re_flax_models.match(_A ).groups()[0] elif _re_pt_models.match(_A ) is not None: lowerCamelCase_ =pt_models lowerCamelCase_ =_re_pt_models.match(_A ).groups()[0] if lookup_dict is not None: while len(_A ) > 0: if attr_name in model_name_to_prefix.values(): lowerCamelCase_ =True break # Try again after removing the last word in the name lowerCamelCase_ ="""""".join(camel_case_split(_A )[:-1] ) # Let's build that table! lowerCamelCase_ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCamelCase_ =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowerCamelCase_ =[len(_A ) + 2 for c in columns] lowerCamelCase_ =max([len(_A ) for name in model_names] ) + 2 # Build the table per se lowerCamelCase_ ="""|""" + """|""".join([_center_text(_A , _A ) for c, w in zip(_A , _A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" lowerCamelCase_ ={True: """✅""", False: """❌"""} for name in model_names: lowerCamelCase_ =model_name_to_prefix[name] lowerCamelCase_ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_A , _A ) for l, w in zip(_A , _A )] ) + "|\n" return table def __UpperCamelCase ( _A : str=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) lowerCamelCase_ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
702
from collections import deque from math import floor from random import random from time import time class _SCREAMING_SNAKE_CASE : def __init__( self )-> List[str]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[Any]: if self.graph.get(_SCREAMING_SNAKE_CASE ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase_ =[[w, v]] if not self.graph.get(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[] def _snake_case ( self )-> str: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> Optional[Any]: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Any: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return len(self.graph[u] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Union[str, Any]: lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =[] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return sorted_nodes def _snake_case ( self )-> str: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> List[str]: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin class _SCREAMING_SNAKE_CASE : def __init__( self )-> Optional[Any]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[str]: # check if the u exists if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase_ =[[w, v]] # add the other way if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase_ =[[w, u]] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) # the other way round if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> int: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return len(self.graph[u] ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self )-> Optional[Any]: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> str: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Dict: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin
75
0
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
703
import os from datetime import datetime as dt from github import Github __A : Optional[int] = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase_ =g.get_repo("""huggingface/diffusers""" ) lowerCamelCase_ =repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase_ =sorted(issue.get_comments() , key=lambda _A : i.created_at , reverse=_A ) lowerCamelCase_ =comments[0] if len(_A ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
75
0
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @property def _snake_case ( self )-> Optional[Any]: torch.manual_seed(0 ) lowerCamelCase_ =UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =self.dummy_uncond_unet lowerCamelCase_ =ScoreSdeVeScheduler() lowerCamelCase_ =ScoreSdeVePipeline(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) sde_ve.to(_SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE )[ 0 ] lowerCamelCase_ =image[0, -3:, -3:, -1] lowerCamelCase_ =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCamelCase_ =np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ ="""google/ncsnpp-church-256""" lowerCamelCase_ =UNetaDModel.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =ScoreSdeVeScheduler.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =ScoreSdeVePipeline(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) sde_ve.to(_SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sde_ve(num_inference_steps=10 , output_type="""numpy""" , generator=_SCREAMING_SNAKE_CASE ).images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowerCamelCase_ =np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
704
import argparse import os import re __A : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. __A : int = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. __A : int = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Optional[Any] = re.compile(R'\[([^\]]+)\]') def __UpperCamelCase ( _A : int ) ->Dict: """simple docstring""" lowerCamelCase_ =_re_indent.search(_A ) return "" if search is None else search.groups()[0] def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 lowerCamelCase_ =["""\n""".join(lines[:index] )] else: lowerCamelCase_ =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ =[lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_A ) ) if index < len(_A ) - 1: lowerCamelCase_ =[lines[index + 1]] index += 1 else: lowerCamelCase_ =[] else: blocks.append("""\n""".join(_A ) ) lowerCamelCase_ =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append("""\n""".join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def __UpperCamelCase ( _A : Optional[int] ) ->Optional[int]: """simple docstring""" def _inner(_A : Optional[Any] ): return key(_A ).lower().replace("""_""" , """""" ) return _inner def __UpperCamelCase ( _A : int , _A : List[Any]=None ) ->List[str]: """simple docstring""" # If no key is provided, we use a noop. def noop(_A : List[str] ): return x if key is None: lowerCamelCase_ =noop # Constants are all uppercase, they go first. lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()] lowerCamelCase_ =ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def __UpperCamelCase ( _A : List[str] ) ->List[str]: """simple docstring""" # This inner function sort imports between [ ]. def _replace(_A : Optional[Any] ): lowerCamelCase_ =match.groups()[0] if "," not in imports: return f'[{imports}]' lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" lowerCamelCase_ =import_statement.split("""\n""" ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase_ =2 if lines[1].strip() == """[""" else 1 lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] ) lowerCamelCase_ =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase_ =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] lowerCamelCase_ =get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase_ =_re_bracket_content.sub(_replace , _A ) return import_statement def __UpperCamelCase ( _A : List[Any] , _A : Optional[Any]=True ) ->str: """simple docstring""" with open(_A , """r""" ) as f: lowerCamelCase_ =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ =split_code_in_indented_blocks( _A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ =main_blocks[block_idx] lowerCamelCase_ =block.split("""\n""" ) # Get to the start of the imports. lowerCamelCase_ =0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase_ =len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] ) lowerCamelCase_ =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ =_re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase_ =[(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase_ =[(i, key) for i, key in enumerate(_A ) if key is not None] lowerCamelCase_ =[x[0] for x in sorted(_A , key=lambda _A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase_ =0 lowerCamelCase_ =[] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , """w""" ) as f: f.write("""\n""".join(_A ) ) def __UpperCamelCase ( _A : str=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A ) if result: lowerCamelCase_ =[os.path.join(_A , """__init__.py""" )] if len(_A ) > 0: raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') __A : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
75
0
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('0.8.3'): raise Exception('requires gluonnlp == 0.8.3') if version.parse(mx.__version__) != version.parse('1.5.0'): raise Exception('requires mxnet == 1.5.0') logging.set_verbosity_info() __A : Any = logging.get_logger(__name__) __A : str = 'The Nymphenburg Palace is a beautiful palace in Munich!' def __UpperCamelCase ( _A : str , _A : str ) ->List[str]: """simple docstring""" lowerCamelCase_ ={ """attention_cell""": """multi_head""", """num_layers""": 4, """units""": 1024, """hidden_size""": 768, """max_length""": 512, """num_heads""": 8, """scaled""": True, """dropout""": 0.1, """use_residual""": True, """embed_size""": 1024, """embed_dropout""": 0.1, """word_embed""": None, """layer_norm_eps""": 1E-5, """token_type_vocab_size""": 2, } lowerCamelCase_ =bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py lowerCamelCase_ =BERTEncoder( attention_cell=predefined_args["""attention_cell"""] , num_layers=predefined_args["""num_layers"""] , units=predefined_args["""units"""] , hidden_size=predefined_args["""hidden_size"""] , max_length=predefined_args["""max_length"""] , num_heads=predefined_args["""num_heads"""] , scaled=predefined_args["""scaled"""] , dropout=predefined_args["""dropout"""] , output_attention=_A , output_all_encodings=_A , use_residual=predefined_args["""use_residual"""] , activation=predefined_args.get("""activation""" , """gelu""" ) , layer_norm_eps=predefined_args.get("""layer_norm_eps""" , _A ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later lowerCamelCase_ ="""openwebtext_ccnews_stories_books_cased""" # Specify download folder to Gluonnlp's vocab lowerCamelCase_ =os.path.join(get_home_dir() , """models""" ) lowerCamelCase_ =_load_vocab(_A , _A , _A , cls=_A ) lowerCamelCase_ =nlp.model.BERTModel( _A , len(_A ) , units=predefined_args["""units"""] , embed_size=predefined_args["""embed_size"""] , embed_dropout=predefined_args["""embed_dropout"""] , word_embed=predefined_args["""word_embed"""] , use_pooler=_A , use_token_type_embed=_A , token_type_vocab_size=predefined_args["""token_type_vocab_size"""] , use_classifier=_A , use_decoder=_A , ) original_bort.load_parameters(_A , cast_dtype=_A , ignore_extra=_A ) lowerCamelCase_ =original_bort._collect_params_with_prefix() # Build our config 🤗 lowerCamelCase_ ={ """architectures""": ["""BertForMaskedLM"""], """attention_probs_dropout_prob""": predefined_args["""dropout"""], """hidden_act""": """gelu""", """hidden_dropout_prob""": predefined_args["""dropout"""], """hidden_size""": predefined_args["""embed_size"""], """initializer_range""": 0.0_2, """intermediate_size""": predefined_args["""hidden_size"""], """layer_norm_eps""": predefined_args["""layer_norm_eps"""], """max_position_embeddings""": predefined_args["""max_length"""], """model_type""": """bort""", """num_attention_heads""": predefined_args["""num_heads"""], """num_hidden_layers""": predefined_args["""num_layers"""], """pad_token_id""": 1, # 2 = BERT, 1 = RoBERTa """type_vocab_size""": 1, # 2 = BERT, 1 = RoBERTa """vocab_size""": len(_A ), } lowerCamelCase_ =BertConfig.from_dict(_A ) lowerCamelCase_ =BertForMaskedLM(_A ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(_A : Dict ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(_A : List[str] , _A : Any ): lowerCamelCase_ =hf_param.shape lowerCamelCase_ =to_torch(params[gluon_param] ) lowerCamelCase_ =gluon_param.shape assert ( shape_hf == shape_gluon ), f'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , """word_embed.0.weight""" ) lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , """encoder.position_weight""" ) lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , """encoder.layer_norm.beta""" ) lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , """encoder.layer_norm.gamma""" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) lowerCamelCase_ =torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): lowerCamelCase_ =hf_bort_model.bert.encoder.layer[i] # self attention lowerCamelCase_ =layer.attention.self lowerCamelCase_ =check_and_map_params( self_attn.key.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) lowerCamelCase_ =check_and_map_params( self_attn.key.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) lowerCamelCase_ =check_and_map_params( self_attn.query.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) lowerCamelCase_ =check_and_map_params( self_attn.query.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) lowerCamelCase_ =check_and_map_params( self_attn.value.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) lowerCamelCase_ =check_and_map_params( self_attn.value.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output lowerCamelCase_ =layer.attention.output lowerCamelCase_ =check_and_map_params( self_output.dense.bias , f'encoder.transformer_cells.{i}.proj.bias' ) lowerCamelCase_ =check_and_map_params( self_output.dense.weight , f'encoder.transformer_cells.{i}.proj.weight' ) lowerCamelCase_ =check_and_map_params( self_output.LayerNorm.bias , f'encoder.transformer_cells.{i}.layer_norm.beta' ) lowerCamelCase_ =check_and_map_params( self_output.LayerNorm.weight , f'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate lowerCamelCase_ =layer.intermediate lowerCamelCase_ =check_and_map_params( intermediate.dense.bias , f'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) lowerCamelCase_ =check_and_map_params( intermediate.dense.weight , f'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output lowerCamelCase_ =layer.output lowerCamelCase_ =check_and_map_params( bert_output.dense.bias , f'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) lowerCamelCase_ =check_and_map_params( bert_output.dense.weight , f'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) lowerCamelCase_ =check_and_map_params( bert_output.LayerNorm.bias , f'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) lowerCamelCase_ =check_and_map_params( bert_output.LayerNorm.weight , f'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models lowerCamelCase_ =RobertaTokenizer.from_pretrained("""roberta-base""" ) lowerCamelCase_ =tokenizer.encode_plus(_A )["""input_ids"""] # Get gluon output lowerCamelCase_ =mx.nd.array([input_ids] ) lowerCamelCase_ =original_bort(inputs=_A , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(_A ) lowerCamelCase_ =BertModel.from_pretrained(_A ) hf_bort_model.eval() lowerCamelCase_ =tokenizer.encode_plus(_A , return_tensors="""pt""" ) lowerCamelCase_ =hf_bort_model(**_A )[0] lowerCamelCase_ =output_gluon[0].asnumpy() lowerCamelCase_ =output_hf[0].detach().numpy() lowerCamelCase_ =np.max(np.abs(hf_layer - gluon_layer ) ).item() lowerCamelCase_ =np.allclose(_A , _A , atol=1E-3 ) if success: print("""✔️ Both model do output the same tensors""" ) else: print("""❌ Both model do **NOT** output the same tensors""" ) print("""Absolute difference is:""" , _A ) if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __A : List[str] = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
705
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : str = {'vocab_file': 'sentencepiece.model'} __A : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } __A : int = { 'google/rembert': 2_56, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Dict: return len(self.sp_model ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> Optional[Any]: lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =d lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
75
0
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=100 , _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=5 , _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.0_2 , _SCREAMING_SNAKE_CASE=3 , )-> int: lowerCamelCase_ =parent lowerCamelCase_ =vocab_size lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCamelCase_ =(image_size // patch_size) ** 2 lowerCamelCase_ =num_patches + 1 def _snake_case ( self )-> Tuple: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =BeitConfig( vocab_size=self.vocab_size , 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 , ) return config, pixel_values, labels def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =FlaxBeitModel(config=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Any: lowerCamelCase_ =FlaxBeitForMaskedImageModeling(config=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.type_sequence_label_size lowerCamelCase_ =FlaxBeitForImageClassification(config=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCamelCase_ =1 lowerCamelCase_ =FlaxBeitForImageClassification(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Tuple = ( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def _snake_case ( self )-> None: lowerCamelCase_ =FlaxBeitModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self )-> List[str]: self.config_tester.run_common_tests() def _snake_case ( self )-> int: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> str: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCamelCase_ =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) @jax.jit def model_jitted(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return model(pixel_values=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) with self.subTest("""JIT Enabled""" ): lowerCamelCase_ =model_jitted(**_SCREAMING_SNAKE_CASE ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): lowerCamelCase_ =model_jitted(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for jitted_output, output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertEqual(jitted_output.shape , output.shape ) def _snake_case ( self )-> Dict: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )-> int: for model_class_name in self.all_model_classes: lowerCamelCase_ =model_class_name.from_pretrained("""microsoft/beit-base-patch16-224""" ) lowerCamelCase_ =model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @cached_property def _snake_case ( self )-> Union[str, Any]: return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224""" ) if is_vision_available() else None @slow def _snake_case ( self )-> List[str]: lowerCamelCase_ =FlaxBeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k""" ) lowerCamelCase_ =self.default_image_processor lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ).pixel_values # prepare bool_masked_pos lowerCamelCase_ =np.ones((1, 196) , dtype=_SCREAMING_SNAKE_CASE ) # forward pass lowerCamelCase_ =model(pixel_values=_SCREAMING_SNAKE_CASE , bool_masked_pos=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =outputs.logits # verify the logits lowerCamelCase_ =(1, 196, 8192) self.assertEqual(logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =np.array( [[-3.2_4_3_7, 0.5_0_7_2, -13.9174], [-3.2_4_5_6, 0.4_9_4_8, -13.9401], [-3.2_0_3_3, 0.5_1_2_1, -13.8550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-2 ) ) @slow def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =FlaxBeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224""" ) lowerCamelCase_ =self.default_image_processor lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ) # forward pass lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =outputs.logits # verify the logits lowerCamelCase_ =(1, 1000) self.assertEqual(logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =np.array([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8] ) self.assertTrue(np.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) lowerCamelCase_ =281 self.assertEqual(logits.argmax(-1 ).item() , _SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )-> List[str]: lowerCamelCase_ =FlaxBeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k""" ) lowerCamelCase_ =self.default_image_processor lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ) # forward pass lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =outputs.logits # verify the logits lowerCamelCase_ =(1, 2_1841) self.assertEqual(logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =np.array([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1] ) self.assertTrue(np.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) lowerCamelCase_ =2396 self.assertEqual(logits.argmax(-1 ).item() , _SCREAMING_SNAKE_CASE )
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
75
0
from __future__ import annotations from collections import namedtuple def __UpperCamelCase ( _A : float , _A : float , _A : float ) ->tuple: """simple docstring""" lowerCamelCase_ =namedtuple("""result""" , """name value""" ) if (voltage, current, power).count(0 ) != 1: raise ValueError("""Only one argument must be 0""" ) elif power < 0: raise ValueError( """Power cannot be negative in any electrical/electronics system""" ) elif voltage == 0: return result("""voltage""" , power / current ) elif current == 0: return result("""current""" , power / voltage ) elif power == 0: return result("""power""" , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
707
# 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.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input __A : List[str] = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def __UpperCamelCase ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =_ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase_ =get_sagemaker_input() else: lowerCamelCase_ =get_cluster_input() return config def __UpperCamelCase ( _A : List[str]=None ) ->str: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""config""" , description=_A ) else: lowerCamelCase_ =argparse.ArgumentParser("""Accelerate config command""" , description=_A ) parser.add_argument( """--config_file""" , default=_A , 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=_A ) return parser def __UpperCamelCase ( _A : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =get_user_input() if args.config_file is not None: lowerCamelCase_ =args.config_file else: if not os.path.isdir(_A ): os.makedirs(_A ) lowerCamelCase_ =default_yaml_config_file if config_file.endswith(""".json""" ): config.to_json_file(_A ) else: config.to_yaml_file(_A ) print(f'accelerate configuration saved at {config_file}' ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =config_command_parser() lowerCamelCase_ =parser.parse_args() config_command(_A ) if __name__ == "__main__": main()
75
0
'''simple docstring''' import math def __UpperCamelCase ( _A : int ) ->list[int]: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =2 lowerCamelCase_ =int(math.sqrt(_A ) ) # Size of every segment lowerCamelCase_ =[True] * (end + 1) lowerCamelCase_ =[] while start <= end: if temp[start] is True: in_prime.append(_A ) for i in range(start * start , end + 1 , _A ): lowerCamelCase_ =False start += 1 prime += in_prime lowerCamelCase_ =end + 1 lowerCamelCase_ =min(2 * end , _A ) while low <= n: lowerCamelCase_ =[True] * (high - low + 1) for each in in_prime: lowerCamelCase_ =math.floor(low / each ) * each if t < low: t += each for j in range(_A , high + 1 , _A ): lowerCamelCase_ =False for j in range(len(_A ) ): if temp[j] is True: prime.append(j + low ) lowerCamelCase_ =high + 1 lowerCamelCase_ =min(high + end , _A ) return prime print(sieve(10**6))
708
def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[[] for _ in range(_A )] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_A ) <= key: return input_string for position, character in enumerate(_A ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_A ) lowerCamelCase_ =["""""".join(_A ) for row in temp_grid] lowerCamelCase_ ="""""".join(_A ) return output_string def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string lowerCamelCase_ =[[] for _ in range(_A )] # generates template for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) lowerCamelCase_ =0 for row in temp_grid: # fills in the characters lowerCamelCase_ =input_string[counter : counter + len(_A )] grid.append(list(_A ) ) counter += len(_A ) lowerCamelCase_ ="""""" # reads as zigzag for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __UpperCamelCase ( _A : str ) ->dict[int, str]: """simple docstring""" lowerCamelCase_ ={} for key_guess in range(1 , len(_A ) ): # tries every key lowerCamelCase_ =decrypt(_A , _A ) return results if __name__ == "__main__": import doctest doctest.testmod()
75
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __A : int = { 'configuration_lxmert': ['LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LxmertConfig'], 'tokenization_lxmert': ['LxmertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = ['LxmertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'LxmertEncoder', 'LxmertForPreTraining', 'LxmertForQuestionAnswering', 'LxmertModel', 'LxmertPreTrainedModel', 'LxmertVisualFeatureEncoder', 'LxmertXLayer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : str = [ 'TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLxmertForPreTraining', 'TFLxmertMainLayer', 'TFLxmertModel', 'TFLxmertPreTrainedModel', 'TFLxmertVisualFeatureEncoder', ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys __A : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
709
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =data lowerCamelCase_ =None class _SCREAMING_SNAKE_CASE : def __init__( self )-> Any: lowerCamelCase_ =None def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.head while temp is not None: print(temp.data , end=""" """ ) lowerCamelCase_ =temp.next print() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =Node(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.head lowerCamelCase_ =new_node def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if node_data_a == node_data_a: return else: lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ =node_a.data, node_a.data if __name__ == "__main__": __A : Optional[int] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
75
0
import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __A : int = logging.getLogger(__name__) __A : Union[str, Any] = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) __A : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _SCREAMING_SNAKE_CASE : _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={ "help": ( "The model checkpoint for weights initialization. Leave None if you want to train a model from" " scratch." ) } , ) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(lowerCAmelCase__)} , ) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"}) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class _SCREAMING_SNAKE_CASE : _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "The input training data file (a text file)."}) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={ "help": ( "The input training data files (multiple files in glob format). " "Very often splitting large files to smaller files can prevent tokenizer going out of memory" ) } , ) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "An optional input train ref data file for whole word mask in Chinese."} , ) _UpperCamelCase:Optional[str] = field( default=lowerCAmelCase__ , metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."} , ) _UpperCamelCase:bool = field( default=lowerCAmelCase__ , metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."} , ) _UpperCamelCase:bool = field( default=lowerCAmelCase__ , metadata={"help": "Train with masked-language modeling loss instead of language modeling."}) _UpperCamelCase:bool = field(default=lowerCAmelCase__ , metadata={"help": "Whether ot not to use whole word mask."}) _UpperCamelCase:float = field( default=0.1_5 , metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}) _UpperCamelCase:float = field( default=1 / 6 , metadata={ "help": ( "Ratio of length of a span of masked tokens to surrounding context length for permutation language" " modeling." ) } , ) _UpperCamelCase:int = field( default=5 , metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."}) _UpperCamelCase:int = field( default=-1 , metadata={ "help": ( "Optional input sequence length after tokenization." "The training dataset will be truncated in block of this size for training." "Default to the model max input length for single sentence inputs (take into account special tokens)." ) } , ) _UpperCamelCase:bool = field( default=lowerCAmelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"}) def __UpperCamelCase ( _A : DataTrainingArguments , _A : PreTrainedTokenizer , _A : bool = False , _A : Optional[str] = None , ) ->int: """simple docstring""" def _dataset(_A : Optional[Any] , _A : Any=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=_A , file_path=_A , block_size=args.block_size , ref_path=_A , ) return LineByLineTextDataset(tokenizer=_A , file_path=_A , block_size=args.block_size ) else: return TextDataset( tokenizer=_A , file_path=_A , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=_A , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(_A ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def __UpperCamelCase ( ) ->str: """simple docstring""" lowerCamelCase_ =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. Use' """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , _A ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: lowerCamelCase_ =AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: lowerCamelCase_ =AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: lowerCamelCase_ =CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: lowerCamelCase_ =AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: lowerCamelCase_ =AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: lowerCamelCase_ =AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=_A , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) lowerCamelCase_ =AutoModelWithLMHead.from_config(_A ) model.resize_token_embeddings(len(_A ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: lowerCamelCase_ =tokenizer.max_len # Our input block size will be the max possible for the model else: lowerCamelCase_ =min(data_args.block_size , tokenizer.max_len ) # Get datasets lowerCamelCase_ =( get_dataset(_A , tokenizer=_A , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) lowerCamelCase_ =( get_dataset(_A , tokenizer=_A , evaluate=_A , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": lowerCamelCase_ =DataCollatorForPermutationLanguageModeling( tokenizer=_A , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: lowerCamelCase_ =DataCollatorForWholeWordMask( tokenizer=_A , mlm_probability=data_args.mlm_probability ) else: lowerCamelCase_ =DataCollatorForLanguageModeling( tokenizer=_A , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer lowerCamelCase_ =Trainer( model=_A , args=_A , data_collator=_A , train_dataset=_A , eval_dataset=_A , prediction_loss_only=_A , ) # Training if training_args.do_train: lowerCamelCase_ =( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=_A ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCamelCase_ ={} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) lowerCamelCase_ =trainer.evaluate() lowerCamelCase_ =math.exp(eval_output["""eval_loss"""] ) lowerCamelCase_ ={"""perplexity""": perplexity} lowerCamelCase_ =os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(_A , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , _A , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(_A ) return results def __UpperCamelCase ( _A : Union[str, Any] ) ->Any: """simple docstring""" main() if __name__ == "__main__": main()
710
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "yolos" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=[512, 864] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =qkv_bias lowerCamelCase_ =num_detection_tokens lowerCamelCase_ =use_mid_position_embeddings lowerCamelCase_ =auxiliary_loss # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = version.parse("1.11") @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self )-> float: return 1E-4 @property def _snake_case ( self )-> int: return 12
75
0
import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=17 , _SCREAMING_SNAKE_CASE=23 , _SCREAMING_SNAKE_CASE=11 , _SCREAMING_SNAKE_CASE=True , )-> List[str]: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =seq_length lowerCamelCase_ =act_dim lowerCamelCase_ =state_dim lowerCamelCase_ =hidden_size lowerCamelCase_ =max_length lowerCamelCase_ =is_training def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) lowerCamelCase_ =floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) lowerCamelCase_ =floats_tensor((self.batch_size, self.seq_length, 1) ) lowerCamelCase_ =floats_tensor((self.batch_size, self.seq_length, 1) ) lowerCamelCase_ =ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) lowerCamelCase_ =random_attention_mask((self.batch_size, self.seq_length) ) lowerCamelCase_ =self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def _snake_case ( self )-> Union[str, Any]: return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , )-> str: lowerCamelCase_ =DecisionTransformerModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={ """states""": states, """actions""": actions, """rewards""": rewards, """returns_to_go""": returns_to_go, """timesteps""": timesteps, """attention_mask""": attention_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Tuple = (DecisionTransformerModel,) if is_torch_available() else () _UpperCamelCase:Union[str, Any] = () _UpperCamelCase:List[str] = {"feature-extraction": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids _UpperCamelCase:Optional[int] = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features _UpperCamelCase:List[Any] = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Tuple = False _UpperCamelCase:str = False _UpperCamelCase:Dict = False _UpperCamelCase:List[str] = False _UpperCamelCase:Any = False _UpperCamelCase:Any = False _UpperCamelCase:Dict = False def _snake_case ( self )-> List[str]: lowerCamelCase_ =DecisionTransformerModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self )-> List[Any]: self.config_tester.run_common_tests() def _snake_case ( self )-> Dict: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )-> Union[str, Any]: for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =DecisionTransformerModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =[ """states""", """actions""", """rewards""", """returns_to_go""", """timesteps""", """attention_mask""", ] self.assertListEqual(arg_names[: len(_SCREAMING_SNAKE_CASE )] , _SCREAMING_SNAKE_CASE ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @slow def _snake_case ( self )-> List[Any]: lowerCamelCase_ =2 # number of steps of autoregressive prediction we will perform lowerCamelCase_ =10 # defined by the RL environment, may be normalized lowerCamelCase_ =DecisionTransformerModel.from_pretrained("""edbeeching/decision-transformer-gym-hopper-expert""" ) lowerCamelCase_ =model.to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model.config torch.manual_seed(0 ) lowerCamelCase_ =torch.randn(1 , 1 , config.state_dim ).to(device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) # env.reset() lowerCamelCase_ =torch.tensor( [[0.2_4_2_7_9_3, -0.2_8_6_9_3_0_7_4, 0.8_7_4_2_6_1_3], [0.6_7_8_1_5_2_7_4, -0.0_8_1_0_1_0_8_5, -0.1_2_9_5_2_1_4_7]] , device=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ).reshape(1 , 1 , 1 ) lowerCamelCase_ =state lowerCamelCase_ =torch.zeros(1 , 0 , config.act_dim , device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) lowerCamelCase_ =torch.zeros(1 , 0 , device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) lowerCamelCase_ =torch.tensor(0 , device=_SCREAMING_SNAKE_CASE , dtype=torch.long ).reshape(1 , 1 ) for step in range(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=_SCREAMING_SNAKE_CASE )] , dim=1 ) lowerCamelCase_ =torch.cat([rewards, torch.zeros(1 , 1 , device=_SCREAMING_SNAKE_CASE )] , dim=1 ) lowerCamelCase_ =torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =model( states=_SCREAMING_SNAKE_CASE , actions=_SCREAMING_SNAKE_CASE , rewards=_SCREAMING_SNAKE_CASE , returns_to_go=_SCREAMING_SNAKE_CASE , timesteps=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ), 1.0, False, {}, ) lowerCamelCase_ =action_pred[0, -1] lowerCamelCase_ =torch.cat([states, state] , dim=1 ) lowerCamelCase_ =returns_to_go[0, -1] - reward lowerCamelCase_ =torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) lowerCamelCase_ =torch.cat( [timesteps, torch.ones((1, 1) , device=_SCREAMING_SNAKE_CASE , dtype=torch.long ) * (step + 1)] , dim=1 )
711
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py __A : List[Any] = 'src/transformers' __A : Tuple = 'docs/source/en' __A : Optional[int] = '.' def __UpperCamelCase ( _A : Tuple , _A : Tuple , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | __A : Dict = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. __A : Optional[int] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Optional[int] = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : str = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. __A : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def __UpperCamelCase ( _A : List[Any] ) ->str: """simple docstring""" lowerCamelCase_ =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _A ) return [m.group(0 ) for m in matches] def __UpperCamelCase ( _A : Union[str, Any] , _A : List[str] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =2 if text == """✅""" or text == """❌""" else len(_A ) lowerCamelCase_ =(width - text_length) // 2 lowerCamelCase_ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCamelCase_ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCamelCase_ ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) # Let's lookup through all transformers object (once). for attr_name in dir(_A ): lowerCamelCase_ =None if attr_name.endswith("""Tokenizer""" ): lowerCamelCase_ =slow_tokenizers lowerCamelCase_ =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): lowerCamelCase_ =fast_tokenizers lowerCamelCase_ =attr_name[:-13] elif _re_tf_models.match(_A ) is not None: lowerCamelCase_ =tf_models lowerCamelCase_ =_re_tf_models.match(_A ).groups()[0] elif _re_flax_models.match(_A ) is not None: lowerCamelCase_ =flax_models lowerCamelCase_ =_re_flax_models.match(_A ).groups()[0] elif _re_pt_models.match(_A ) is not None: lowerCamelCase_ =pt_models lowerCamelCase_ =_re_pt_models.match(_A ).groups()[0] if lookup_dict is not None: while len(_A ) > 0: if attr_name in model_name_to_prefix.values(): lowerCamelCase_ =True break # Try again after removing the last word in the name lowerCamelCase_ ="""""".join(camel_case_split(_A )[:-1] ) # Let's build that table! lowerCamelCase_ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCamelCase_ =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowerCamelCase_ =[len(_A ) + 2 for c in columns] lowerCamelCase_ =max([len(_A ) for name in model_names] ) + 2 # Build the table per se lowerCamelCase_ ="""|""" + """|""".join([_center_text(_A , _A ) for c, w in zip(_A , _A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" lowerCamelCase_ ={True: """✅""", False: """❌"""} for name in model_names: lowerCamelCase_ =model_name_to_prefix[name] lowerCamelCase_ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_A , _A ) for l, w in zip(_A , _A )] ) + "|\n" return table def __UpperCamelCase ( _A : str=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) lowerCamelCase_ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
75
0
import os import jsonlines import numpy as np from tqdm import tqdm __A : str = 20_48 __A : Optional[int] = 40_96 __A : List[Any] = 42 __A : Optional[Any] = os.environ.pop('PROCESS_TRAIN', 'false') __A : Tuple = {'null': 0, 'short': 1, 'long': 2, 'yes': 3, 'no': 4} def __UpperCamelCase ( _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" def choose_first(_A : Optional[int] , _A : Tuple=False ): assert isinstance(_A , _A ) if len(_A ) == 1: lowerCamelCase_ =answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: lowerCamelCase_ ={k: [a[k]] for k in a} if len(a["""start_token"""] ) > 0: break return a lowerCamelCase_ ={"""id""": example["""id"""]} lowerCamelCase_ =example["""annotations"""] lowerCamelCase_ =annotation["""yes_no_answer"""] if 0 in yes_no_answer or 1 in yes_no_answer: lowerCamelCase_ =["""yes"""] if 1 in yes_no_answer else ["""no"""] lowerCamelCase_ =lowerCamelCase_ =[] lowerCamelCase_ =lowerCamelCase_ =[] lowerCamelCase_ =["""<cls>"""] else: lowerCamelCase_ =["""short"""] lowerCamelCase_ =choose_first(annotation["""short_answers"""] ) if len(out["""start_token"""] ) == 0: # answer will be long if short is not available lowerCamelCase_ =["""long"""] lowerCamelCase_ =choose_first(annotation["""long_answer"""] , is_long_answer=_A ) lowerCamelCase_ =[] answer.update(_A ) # disregard some samples if len(answer["""start_token"""] ) > 1 or answer["start_token"] == answer["end_token"]: lowerCamelCase_ =True else: lowerCamelCase_ =False lowerCamelCase_ =["""start_token""", """end_token""", """start_byte""", """end_byte""", """text"""] if not all(isinstance(answer[k] , _A ) for k in cols ): raise ValueError("""Issue in ID""" , example["""id"""] ) return answer def __UpperCamelCase ( _A : Union[str, Any] , _A : int=False ) ->Dict: """simple docstring""" lowerCamelCase_ =_get_single_answer(_A ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element lowerCamelCase_ =example["""document"""]["""tokens"""] lowerCamelCase_ =[] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) return { "context": " ".join(_A ), "answer": { "start_token": -100, # ignore index in cross-entropy "end_token": -100, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples lowerCamelCase_ =["""start_token""", """end_token"""] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 lowerCamelCase_ =example["""document"""]["""tokens"""] lowerCamelCase_ =answer["""start_token"""] lowerCamelCase_ =answer["""end_token"""] lowerCamelCase_ =[] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 lowerCamelCase_ =""" """.join(context[start_token:end_token] ) # checking above code if assertion: lowerCamelCase_ =doc["""is_html"""][answer["""start_token"""] : answer["""end_token"""]] lowerCamelCase_ =doc["""token"""][answer["""start_token"""] : answer["""end_token"""]] lowerCamelCase_ =""" """.join([old[i] for i in range(len(_A ) ) if not is_html[i]] ) if new != old: print("""ID:""" , example["""id"""] ) print("""New:""" , _A , end="""\n""" ) print("""Old:""" , _A , end="""\n\n""" ) return { "context": " ".join(_A ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def __UpperCamelCase ( _A : Tuple , _A : Any , _A : List[Any]=2048 , _A : int=4096 , _A : List[str]=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =get_context_and_ans(_A , assertion=_A ) lowerCamelCase_ =out["""answer"""] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } lowerCamelCase_ =tokenizer(example["""question"""]["""text"""] , out["""context"""] ).input_ids lowerCamelCase_ =input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =input_ids[:q_len] lowerCamelCase_ =range(_A , len(_A ) , max_length - doc_stride ) for i in doc_start_indices: lowerCamelCase_ =i + max_length - q_len lowerCamelCase_ =input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer["""category"""][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-100] * len(_A ), "end_token": [-100] * len(_A ), "category": category, }, } lowerCamelCase_ =out["""context"""].split() lowerCamelCase_ =splitted_context[answer["""end_token"""]] lowerCamelCase_ =len( tokenizer( """ """.join(splitted_context[: answer["""start_token"""]] ) , add_special_tokens=_A , ).input_ids ) lowerCamelCase_ =len( tokenizer(""" """.join(splitted_context[: answer["""end_token"""]] ) , add_special_tokens=_A ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token lowerCamelCase_ =len(tokenizer(_A , add_special_tokens=_A ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 lowerCamelCase_ =input_ids[answer["""start_token"""] : answer["""end_token"""] + 1] # right & left are inclusive lowerCamelCase_ =answer["""start_token"""] lowerCamelCase_ =answer["""end_token"""] if assertion: lowerCamelCase_ =tokenizer.decode(_A ) if answer["span"] != new: print("""ISSUE IN TOKENIZATION""" ) print("""OLD:""" , answer["""span"""] ) print("""NEW:""" , _A , end="""\n\n""" ) if len(_A ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } lowerCamelCase_ =input_ids[:q_len] lowerCamelCase_ =range(_A , len(_A ) , max_length - doc_stride ) lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =[] # null, yes, no, long, short for i in doc_start_indices: lowerCamelCase_ =i + max_length - q_len lowerCamelCase_ =input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: lowerCamelCase_ =start_token - i + q_len lowerCamelCase_ =end_token - i + q_len answers_category.append(answer["""category"""][0] ) # ["short"] -> "short" else: lowerCamelCase_ =-100 lowerCamelCase_ =-100 answers_category.append("""null""" ) lowerCamelCase_ =inputs[-1][start_token : end_token + 1] answers_start_token.append(_A ) answers_end_token.append(_A ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print("""ISSUE in strided for ID:""" , example["""id"""] ) print("""New:""" , tokenizer.decode(_A ) ) print("""Old:""" , tokenizer.decode(_A ) , end="""\n\n""" ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def __UpperCamelCase ( _A : Optional[int] , _A : Tuple , _A : Tuple=2048 , _A : Optional[Any]=4096 , _A : Tuple=False ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =get_strided_contexts_and_ans( _A , _A , doc_stride=_A , max_length=_A , assertion=_A , ) return example def __UpperCamelCase ( _A : List[str] , _A : Dict ) ->Optional[int]: """simple docstring""" with jsonlines.open(_A , """a""" ) as writer: for example in tqdm(_A , total=len(_A ) , desc="""Saving samples ... """ ): lowerCamelCase_ =example["""labels"""] for ids, start, end, cat in zip( example["""input_ids"""] , labels["""start_token"""] , labels["""end_token"""] , labels["""category"""] , ): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { """input_ids""": ids, """start_token""": start, """end_token""": end, """category""": CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer __A : Optional[Any] = load_dataset('natural_questions') __A : List[Any] = BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base') __A : Optional[Any] = data['train' if PROCESS_TRAIN == 'true' else 'validation'] __A : int = { 'tokenizer': tokenizer, 'doc_stride': DOC_STRIDE, 'max_length': MAX_LENGTH, 'assertion': False, } __A : str = data.map(prepare_inputs, fn_kwargs=fn_kwargs) __A : Tuple = data.remove_columns(['annotations', 'document', 'id', 'question']) print(data) np.random.seed(SEED) __A : List[Any] = 'nq-training.jsonl' if PROCESS_TRAIN == 'true' else 'nq-validation.jsonl' save_to_disk(data, file_name=cache_file_name)
712
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =num_stages lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =out_features lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =num_stages def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self )-> Union[str, Any]: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_SCREAMING_SNAKE_CASE , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_SCREAMING_SNAKE_CASE , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCamelCase:Any = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Dict = False _UpperCamelCase:int = False _UpperCamelCase:Any = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> int: lowerCamelCase_ =UperNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( 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 _snake_case ( self )-> Tuple: return def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _snake_case ( self )-> List[Any]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> str: pass def _snake_case ( self )-> Optional[int]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =_config_zero_init(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =_config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ =model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _snake_case ( self )-> Dict: pass @slow def _snake_case ( self )-> Tuple: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Tuple: """simple docstring""" lowerCamelCase_ =hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) lowerCamelCase_ =Image.open(_A ).convert("""RGB""" ) return image @require_torch @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def _snake_case ( self )-> int: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
75
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __A : List[str] = { 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
713
from typing import Dict, Iterable, 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, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_MEAN , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_STD , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ =int((256 / 224) * size["""shortest_edge"""] ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""height""": output_size[0], """width""": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( _SCREAMING_SNAKE_CASE , size=(size_dict["""height"""], size_dict["""width"""]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: 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_center_crop if do_center_crop is not None else self.do_center_crop 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_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_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.""" ) # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
75
0
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter __A : Any = True except ImportError: __A : List[str] = False __A : Any = logging.get_logger(__name__) # pylint: disable=invalid-name def __UpperCamelCase ( _A : Namespace ) ->Optional[int]: """simple docstring""" return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @staticmethod def _snake_case ( _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =parser.add_parser("""add-new-model""" ) add_new_model_parser.add_argument("""--testing""" , action="""store_true""" , help="""If in testing mode.""" ) add_new_model_parser.add_argument("""--testing_file""" , type=_SCREAMING_SNAKE_CASE , help="""Configuration file on which to run.""" ) add_new_model_parser.add_argument( """--path""" , type=_SCREAMING_SNAKE_CASE , help="""Path to cookiecutter. Should only be used for testing purposes.""" ) add_new_model_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , *_SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =testing lowerCamelCase_ =testing_file lowerCamelCase_ =path def _snake_case ( self )-> str: warnings.warn( """The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. """ """It is not actively maintained anymore, so might give a result that won't pass all tests and quality """ """checks, you should use `transformers-cli add-new-model-like` instead.""" ) if not _has_cookiecutter: raise ImportError( """Model creation dependencies are required to use the `add_new_model` command. Install them by running """ """the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n""" ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory lowerCamelCase_ =[directory for directory in os.listdir() if """cookiecutter-template-""" == directory[:22]] if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError( """Several directories starting with `cookiecutter-template-` in current working directory. """ """Please clean your directory by removing all folders starting with `cookiecutter-template-` or """ """change your working directory.""" ) lowerCamelCase_ =( Path(_SCREAMING_SNAKE_CASE ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) lowerCamelCase_ =path_to_transformer_root / """templates""" / """adding_a_new_model""" # Execute cookiecutter if not self._testing: cookiecutter(str(_SCREAMING_SNAKE_CASE ) ) else: with open(self._testing_file , """r""" ) as configuration_file: lowerCamelCase_ =json.load(_SCREAMING_SNAKE_CASE ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) , no_input=_SCREAMING_SNAKE_CASE , extra_context=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =[directory for directory in os.listdir() if """cookiecutter-template-""" in directory[:22]][0] # Retrieve configuration with open(directory + """/configuration.json""" , """r""" ) as configuration_file: lowerCamelCase_ =json.load(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =configuration["""lowercase_modelname"""] lowerCamelCase_ =configuration["""generate_tensorflow_pytorch_and_flax"""] os.remove(f'{directory}/configuration.json' ) lowerCamelCase_ ="""PyTorch""" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ ="""TensorFlow""" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ ="""Flax""" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ =f'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) os.makedirs(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}' , exist_ok=_SCREAMING_SNAKE_CASE ) # Tests require submodules as they have parent imports with open(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' , """w""" ): pass shutil.move( f'{directory}/__init__.py' , f'{model_dir}/__init__.py' , ) shutil.move( f'{directory}/configuration_{lowercase_model_name}.py' , f'{model_dir}/configuration_{lowercase_model_name}.py' , ) def remove_copy_lines(_SCREAMING_SNAKE_CASE ): with open(_SCREAMING_SNAKE_CASE , """r""" ) as f: lowerCamelCase_ =f.readlines() with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(_SCREAMING_SNAKE_CASE ) if output_pytorch: if not self._testing: remove_copy_lines(f'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_{lowercase_model_name}.py' , f'{model_dir}/modeling_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(f'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_tf_{lowercase_model_name}.py' , f'{model_dir}/modeling_tf_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_tf_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(f'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( f'{directory}/modeling_flax_{lowercase_model_name}.py' , f'{model_dir}/modeling_flax_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/test_modeling_flax_{lowercase_model_name}.py' , f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' , ) else: os.remove(f'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(f'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( f'{directory}/{lowercase_model_name}.md' , f'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' , ) shutil.move( f'{directory}/tokenization_{lowercase_model_name}.py' , f'{model_dir}/tokenization_{lowercase_model_name}.py' , ) shutil.move( f'{directory}/tokenization_fast_{lowercase_model_name}.py' , f'{model_dir}/tokenization_{lowercase_model_name}_fast.py' , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Create temp file lowerCamelCase_ , lowerCamelCase_ =mkstemp() lowerCamelCase_ =False with fdopen(_SCREAMING_SNAKE_CASE , """w""" ) as new_file: with open(_SCREAMING_SNAKE_CASE ) as old_file: for line in old_file: new_file.write(_SCREAMING_SNAKE_CASE ) if line_to_copy_below in line: lowerCamelCase_ =True for line_to_copy in lines_to_copy: new_file.write(_SCREAMING_SNAKE_CASE ) if not line_found: raise ValueError(f'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Remove original file remove(_SCREAMING_SNAKE_CASE ) # Move new file move(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def skip_units(_SCREAMING_SNAKE_CASE ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(_SCREAMING_SNAKE_CASE ): with open(_SCREAMING_SNAKE_CASE ) as datafile: lowerCamelCase_ =[] lowerCamelCase_ =False lowerCamelCase_ =False for line in datafile: if "# To replace in: " in line and "##" not in line: lowerCamelCase_ =line.split("""\"""" )[1] lowerCamelCase_ =skip_units(_SCREAMING_SNAKE_CASE ) elif "# Below: " in line and "##" not in line: lowerCamelCase_ =line.split("""\"""" )[1] lowerCamelCase_ =skip_units(_SCREAMING_SNAKE_CASE ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =[] elif "# Replace with" in line and "##" not in line: lowerCamelCase_ =[] elif "##" not in line: lines_to_copy.append(_SCREAMING_SNAKE_CASE ) remove(_SCREAMING_SNAKE_CASE ) replace_in_files(f'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(_SCREAMING_SNAKE_CASE )
714
# Imports import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Any: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: if red is not None: lowerCamelCase_ =red if green is not None: lowerCamelCase_ =green if blue is not None: lowerCamelCase_ =blue if red_edge is not None: lowerCamelCase_ =red_edge if nir is not None: lowerCamelCase_ =nir return True def _snake_case ( self , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def _snake_case ( self )-> Optional[Any]: return -0.1_8 + (1.1_7 * ((self.nir - self.red) / (self.nir + self.red))) def _snake_case ( self )-> Tuple: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _snake_case ( self )-> str: return self.nir * (self.red / (self.green**2)) def _snake_case ( self )-> Optional[int]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _snake_case ( self )-> Tuple: return (self.nir - self.red) / (self.nir + self.red) def _snake_case ( self )-> Dict: return (self.nir - self.blue) / (self.nir + self.blue) def _snake_case ( self )-> List[Any]: return (self.redEdge - self.red) / (self.redEdge + self.red) def _snake_case ( self )-> Tuple: return (self.nir - self.green) / (self.nir + self.green) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.0_8 , _SCREAMING_SNAKE_CASE=1.2_2 , _SCREAMING_SNAKE_CASE=0.0_3 )-> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _snake_case ( self )-> Tuple: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _snake_case ( self )-> Any: return (self.nir / self.green) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.nir / self.redEdge) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.red - self.blue) / self.red def _snake_case ( self )-> Dict: lowerCamelCase_ =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _snake_case ( self )-> int: return self.nir - self.green def _snake_case ( self )-> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.2_5 * n) - (self.red - 0.1_2_5) / (1 - self.red) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.1_6 )-> List[Any]: return (self.nir - self.green) / (self.nir + self.green + y) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.5 )-> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _snake_case ( self )-> int: return np.arctan( ((2 * self.red - self.green - self.blue) / 3_0.5) * (self.green - self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: return (self.nir - b) / (a * self.red) def _snake_case ( self )-> int: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _snake_case ( self )-> Optional[Any]: return (self.red + self.green + self.blue) / 3_0.5 def _snake_case ( self )-> List[str]: return self.nir / self.red def _snake_case ( self )-> List[str]: return (self.rvi() - 1) / (self.rvi() + 1) def _snake_case ( self )-> str: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _snake_case ( self )-> List[Any]: return self.green / (self.nir + self.red + self.green) def _snake_case ( self )-> Dict: return self.nir / (self.nir + self.red + self.green) def _snake_case ( self )-> List[str]: return self.red / (self.nir + self.red + self.green) def _snake_case ( self )-> int: return (self.green - self.red) / (self.green + self.red) def _snake_case ( self )-> str: return (self.red - self.green) / (self.red + self.green) def _snake_case ( self )-> str: lowerCamelCase_ =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCamelCase_ =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _snake_case ( self )-> List[str]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _snake_case ( self )-> List[Any]: return self.nir / self.red def _snake_case ( self )-> Optional[int]: return (self.ndvi() + 0.5) ** (1 / 2) def _snake_case ( self )-> str: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
75
0
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Dict = ["image_processor", "tokenizer"] _UpperCamelCase:List[str] = "AutoImageProcessor" _UpperCamelCase:int = "AutoTokenizer" def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> int: super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.image_processor def __call__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> Tuple: 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: lowerCamelCase_ =self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if images is not None: lowerCamelCase_ =self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None and images is not None: lowerCamelCase_ =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_SCREAMING_SNAKE_CASE ) , tensor_type=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Union[str, Any]: return ["input_ids", "attention_mask", "pixel_values"]
716
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def __UpperCamelCase ( _A : np.ndarray ) ->np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.mean(1 ) # Centralize the data of class i lowerCamelCase_ =data - column_reshape(_A ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_A , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =np.dot(_A , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =features.mean(1 ) lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.shape[1] lowerCamelCase_ =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" # Check if the features have been loaded if features.any(): lowerCamelCase_ =features.mean(1 ) # Center the dataset lowerCamelCase_ =features - np.reshape(_A , (data_mean.size, 1) ) lowerCamelCase_ =np.dot(_A , centered_data.T ) / features.shape[1] lowerCamelCase_ , lowerCamelCase_ =np.linalg.eigh(_A ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCamelCase_ =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCamelCase_ =np.dot(filtered_eigenvectors.T , _A ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: lowerCamelCase_ , lowerCamelCase_ =eigh( covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , ) lowerCamelCase_ =eigenvectors[:, ::-1][:, :dimensions] lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =np.linalg.svd(_A ) lowerCamelCase_ =svd_matrix[:, 0:dimensions] lowerCamelCase_ =np.dot(filtered_svd_matrix.T , _A ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" # Create dummy dataset with 2 classes and 3 features lowerCamelCase_ =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCamelCase_ =np.array([0, 0, 0, 1, 1] ) lowerCamelCase_ =2 lowerCamelCase_ =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_A ) as error_info: lowerCamelCase_ =linear_discriminant_analysis( _A , _A , _A , _A ) if isinstance(_A , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCamelCase_ =2 lowerCamelCase_ =np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_A ) as error_info: lowerCamelCase_ =principal_component_analysis(_A , _A ) if not np.allclose(_A , _A ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
75
0
'''simple docstring''' import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( """compression_format, is_archive""" , [ ("""7z""", True), ("""bz2""", False), ("""gzip""", False), ("""lz4""", False), ("""tar""", True), ("""xz""", False), ("""zip""", True), ("""zstd""", False), ] , ) def __UpperCamelCase ( _A : Any , _A : str , _A : Dict , _A : Tuple , _A : Union[str, Any] , _A : Optional[int] , _A : List[Any] , _A : Tuple , _A : Dict , _A : Union[str, Any] , _A : Optional[Any] , _A : List[str] , ) ->List[Any]: """simple docstring""" lowerCamelCase_ ={ """7z""": (seven_zip_file, SevenZipExtractor), """bz2""": (bza_file, BzipaExtractor), """gzip""": (gz_file, GzipExtractor), """lz4""": (lza_file, LzaExtractor), """tar""": (tar_file, TarExtractor), """xz""": (xz_file, XzExtractor), """zip""": (zip_file, ZipExtractor), """zstd""": (zstd_file, ZstdExtractor), } lowerCamelCase_ , lowerCamelCase_ =input_paths_and_base_extractors[compression_format] if input_path is None: lowerCamelCase_ =f'for \'{compression_format}\' compression_format, ' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_A ) assert base_extractor.is_extractable(_A ) lowerCamelCase_ =tmp_path / ("""extracted""" if is_archive else """extracted.txt""") base_extractor.extract(_A , _A ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name lowerCamelCase_ =file_path.read_text(encoding="""utf-8""" ) else: lowerCamelCase_ =output_path.read_text(encoding="""utf-8""" ) lowerCamelCase_ =text_file.read_text(encoding="""utf-8""" ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( """compression_format, is_archive""" , [ ("""7z""", True), ("""bz2""", False), ("""gzip""", False), ("""lz4""", False), ("""tar""", True), ("""xz""", False), ("""zip""", True), ("""zstd""", False), ] , ) def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[Any] , _A : Any , _A : Tuple , _A : Optional[int] , _A : List[str] , _A : Any , _A : Union[str, Any] , _A : Tuple , _A : Optional[Any] , _A : Union[str, Any] , _A : str , ) ->Tuple: """simple docstring""" lowerCamelCase_ ={ """7z""": seven_zip_file, """bz2""": bza_file, """gzip""": gz_file, """lz4""": lza_file, """tar""": tar_file, """xz""": xz_file, """zip""": zip_file, """zstd""": zstd_file, } lowerCamelCase_ =input_paths[compression_format] if input_path is None: lowerCamelCase_ =f'for \'{compression_format}\' compression_format, ' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_A ) lowerCamelCase_ =Extractor.infer_extractor_format(_A ) assert extractor_format is not None lowerCamelCase_ =tmp_path / ("""extracted""" if is_archive else """extracted.txt""") Extractor.extract(_A , _A , _A ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name lowerCamelCase_ =file_path.read_text(encoding="""utf-8""" ) else: lowerCamelCase_ =output_path.read_text(encoding="""utf-8""" ) lowerCamelCase_ =text_file.read_text(encoding="""utf-8""" ) assert extracted_file_content == expected_file_content @pytest.fixture def __UpperCamelCase ( _A : Optional[Any] , _A : str ) ->Tuple: """simple docstring""" import tarfile lowerCamelCase_ =tmp_path / """data_dot_dot""" directory.mkdir() lowerCamelCase_ =directory / """tar_file_with_dot_dot.tar""" with tarfile.TarFile(_A , """w""" ) as f: f.add(_A , arcname=os.path.join("""..""" , text_file.name ) ) return path @pytest.fixture def __UpperCamelCase ( _A : Dict ) ->str: """simple docstring""" import tarfile lowerCamelCase_ =tmp_path / """data_sym_link""" directory.mkdir() lowerCamelCase_ =directory / """tar_file_with_sym_link.tar""" os.symlink("""..""" , directory / """subdir""" , target_is_directory=_A ) with tarfile.TarFile(_A , """w""" ) as f: f.add(str(directory / """subdir""" ) , arcname="""subdir""" ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( """insecure_tar_file, error_log""" , [("""tar_file_with_dot_dot""", """illegal path"""), ("""tar_file_with_sym_link""", """Symlink""")] , ) def __UpperCamelCase ( _A : str , _A : Union[str, Any] , _A : List[Any] , _A : Tuple , _A : Tuple , _A : List[str] ) ->List[str]: """simple docstring""" lowerCamelCase_ ={ """tar_file_with_dot_dot""": tar_file_with_dot_dot, """tar_file_with_sym_link""": tar_file_with_sym_link, } lowerCamelCase_ =insecure_tar_files[insecure_tar_file] lowerCamelCase_ =tmp_path / """extracted""" TarExtractor.extract(_A , _A ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def __UpperCamelCase ( _A : Optional[int] ) ->Any: """simple docstring""" lowerCamelCase_ =tmpdir / """not_a_zip_file""" # From: https://github.com/python/cpython/pull/5053 lowerCamelCase_ =( B"""\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00""" B"""\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I""" B"""DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07""" B"""\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82""" ) with not_a_zip_file.open("""wb""" ) as f: f.write(_A ) assert zipfile.is_zipfile(str(_A ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(_A ) # but we're right
717
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
75
0
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =data lowerCamelCase_ =None class _SCREAMING_SNAKE_CASE : def __init__( self )-> Any: lowerCamelCase_ =None def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.head while temp is not None: print(temp.data , end=""" """ ) lowerCamelCase_ =temp.next print() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =Node(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.head lowerCamelCase_ =new_node def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if node_data_a == node_data_a: return else: lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ =node_a.data, node_a.data if __name__ == "__main__": __A : Optional[int] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
718
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
0
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel __A : Optional[Any] = { 'text_branch': 'text_model', 'audio_branch': 'audio_model.audio_encoder', 'attn': 'attention.self', 'self.proj': 'output.dense', 'attention.self_mask': 'attn_mask', 'mlp.fc1': 'intermediate.dense', 'mlp.fc2': 'output.dense', 'norm1': 'layernorm_before', 'norm2': 'layernorm_after', 'bn0': 'batch_norm', } __A : Tuple = AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc') def __UpperCamelCase ( _A : Union[str, Any] , _A : Tuple=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ =create_model( """HTSAT-tiny""" , """roberta""" , _A , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=_A , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def __UpperCamelCase ( _A : List[Any] ) ->List[str]: """simple docstring""" lowerCamelCase_ ={} lowerCamelCase_ =R""".*sequential.(\d+).*""" lowerCamelCase_ =R""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: lowerCamelCase_ =key.replace(_A , _A ) if re.match(_A , _A ): # replace sequential layers with list lowerCamelCase_ =re.match(_A , _A ).group(1 ) lowerCamelCase_ =key.replace(f'sequential.{sequential_layer}.' , f'layers.{int(_A )//3}.linear.' ) elif re.match(_A , _A ): lowerCamelCase_ =int(re.match(_A , _A ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... lowerCamelCase_ =1 if projecton_layer == 0 else 2 lowerCamelCase_ =key.replace(f'_projection.{projecton_layer}.' , f'_projection.linear{transformers_projection_layer}.' ) if "audio" and "qkv" in key: # split qkv into query key and value lowerCamelCase_ =value lowerCamelCase_ =mixed_qkv.size(0 ) // 3 lowerCamelCase_ =mixed_qkv[:qkv_dim] lowerCamelCase_ =mixed_qkv[qkv_dim : qkv_dim * 2] lowerCamelCase_ =mixed_qkv[qkv_dim * 2 :] lowerCamelCase_ =query_layer lowerCamelCase_ =key_layer lowerCamelCase_ =value_layer else: lowerCamelCase_ =value return model_state_dict def __UpperCamelCase ( _A : List[Any] , _A : str , _A : Tuple , _A : Union[str, Any]=False ) ->List[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ =init_clap(_A , enable_fusion=_A ) clap_model.eval() lowerCamelCase_ =clap_model.state_dict() lowerCamelCase_ =rename_state_dict(_A ) lowerCamelCase_ =ClapConfig() lowerCamelCase_ =enable_fusion lowerCamelCase_ =ClapModel(_A ) # ignore the spectrogram embedding layer model.load_state_dict(_A , strict=_A ) model.save_pretrained(_A ) transformers_config.save_pretrained(_A ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not') __A : str = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
719
from collections import namedtuple import requests from lxml import html # type: ignore __A : Dict = namedtuple('covid_data', 'cases deaths recovered') def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data: """simple docstring""" lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) ) __A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
75
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : Optional[int] = { 'configuration_mobilenet_v2': [ 'MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileNetV2Config', 'MobileNetV2OnnxConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['MobileNetV2FeatureExtractor'] __A : Any = ['MobileNetV2ImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ 'MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileNetV2ForImageClassification', 'MobileNetV2ForSemanticSegmentation', 'MobileNetV2Model', 'MobileNetV2PreTrainedModel', 'load_tf_weights_in_mobilenet_v2', ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __A : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
720
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() __A : Optional[int] = logging.get_logger('transformers.models.speecht5') def __UpperCamelCase ( _A : List[str] , _A : Optional[Any] , _A : List[str] ) ->Any: """simple docstring""" hf_model.apply_weight_norm() lowerCamelCase_ =checkpoint["""input_conv.weight_g"""] lowerCamelCase_ =checkpoint["""input_conv.weight_v"""] lowerCamelCase_ =checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): lowerCamelCase_ =checkpoint[f'upsamples.{i}.1.weight_g'] lowerCamelCase_ =checkpoint[f'upsamples.{i}.1.weight_v'] lowerCamelCase_ =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_ =checkpoint[f'blocks.{i}.convs1.{j}.1.weight_g'] lowerCamelCase_ =checkpoint[f'blocks.{i}.convs1.{j}.1.weight_v'] lowerCamelCase_ =checkpoint[f'blocks.{i}.convs1.{j}.1.bias'] lowerCamelCase_ =checkpoint[f'blocks.{i}.convs2.{j}.1.weight_g'] lowerCamelCase_ =checkpoint[f'blocks.{i}.convs2.{j}.1.weight_v'] lowerCamelCase_ =checkpoint[f'blocks.{i}.convs2.{j}.1.bias'] lowerCamelCase_ =checkpoint["""output_conv.1.weight_g"""] lowerCamelCase_ =checkpoint["""output_conv.1.weight_v"""] lowerCamelCase_ =checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def __UpperCamelCase ( _A : Any , _A : Optional[int] , _A : List[Any] , _A : int=None , _A : Optional[int]=None , ) ->int: """simple docstring""" if config_path is not None: lowerCamelCase_ =SpeechTaHifiGanConfig.from_pretrained(_A ) else: lowerCamelCase_ =SpeechTaHifiGanConfig() lowerCamelCase_ =SpeechTaHifiGan(_A ) lowerCamelCase_ =torch.load(_A ) load_weights(orig_checkpoint["""model"""]["""generator"""] , _A , _A ) lowerCamelCase_ =np.load(_A ) lowerCamelCase_ =stats[0].reshape(-1 ) lowerCamelCase_ =stats[1].reshape(-1 ) lowerCamelCase_ =torch.from_numpy(_A ).float() lowerCamelCase_ =torch.from_numpy(_A ).float() model.save_pretrained(_A ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(_A ) if __name__ == "__main__": __A : Union[str, Any] = 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.' ) __A : str = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
721
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
75
0
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , **_SCREAMING_SNAKE_CASE , )-> List[Any]: super().__init__(features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =Sql( cache_dir=_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , sql=_SCREAMING_SNAKE_CASE , con=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =None lowerCamelCase_ =None lowerCamelCase_ =None lowerCamelCase_ =None self.builder.download_and_prepare( download_config=_SCREAMING_SNAKE_CASE , download_mode=_SCREAMING_SNAKE_CASE , verification_mode=_SCREAMING_SNAKE_CASE , base_path=_SCREAMING_SNAKE_CASE , ) # Build dataset for splits lowerCamelCase_ =self.builder.as_dataset( split="""train""" , verification_mode=_SCREAMING_SNAKE_CASE , in_memory=self.keep_in_memory ) return dataset class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> List[Any]: if num_proc is not None and num_proc <= 0: raise ValueError(f'num_proc {num_proc} must be an integer > 0.' ) lowerCamelCase_ =dataset lowerCamelCase_ =name lowerCamelCase_ =con lowerCamelCase_ =batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE lowerCamelCase_ =num_proc lowerCamelCase_ =to_sql_kwargs def _snake_case ( self )-> int: lowerCamelCase_ =self.to_sql_kwargs.pop("""sql""" , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.to_sql_kwargs.pop("""con""" , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.to_sql_kwargs.pop("""index""" , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self._write(index=_SCREAMING_SNAKE_CASE , **self.to_sql_kwargs ) return written def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =args lowerCamelCase_ ={**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs lowerCamelCase_ =query_table( table=self.dataset.data , key=slice(_SCREAMING_SNAKE_CASE , offset + self.batch_size ) , indices=self.dataset._indices , ) lowerCamelCase_ =batch.to_pandas() lowerCamelCase_ =df.to_sql(self.name , self.con , index=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return num_rows or len(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: lowerCamelCase_ , lowerCamelCase_ =len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
700
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "deta" _UpperCamelCase:int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , **_SCREAMING_SNAKE_CASE , )-> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase_ =CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =backbone_config.pop("""model_type""" ) lowerCamelCase_ =CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ =config_class.from_dict(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone_config lowerCamelCase_ =num_queries lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =d_model lowerCamelCase_ =encoder_ffn_dim lowerCamelCase_ =encoder_layers lowerCamelCase_ =encoder_attention_heads lowerCamelCase_ =decoder_ffn_dim lowerCamelCase_ =decoder_layers lowerCamelCase_ =decoder_attention_heads lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =activation_dropout lowerCamelCase_ =activation_function lowerCamelCase_ =init_std lowerCamelCase_ =init_xavier_std lowerCamelCase_ =encoder_layerdrop lowerCamelCase_ =auxiliary_loss lowerCamelCase_ =position_embedding_type # deformable attributes lowerCamelCase_ =num_feature_levels lowerCamelCase_ =encoder_n_points lowerCamelCase_ =decoder_n_points lowerCamelCase_ =two_stage lowerCamelCase_ =two_stage_num_proposals lowerCamelCase_ =with_box_refine lowerCamelCase_ =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =mask_loss_coefficient lowerCamelCase_ =dice_loss_coefficient lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient lowerCamelCase_ =focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> int: return self.encoder_attention_heads @property def _snake_case ( self )-> int: return self.d_model def _snake_case ( self )-> str: lowerCamelCase_ =copy.deepcopy(self.__dict__ ) lowerCamelCase_ =self.backbone_config.to_dict() lowerCamelCase_ =self.__class__.model_type return output
75
0
from collections import defaultdict def __UpperCamelCase ( _A : str , _A : str ) ->bool: """simple docstring""" lowerCamelCase_ =first_str.lower().strip() lowerCamelCase_ =second_str.lower().strip() # Remove whitespace lowerCamelCase_ =first_str.replace(""" """ , """""" ) lowerCamelCase_ =second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(_A ) != len(_A ): return False # Default values for count should be 0 lowerCamelCase_ =defaultdict(_A ) # For each character in input strings, # increment count in the corresponding for i in range(len(_A ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() __A : Optional[int] = input('Enter the first string ').strip() __A : str = input('Enter the second string ').strip() __A : Union[str, Any] = check_anagrams(input_a, input_b) print(F"""{input_a} and {input_b} are {"" if status else "not "}anagrams.""")
701
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __A : int = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Any = "albert" def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =vocab_size lowerCamelCase_ =embedding_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_hidden_groups lowerCamelCase_ =num_attention_heads lowerCamelCase_ =inner_group_num lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =position_embedding_type class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
75
0
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker __A : Any = 'CompVis/stable-diffusion-v1-1' __A : Tuple = 'CompVis/stable-diffusion-v1-2' __A : Any = 'CompVis/stable-diffusion-v1-3' __A : str = 'CompVis/stable-diffusion-v1-4' class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , )-> Tuple: super()._init_() lowerCamelCase_ =StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =StableDiffusionPipeline( vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , requires_safety_checker=_SCREAMING_SNAKE_CASE , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def _snake_case ( self )-> Dict[str, Any]: return {k: getattr(self , _SCREAMING_SNAKE_CASE ) for k in self.config.keys() if not k.startswith("""_""" )} def _snake_case ( self , _SCREAMING_SNAKE_CASE = "auto" )-> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase_ =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> str: self.enable_attention_slicing(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , )-> Dict: return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , )-> str: return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , )-> Optional[Any]: lowerCamelCase_ ="""cuda""" if torch.cuda.is_available() else """cpu""" self.to(_SCREAMING_SNAKE_CASE ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(f'`height` and `width` must be divisible by 8 but are {height} and {width}.' ) # Get first result from Stable Diffusion Checkpoint v1.1 lowerCamelCase_ =self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.2 lowerCamelCase_ =self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.3 lowerCamelCase_ =self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.4 lowerCamelCase_ =self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
702
from collections import deque from math import floor from random import random from time import time class _SCREAMING_SNAKE_CASE : def __init__( self )-> List[str]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[Any]: if self.graph.get(_SCREAMING_SNAKE_CASE ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase_ =[[w, v]] if not self.graph.get(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[] def _snake_case ( self )-> str: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> Optional[Any]: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Any: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return len(self.graph[u] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Union[str, Any]: lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =[] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return sorted_nodes def _snake_case ( self )-> str: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> List[str]: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin class _SCREAMING_SNAKE_CASE : def __init__( self )-> Optional[Any]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[str]: # check if the u exists if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase_ =[[w, v]] # add the other way if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase_ =[[w, u]] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) # the other way round if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> int: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return len(self.graph[u] ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self )-> Optional[Any]: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> str: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Dict: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin
75
0
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self )-> Any: lowerCamelCase_ =StableDiffusionKDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler("""sample_euler""" ) lowerCamelCase_ ="""A painting of a squirrel eating a burger""" lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sd_pipe([prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) lowerCamelCase_ =output.images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase_ =np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler("""sample_euler""" ) lowerCamelCase_ ="""A painting of a squirrel eating a burger""" lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sd_pipe([prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) lowerCamelCase_ =output.images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase_ =np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self )-> Dict: lowerCamelCase_ =StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) lowerCamelCase_ =sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) sd_pipe.set_scheduler("""sample_dpmpp_2m""" ) lowerCamelCase_ ="""A painting of a squirrel eating a burger""" lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=15 , output_type="""np""" , use_karras_sigmas=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =output.images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase_ =np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
703
import os from datetime import datetime as dt from github import Github __A : Optional[int] = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase_ =g.get_repo("""huggingface/diffusers""" ) lowerCamelCase_ =repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase_ =sorted(issue.get_comments() , key=lambda _A : i.created_at , reverse=_A ) lowerCamelCase_ =comments[0] if len(_A ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
75
0
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def SCREAMING_SNAKE_CASE_ ( _A : Dataset , _A : Dict[str, str] ) ->str: """simple docstring""" lowerCamelCase_ =args.log_outputs lowerCamelCase_ ="""_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric lowerCamelCase_ =load_metric("""wer""" ) lowerCamelCase_ =load_metric("""cer""" ) # compute metrics lowerCamelCase_ =wer.compute(references=result["""target"""] , predictions=result["""prediction"""] ) lowerCamelCase_ =cer.compute(references=result["""target"""] , predictions=result["""prediction"""] ) # print & log results lowerCamelCase_ =f'WER: {wer_result}\nCER: {cer_result}' print(_A ) with open(f'{dataset_id}_eval_results.txt' , """w""" ) as f: f.write(_A ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: lowerCamelCase_ =f'log_{dataset_id}_predictions.txt' lowerCamelCase_ =f'log_{dataset_id}_targets.txt' with open(_A , """w""" ) as p, open(_A , """w""" ) as t: # mapping function to write output def write_to_file(_A : int , _A : Optional[int] ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(_A , with_indices=_A ) def SCREAMING_SNAKE_CASE_ ( _A : str ) ->str: """simple docstring""" lowerCamelCase_ ="""[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training lowerCamelCase_ =re.sub(_A , """""" , text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! lowerCamelCase_ =["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: lowerCamelCase_ =""" """.join(text.split(_A ) ) return text def SCREAMING_SNAKE_CASE_ ( _A : int ) ->Tuple: """simple docstring""" lowerCamelCase_ =load_dataset(args.dataset , args.config , split=args.split , use_auth_token=_A ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor lowerCamelCase_ =AutoFeatureExtractor.from_pretrained(args.model_id ) lowerCamelCase_ =feature_extractor.sampling_rate # resample audio lowerCamelCase_ =dataset.cast_column("""audio""" , Audio(sampling_rate=_A ) ) # load eval pipeline if args.device is None: lowerCamelCase_ =0 if torch.cuda.is_available() else -1 lowerCamelCase_ =pipeline("""automatic-speech-recognition""" , model=args.model_id , device=args.device ) # map function to decode audio def map_to_pred(_A : Dict ): lowerCamelCase_ =asr( batch["""audio"""]["""array"""] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s ) lowerCamelCase_ =prediction["""text"""] lowerCamelCase_ =normalize_text(batch["""sentence"""] ) return batch # run inference on all examples lowerCamelCase_ =dataset.map(_A , remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(_A , _A ) if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '--model_id', type=str, required=True, help='Model identifier. Should be loadable with 🤗 Transformers' ) parser.add_argument( '--dataset', type=str, required=True, help='Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets', ) parser.add_argument( '--config', type=str, required=True, help='Config of the dataset. *E.g.* `\'en\'` for Common Voice' ) parser.add_argument('--split', type=str, required=True, help='Split of the dataset. *E.g.* `\'test\'`') parser.add_argument( '--chunk_length_s', type=float, default=None, help='Chunk length in seconds. Defaults to 5 seconds.' ) parser.add_argument( '--stride_length_s', type=float, default=None, help='Stride of the audio chunks. Defaults to 1 second.' ) parser.add_argument( '--log_outputs', action='store_true', help='If defined, write outputs to log file for analysis.' ) parser.add_argument( '--device', type=int, default=None, help='The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.', ) __A : Dict = parser.parse_args() main(args)
704
import argparse import os import re __A : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. __A : int = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. __A : int = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Optional[Any] = re.compile(R'\[([^\]]+)\]') def __UpperCamelCase ( _A : int ) ->Dict: """simple docstring""" lowerCamelCase_ =_re_indent.search(_A ) return "" if search is None else search.groups()[0] def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 lowerCamelCase_ =["""\n""".join(lines[:index] )] else: lowerCamelCase_ =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ =[lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_A ) ) if index < len(_A ) - 1: lowerCamelCase_ =[lines[index + 1]] index += 1 else: lowerCamelCase_ =[] else: blocks.append("""\n""".join(_A ) ) lowerCamelCase_ =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append("""\n""".join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def __UpperCamelCase ( _A : Optional[int] ) ->Optional[int]: """simple docstring""" def _inner(_A : Optional[Any] ): return key(_A ).lower().replace("""_""" , """""" ) return _inner def __UpperCamelCase ( _A : int , _A : List[Any]=None ) ->List[str]: """simple docstring""" # If no key is provided, we use a noop. def noop(_A : List[str] ): return x if key is None: lowerCamelCase_ =noop # Constants are all uppercase, they go first. lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()] lowerCamelCase_ =ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def __UpperCamelCase ( _A : List[str] ) ->List[str]: """simple docstring""" # This inner function sort imports between [ ]. def _replace(_A : Optional[Any] ): lowerCamelCase_ =match.groups()[0] if "," not in imports: return f'[{imports}]' lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" lowerCamelCase_ =import_statement.split("""\n""" ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase_ =2 if lines[1].strip() == """[""" else 1 lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] ) lowerCamelCase_ =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase_ =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] lowerCamelCase_ =get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase_ =_re_bracket_content.sub(_replace , _A ) return import_statement def __UpperCamelCase ( _A : List[Any] , _A : Optional[Any]=True ) ->str: """simple docstring""" with open(_A , """r""" ) as f: lowerCamelCase_ =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ =split_code_in_indented_blocks( _A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ =main_blocks[block_idx] lowerCamelCase_ =block.split("""\n""" ) # Get to the start of the imports. lowerCamelCase_ =0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase_ =len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] ) lowerCamelCase_ =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ =_re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase_ =[(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase_ =[(i, key) for i, key in enumerate(_A ) if key is not None] lowerCamelCase_ =[x[0] for x in sorted(_A , key=lambda _A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase_ =0 lowerCamelCase_ =[] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , """w""" ) as f: f.write("""\n""".join(_A ) ) def __UpperCamelCase ( _A : str=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A ) if result: lowerCamelCase_ =[os.path.join(_A , """__init__.py""" )] if len(_A ) > 0: raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') __A : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
75
0
__A : Optional[int] = frozenset( [ 'prompt', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) __A : Any = frozenset(['prompt', 'negative_prompt']) __A : Any = frozenset([]) __A : List[str] = frozenset(['image']) __A : Optional[Any] = frozenset( [ 'image', 'height', 'width', 'guidance_scale', ] ) __A : Optional[Any] = frozenset(['image']) __A : Optional[Any] = frozenset( [ 'prompt', 'image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) __A : Union[str, Any] = frozenset(['prompt', 'image', 'negative_prompt']) __A : Union[str, Any] = frozenset( [ # Text guided image variation with an image mask 'prompt', 'image', 'mask_image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) __A : Dict = frozenset(['prompt', 'image', 'mask_image', 'negative_prompt']) __A : str = frozenset( [ # image variation with an image mask 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) __A : Dict = frozenset(['image', 'mask_image']) __A : Any = frozenset( [ 'example_image', 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) __A : Dict = frozenset(['example_image', 'image', 'mask_image']) __A : int = frozenset(['class_labels']) __A : Any = frozenset(['class_labels']) __A : int = frozenset(['batch_size']) __A : Union[str, Any] = frozenset([]) __A : int = frozenset(['batch_size']) __A : Optional[int] = frozenset([]) __A : Union[str, Any] = frozenset( [ 'prompt', 'audio_length_in_s', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) __A : Any = frozenset(['prompt', 'negative_prompt']) __A : Optional[int] = frozenset(['input_tokens']) __A : Union[str, Any] = frozenset(['input_tokens'])
705
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : str = {'vocab_file': 'sentencepiece.model'} __A : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } __A : int = { 'google/rembert': 2_56, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Dict: return len(self.sp_model ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> Optional[Any]: lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =d lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
75
0
__A : Union[str, Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' def __UpperCamelCase ( _A : bytes ) ->bytes: """simple docstring""" # Make sure the supplied data is a bytes-like object if not isinstance(_A , _A ): lowerCamelCase_ =f'a bytes-like object is required, not \'{data.__class__.__name__}\'' raise TypeError(_A ) lowerCamelCase_ ="""""".join(bin(_A )[2:].zfill(8 ) for byte in data ) lowerCamelCase_ =len(_A ) % 6 != 0 if padding_needed: # The padding that will be added later lowerCamelCase_ =B"""=""" * ((6 - len(_A ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_A ) % 6) else: lowerCamelCase_ =B"""""" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_A ) , 6 ) ).encode() + padding ) def __UpperCamelCase ( _A : str ) ->bytes: """simple docstring""" # Make sure encoded_data is either a string or a bytes-like object if not isinstance(_A , _A ) and not isinstance(_A , _A ): lowerCamelCase_ =( """argument should be a bytes-like object or ASCII string, """ f'not \'{encoded_data.__class__.__name__}\'' ) raise TypeError(_A ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_A , _A ): try: lowerCamelCase_ =encoded_data.decode("""utf-8""" ) except UnicodeDecodeError: raise ValueError("""base64 encoded data should only contain ASCII characters""" ) lowerCamelCase_ =encoded_data.count("""=""" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_A ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one lowerCamelCase_ =encoded_data[:-padding] lowerCamelCase_ ="""""".join( bin(B64_CHARSET.index(_A ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: lowerCamelCase_ ="""""".join( bin(B64_CHARSET.index(_A ) )[2:].zfill(6 ) for char in encoded_data ) lowerCamelCase_ =[ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_A ) , 8 ) ] return bytes(_A ) if __name__ == "__main__": import doctest doctest.testmod()
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
75
0
from __future__ import annotations class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =TypeError( """Matrices must be formed from a list of zero or more lists containing at """ """least one and the same number of values, each of which must be of type """ """int or float.""" ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =len(rows[0] ) if cols == 0: raise error for row in rows: if len(_SCREAMING_SNAKE_CASE ) != cols: raise error for value in row: if not isinstance(_SCREAMING_SNAKE_CASE , (int, float) ): raise error lowerCamelCase_ =rows else: lowerCamelCase_ =[] def _snake_case ( self )-> list[list[int]]: return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )] @property def _snake_case ( self )-> int: return len(self.rows ) @property def _snake_case ( self )-> int: return len(self.rows[0] ) @property def _snake_case ( self )-> tuple[int, int]: return (self.num_rows, self.num_columns) @property def _snake_case ( self )-> bool: return self.order[0] == self.order[1] def _snake_case ( self )-> Matrix: lowerCamelCase_ =[ [0 if column_num != row_num else 1 for column_num in range(self.num_rows )] for row_num in range(self.num_rows ) ] return Matrix(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> int: if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0] ) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns ) ) def _snake_case ( self )-> bool: return bool(self.determinant() ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =[ [ self.rows[other_row][other_column] for other_column in range(self.num_columns ) if other_column != column ] for other_row in range(self.num_rows ) if other_row != row ] return Matrix(_SCREAMING_SNAKE_CASE ).determinant() def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> int: if (row + column) % 2 == 0: return self.get_minor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return -1 * self.get_minor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Matrix: return Matrix( [ [self.get_minor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for column in range(self.num_columns )] for row in range(self.num_rows ) ] ) def _snake_case ( self )-> Matrix: return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns ) ] for row in range(self.minors().num_rows ) ] ) def _snake_case ( self )-> Matrix: lowerCamelCase_ =[ [self.cofactors().rows[column][row] for column in range(self.num_columns )] for row in range(self.num_rows ) ] return Matrix(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Matrix: lowerCamelCase_ =self.determinant() if not determinant: raise TypeError("""Only matrices with a non-zero determinant have an inverse""" ) return self.adjugate() * (1 / determinant) def __repr__( self )-> str: return str(self.rows ) def __str__( self )-> str: if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0] ) ) + "]]" return ( "[" + "\n ".join( [ """[""" + """. """.join([str(_SCREAMING_SNAKE_CASE ) for value in row] ) + """.]""" for row in self.rows ] ) + "]" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> None: lowerCamelCase_ =TypeError("""Row must be a list containing all ints and/or floats""" ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise type_error for value in row: if not isinstance(_SCREAMING_SNAKE_CASE , (int, float) ): raise type_error if len(_SCREAMING_SNAKE_CASE ) != self.num_columns: raise ValueError( """Row must be equal in length to the other rows in the matrix""" ) if position is None: self.rows.append(_SCREAMING_SNAKE_CASE ) else: lowerCamelCase_ =self.rows[0:position] + [row] + self.rows[position:] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> None: lowerCamelCase_ =TypeError( """Column must be a list containing all ints and/or floats""" ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise type_error for value in column: if not isinstance(_SCREAMING_SNAKE_CASE , (int, float) ): raise type_error if len(_SCREAMING_SNAKE_CASE ) != self.num_rows: raise ValueError( """Column must be equal in length to the other columns in the matrix""" ) if position is None: lowerCamelCase_ =[self.rows[i] + [column[i]] for i in range(self.num_rows )] else: lowerCamelCase_ =[ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows ) ] def __eq__( self , _SCREAMING_SNAKE_CASE )-> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return NotImplemented return self.rows == other.rows def __ne__( self , _SCREAMING_SNAKE_CASE )-> bool: return not self == other def __neg__( self )-> Matrix: return self * -1 def __add__( self , _SCREAMING_SNAKE_CASE )-> Matrix: if self.order != other.order: raise ValueError("""Addition requires matrices of the same order""" ) return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __sub__( self , _SCREAMING_SNAKE_CASE )-> Matrix: if self.order != other.order: raise ValueError("""Subtraction requires matrices of the same order""" ) return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __mul__( self , _SCREAMING_SNAKE_CASE )-> Matrix: if isinstance(_SCREAMING_SNAKE_CASE , (int, float) ): return Matrix( [[int(element * other ) for element in row] for row in self.rows] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if self.num_columns != other.num_rows: raise ValueError( """The number of columns in the first matrix must """ """be equal to the number of rows in the second""" ) return Matrix( [ [Matrix.dot_product(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( """A Matrix can only be multiplied by an int, float, or another matrix""" ) def __pow__( self , _SCREAMING_SNAKE_CASE )-> Matrix: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError("""A Matrix can only be raised to the power of an int""" ) if not self.is_square: raise ValueError("""Only square matrices can be raised to a power""" ) if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( """Only invertable matrices can be raised to a negative power""" ) lowerCamelCase_ =self for _ in range(other - 1 ): result *= self return result @classmethod def _snake_case ( cls , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> int: return sum(row[i] * column[i] for i in range(len(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
707
# 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.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input __A : List[str] = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def __UpperCamelCase ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =_ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase_ =get_sagemaker_input() else: lowerCamelCase_ =get_cluster_input() return config def __UpperCamelCase ( _A : List[str]=None ) ->str: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""config""" , description=_A ) else: lowerCamelCase_ =argparse.ArgumentParser("""Accelerate config command""" , description=_A ) parser.add_argument( """--config_file""" , default=_A , 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=_A ) return parser def __UpperCamelCase ( _A : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =get_user_input() if args.config_file is not None: lowerCamelCase_ =args.config_file else: if not os.path.isdir(_A ): os.makedirs(_A ) lowerCamelCase_ =default_yaml_config_file if config_file.endswith(""".json""" ): config.to_json_file(_A ) else: config.to_yaml_file(_A ) print(f'accelerate configuration saved at {config_file}' ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =config_command_parser() lowerCamelCase_ =parser.parse_args() config_command(_A ) if __name__ == "__main__": main()
75
0
'''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 warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =data def __iter__( self )-> Any: for element in self.data: yield element def __UpperCamelCase ( _A : List[str]=True ) ->str: """simple docstring""" lowerCamelCase_ =Accelerator(even_batches=_A ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def __UpperCamelCase ( _A : Accelerator , _A : int , _A : int , _A : bool = False ) ->List[str]: """simple docstring""" if iterable: lowerCamelCase_ =DummyIterableDataset(torch.as_tensor(range(_A ) ) ) else: lowerCamelCase_ =TensorDataset(torch.as_tensor(range(_A ) ) ) lowerCamelCase_ =DataLoader(_A , batch_size=_A ) lowerCamelCase_ =accelerator.prepare(_A ) return dl def __UpperCamelCase ( _A : Accelerator , _A : int , _A : int , _A : List[int] , _A : List[int] , ) ->Any: """simple docstring""" lowerCamelCase_ =create_dataloader(accelerator=_A , dataset_size=_A , batch_size=_A ) lowerCamelCase_ =[len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( _A , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( _A , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def __UpperCamelCase ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =create_accelerator(even_batches=_A ) verify_dataloader_batch_sizes( _A , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( _A , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =create_accelerator(even_batches=_A ) lowerCamelCase_ =torch.nn.Linear(1 , 1 ) lowerCamelCase_ =accelerator.prepare(_A ) lowerCamelCase_ =create_dataloader(_A , dataset_size=3 , batch_size=1 ) lowerCamelCase_ =[] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(_A ): lowerCamelCase_ =ddp_model(batch[0].float() ) lowerCamelCase_ =output.sum() loss.backward() batch_idxs.append(_A ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def __UpperCamelCase ( _A : Any ) ->Any: """simple docstring""" with warnings.catch_warnings(record=_A ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , _A ) assert "only supported for multi-GPU" in str(w[-1].message ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =True lowerCamelCase_ =False lowerCamelCase_ =create_accelerator(even_batches=_A ) lowerCamelCase_ =torch.nn.Linear(1 , 1 ) lowerCamelCase_ =accelerator.prepare(_A ) lowerCamelCase_ =create_dataloader(_A , dataset_size=3 , batch_size=1 ) lowerCamelCase_ =create_dataloader(_A , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=_A ): lowerCamelCase_ =train_dl.batch_sampler.even_batches lowerCamelCase_ =valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def __UpperCamelCase ( ) ->int: """simple docstring""" lowerCamelCase_ =True lowerCamelCase_ =False lowerCamelCase_ =create_accelerator(even_batches=_A ) lowerCamelCase_ =torch.nn.Linear(1 , 1 ) lowerCamelCase_ =accelerator.prepare(_A ) create_dataloader(_A , dataset_size=3 , batch_size=1 , iterable=_A ) lowerCamelCase_ =create_dataloader(_A , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=_A ): lowerCamelCase_ =batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =create_accelerator() lowerCamelCase_ =torch.nn.Linear(1 , 1 ) lowerCamelCase_ =accelerator.prepare(_A ) create_dataloader(_A , dataset_size=3 , batch_size=1 , iterable=_A ) with warnings.catch_warnings(record=_A ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=_A ): pass assert issubclass(w[-1].category , _A ) assert "only supported for map-style datasets" in str(w[-1].message ) def __UpperCamelCase ( ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) lowerCamelCase_ =accelerator.state.distributed_type lowerCamelCase_ =DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(_A ) lowerCamelCase_ =original_state if __name__ == "__main__": main()
708
def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[[] for _ in range(_A )] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_A ) <= key: return input_string for position, character in enumerate(_A ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_A ) lowerCamelCase_ =["""""".join(_A ) for row in temp_grid] lowerCamelCase_ ="""""".join(_A ) return output_string def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string lowerCamelCase_ =[[] for _ in range(_A )] # generates template for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) lowerCamelCase_ =0 for row in temp_grid: # fills in the characters lowerCamelCase_ =input_string[counter : counter + len(_A )] grid.append(list(_A ) ) counter += len(_A ) lowerCamelCase_ ="""""" # reads as zigzag for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __UpperCamelCase ( _A : str ) ->dict[int, str]: """simple docstring""" lowerCamelCase_ ={} for key_guess in range(1 , len(_A ) ): # tries every key lowerCamelCase_ =decrypt(_A , _A ) return results if __name__ == "__main__": import doctest doctest.testmod()
75
0
import argparse import os import re __A : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. __A : int = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. __A : int = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Optional[Any] = re.compile(R'\[([^\]]+)\]') def __lowercase ( _A : int ) ->Dict: """simple docstring""" lowerCamelCase_ =_re_indent.search(_A ) return "" if search is None else search.groups()[0] def __lowercase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 lowerCamelCase_ =["""\n""".join(lines[:index] )] else: lowerCamelCase_ =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ =[lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_A ) ) if index < len(_A ) - 1: lowerCamelCase_ =[lines[index + 1]] index += 1 else: lowerCamelCase_ =[] else: blocks.append("""\n""".join(_A ) ) lowerCamelCase_ =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append("""\n""".join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def __lowercase ( _A : Optional[int] ) ->Optional[int]: """simple docstring""" def _inner(_A : Optional[Any] ): return key(_A ).lower().replace("""_""" , """""" ) return _inner def __lowercase ( _A : int , _A : List[Any]=None ) ->List[str]: """simple docstring""" # If no key is provided, we use a noop. def noop(_A : List[str] ): return x if key is None: lowerCamelCase_ =noop # Constants are all uppercase, they go first. lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()] lowerCamelCase_ =ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def __lowercase ( _A : List[str] ) ->List[str]: """simple docstring""" # This inner function sort imports between [ ]. def _replace(_A : Optional[Any] ): lowerCamelCase_ =match.groups()[0] if "," not in imports: return f'[{imports}]' lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" lowerCamelCase_ =import_statement.split("""\n""" ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase_ =2 if lines[1].strip() == """[""" else 1 lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] ) lowerCamelCase_ =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase_ =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] lowerCamelCase_ =get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase_ =_re_bracket_content.sub(_replace , _A ) return import_statement def __lowercase ( _A : List[Any] , _A : Optional[Any]=True ) ->str: """simple docstring""" with open(_A , """r""" ) as f: lowerCamelCase_ =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ =split_code_in_indented_blocks( _A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ =main_blocks[block_idx] lowerCamelCase_ =block.split("""\n""" ) # Get to the start of the imports. lowerCamelCase_ =0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase_ =len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] ) lowerCamelCase_ =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ =_re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase_ =[(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase_ =[(i, key) for i, key in enumerate(_A ) if key is not None] lowerCamelCase_ =[x[0] for x in sorted(_A , key=lambda _A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase_ =0 lowerCamelCase_ =[] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , """w""" ) as f: f.write("""\n""".join(_A ) ) def __lowercase ( _A : str=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A ) if result: lowerCamelCase_ =[os.path.join(_A , """__init__.py""" )] if len(_A ) > 0: raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') __A : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
709
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =data lowerCamelCase_ =None class _SCREAMING_SNAKE_CASE : def __init__( self )-> Any: lowerCamelCase_ =None def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.head while temp is not None: print(temp.data , end=""" """ ) lowerCamelCase_ =temp.next print() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =Node(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.head lowerCamelCase_ =new_node def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if node_data_a == node_data_a: return else: lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ =node_a.data, node_a.data if __name__ == "__main__": __A : Optional[int] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
75
0
from typing import Any def __UpperCamelCase ( _A : list , _A : list , _A : dict , _A : dict , _A : dict , ) ->list: """simple docstring""" _validation( _A , _A , _A , _A , _A , ) # Creates data structures and fill initial step lowerCamelCase_ ={} lowerCamelCase_ ={} for state in states_space: lowerCamelCase_ =observations_space[0] lowerCamelCase_ =( initial_probabilities[state] * emission_probabilities[state][observation] ) lowerCamelCase_ =None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1 , len(_A ) ): lowerCamelCase_ =observations_space[o] lowerCamelCase_ =observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function lowerCamelCase_ ="""""" lowerCamelCase_ =-1 for k_state in states_space: lowerCamelCase_ =( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: lowerCamelCase_ =probability lowerCamelCase_ =k_state # Update probabilities and pointers dicts lowerCamelCase_ =( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) lowerCamelCase_ =arg_max # The final observation lowerCamelCase_ =observations_space[len(_A ) - 1] # argmax for given final observation lowerCamelCase_ ="""""" lowerCamelCase_ =-1 for k_state in states_space: lowerCamelCase_ =probabilities[(k_state, final_observation)] if probability > max_probability: lowerCamelCase_ =probability lowerCamelCase_ =k_state lowerCamelCase_ =arg_max # Process pointers backwards lowerCamelCase_ =last_state lowerCamelCase_ =[] for o in range(len(_A ) - 1 , -1 , -1 ): result.append(_A ) lowerCamelCase_ =pointers[previous, observations_space[o]] result.reverse() return result def __UpperCamelCase ( _A : Any , _A : Any , _A : Any , _A : Any , _A : Any , ) ->None: """simple docstring""" _validate_not_empty( _A , _A , _A , _A , _A , ) _validate_lists(_A , _A ) _validate_dicts( _A , _A , _A ) def __UpperCamelCase ( _A : Any , _A : Any , _A : Any , _A : Any , _A : Any , ) ->None: """simple docstring""" if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("""There's an empty parameter""" ) def __UpperCamelCase ( _A : Any , _A : Any ) ->None: """simple docstring""" _validate_list(_A , """observations_space""" ) _validate_list(_A , """states_space""" ) def __UpperCamelCase ( _A : Any , _A : str ) ->None: """simple docstring""" if not isinstance(_object , _A ): lowerCamelCase_ =f'{var_name} must be a list' raise ValueError(_A ) else: for x in _object: if not isinstance(_A , _A ): lowerCamelCase_ =f'{var_name} must be a list of strings' raise ValueError(_A ) def __UpperCamelCase ( _A : Any , _A : Any , _A : Any , ) ->None: """simple docstring""" _validate_dict(_A , """initial_probabilities""" , _A ) _validate_nested_dict(_A , """transition_probabilities""" ) _validate_nested_dict(_A , """emission_probabilities""" ) def __UpperCamelCase ( _A : Any , _A : str ) ->None: """simple docstring""" _validate_dict(_object , _A , _A ) for x in _object.values(): _validate_dict(_A , _A , _A , _A ) def __UpperCamelCase ( _A : Any , _A : str , _A : type , _A : bool = False ) ->None: """simple docstring""" if not isinstance(_object , _A ): lowerCamelCase_ =f'{var_name} must be a dict' raise ValueError(_A ) if not all(isinstance(_A , _A ) for x in _object ): lowerCamelCase_ =f'{var_name} all keys must be strings' raise ValueError(_A ) if not all(isinstance(_A , _A ) for x in _object.values() ): lowerCamelCase_ ="""nested dictionary """ if nested else """""" lowerCamelCase_ =f'{var_name} {nested_text}all values must be {value_type.__name__}' raise ValueError(_A ) if __name__ == "__main__": from doctest import testmod testmod()
710
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "yolos" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=[512, 864] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =qkv_bias lowerCamelCase_ =num_detection_tokens lowerCamelCase_ =use_mid_position_embeddings lowerCamelCase_ =auxiliary_loss # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = version.parse("1.11") @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self )-> float: return 1E-4 @property def _snake_case ( self )-> int: return 12
75
0
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: lowerCamelCase_ =dataset lowerCamelCase_ =process lowerCamelCase_ =params def __len__( self )-> str: return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE )-> Dict: lowerCamelCase_ =self.dataset[i] lowerCamelCase_ =self.process(_SCREAMING_SNAKE_CASE , **self.params ) return processed class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> List[str]: lowerCamelCase_ =loader lowerCamelCase_ =infer lowerCamelCase_ =params if loader_batch_size == 1: # Let's spare some time by deactivating altogether lowerCamelCase_ =None lowerCamelCase_ =loader_batch_size # Internal bookkeeping lowerCamelCase_ =None lowerCamelCase_ =None def __len__( self )-> List[Any]: return len(self.loader ) def __iter__( self )-> Tuple: lowerCamelCase_ =iter(self.loader ) return self def _snake_case ( self )-> int: if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice lowerCamelCase_ =self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) lowerCamelCase_ ={} for k, element in self._loader_batch_data.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Convert ModelOutput to tuple first lowerCamelCase_ =element.to_tuple() if isinstance(element[0] , torch.Tensor ): lowerCamelCase_ =tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase_ =tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): lowerCamelCase_ =tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase_ =tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around lowerCamelCase_ =None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase_ =element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase_ =np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. lowerCamelCase_ =element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 lowerCamelCase_ =self._loader_batch_data.__class__(_SCREAMING_SNAKE_CASE ) self._loader_batch_index += 1 return result def _snake_case ( self )-> Union[str, Any]: if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch lowerCamelCase_ =next(self.iterator ) lowerCamelCase_ =self.infer(_SCREAMING_SNAKE_CASE , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): lowerCamelCase_ =processed else: lowerCamelCase_ =list(processed.keys() )[0] lowerCamelCase_ =processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) else: lowerCamelCase_ =first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase_ =observed_batch_size # Setting internal index to unwrap the batch lowerCamelCase_ =processed lowerCamelCase_ =0 return self.loader_batch_item() else: # We're not unrolling batches return processed class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> List[Any]: super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __iter__( self )-> int: lowerCamelCase_ =iter(self.loader ) lowerCamelCase_ =None return self def _snake_case ( self )-> Optional[Any]: if self.subiterator is None: lowerCamelCase_ =self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item lowerCamelCase_ =next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators lowerCamelCase_ =self.infer(next(self.iterator ) , **self.params ) lowerCamelCase_ =next(self.subiterator ) return processed class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __iter__( self )-> Any: lowerCamelCase_ =iter(self.loader ) return self def _snake_case ( self )-> List[str]: # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. lowerCamelCase_ =False lowerCamelCase_ =[] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: lowerCamelCase_ =self.loader_batch_item() lowerCamelCase_ =item.pop("""is_last""" ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator while not is_last: lowerCamelCase_ =self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): lowerCamelCase_ =processed else: lowerCamelCase_ =list(processed.keys() )[0] lowerCamelCase_ =processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) else: lowerCamelCase_ =first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase_ =observed_batch_size lowerCamelCase_ =processed lowerCamelCase_ =0 while self._loader_batch_index < self.loader_batch_size: lowerCamelCase_ =self.loader_batch_item() lowerCamelCase_ =item.pop("""is_last""" ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator else: lowerCamelCase_ =processed lowerCamelCase_ =item.pop("""is_last""" ) accumulator.append(_SCREAMING_SNAKE_CASE ) return accumulator class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =dataset lowerCamelCase_ =key def __len__( self )-> Optional[int]: return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE )-> Any: return self.dataset[i][self.key] class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Any: lowerCamelCase_ =dataset lowerCamelCase_ =keya lowerCamelCase_ =keya def __len__( self )-> List[Any]: return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
711
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py __A : List[Any] = 'src/transformers' __A : Tuple = 'docs/source/en' __A : Optional[int] = '.' def __UpperCamelCase ( _A : Tuple , _A : Tuple , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | __A : Dict = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. __A : Optional[int] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Optional[int] = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : str = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. __A : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def __UpperCamelCase ( _A : List[Any] ) ->str: """simple docstring""" lowerCamelCase_ =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _A ) return [m.group(0 ) for m in matches] def __UpperCamelCase ( _A : Union[str, Any] , _A : List[str] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =2 if text == """✅""" or text == """❌""" else len(_A ) lowerCamelCase_ =(width - text_length) // 2 lowerCamelCase_ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCamelCase_ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCamelCase_ ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) # Let's lookup through all transformers object (once). for attr_name in dir(_A ): lowerCamelCase_ =None if attr_name.endswith("""Tokenizer""" ): lowerCamelCase_ =slow_tokenizers lowerCamelCase_ =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): lowerCamelCase_ =fast_tokenizers lowerCamelCase_ =attr_name[:-13] elif _re_tf_models.match(_A ) is not None: lowerCamelCase_ =tf_models lowerCamelCase_ =_re_tf_models.match(_A ).groups()[0] elif _re_flax_models.match(_A ) is not None: lowerCamelCase_ =flax_models lowerCamelCase_ =_re_flax_models.match(_A ).groups()[0] elif _re_pt_models.match(_A ) is not None: lowerCamelCase_ =pt_models lowerCamelCase_ =_re_pt_models.match(_A ).groups()[0] if lookup_dict is not None: while len(_A ) > 0: if attr_name in model_name_to_prefix.values(): lowerCamelCase_ =True break # Try again after removing the last word in the name lowerCamelCase_ ="""""".join(camel_case_split(_A )[:-1] ) # Let's build that table! lowerCamelCase_ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCamelCase_ =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowerCamelCase_ =[len(_A ) + 2 for c in columns] lowerCamelCase_ =max([len(_A ) for name in model_names] ) + 2 # Build the table per se lowerCamelCase_ ="""|""" + """|""".join([_center_text(_A , _A ) for c, w in zip(_A , _A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" lowerCamelCase_ ={True: """✅""", False: """❌"""} for name in model_names: lowerCamelCase_ =model_name_to_prefix[name] lowerCamelCase_ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_A , _A ) for l, w in zip(_A , _A )] ) + "|\n" return table def __UpperCamelCase ( _A : str=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) lowerCamelCase_ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
75
0
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def __UpperCamelCase ( _A : Optional[int] ) ->int: """simple docstring""" lowerCamelCase_ =[ """decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(_A , _A ) def __UpperCamelCase ( _A : Any ) ->List[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ =emb.weight.shape lowerCamelCase_ =nn.Linear(_A , _A , bias=_A ) lowerCamelCase_ =emb.weight.data return lin_layer def __UpperCamelCase ( _A : List[Any] ) ->int: """simple docstring""" lowerCamelCase_ =torch.load(_A , map_location="""cpu""" ) lowerCamelCase_ =Namespace(**checkpoint["""cfg"""]["""model"""] ) lowerCamelCase_ =checkpoint["""model"""] remove_ignore_keys_(_A ) lowerCamelCase_ =state_dict["""decoder.embed_tokens.weight"""].shape[0] lowerCamelCase_ ={key.replace("""decoder""" , """model""" ): val for key, val in state_dict.items()} lowerCamelCase_ =XGLMConfig( vocab_size=_A , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""gelu""" , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) lowerCamelCase_ =XGLMForCausalLM(_A ) lowerCamelCase_ =model.load_state_dict(_A , strict=_A ) print(_A ) lowerCamelCase_ =make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": __A : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') __A : int = parser.parse_args() __A : Optional[Any] = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
712
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =num_stages lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =out_features lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =num_stages def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self )-> Union[str, Any]: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_SCREAMING_SNAKE_CASE , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_SCREAMING_SNAKE_CASE , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCamelCase:Any = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Dict = False _UpperCamelCase:int = False _UpperCamelCase:Any = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> int: lowerCamelCase_ =UperNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( 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 _snake_case ( self )-> Tuple: return def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _snake_case ( self )-> List[Any]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> str: pass def _snake_case ( self )-> Optional[int]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =_config_zero_init(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =_config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ =model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _snake_case ( self )-> Dict: pass @slow def _snake_case ( self )-> Tuple: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Tuple: """simple docstring""" lowerCamelCase_ =hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) lowerCamelCase_ =Image.open(_A ).convert("""RGB""" ) return image @require_torch @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def _snake_case ( self )-> int: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
75
0
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =cva.getAffineTransform(_A , _A ) return cva.warpAffine(_A , _A , (rows, cols) ) if __name__ == "__main__": # read original image __A : str = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value __A : List[Any] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape __A : int = gray_img.shape # set different points to rotate image __A : Optional[int] = np.array([[50, 50], [2_00, 50], [50, 2_00]], np.floataa) __A : List[str] = np.array([[10, 1_00], [2_00, 50], [1_00, 2_50]], np.floataa) __A : List[str] = np.array([[50, 50], [1_50, 50], [1_20, 2_00]], np.floataa) __A : Optional[Any] = np.array([[10, 1_00], [80, 50], [1_80, 2_50]], np.floataa) # add all rotated images in a list __A : Any = [ 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 __A : Optional[int] = plt.figure(1) __A : Optional[Any] = ['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()
713
from typing import Dict, Iterable, 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, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_MEAN , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_STD , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ =int((256 / 224) * size["""shortest_edge"""] ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""height""": output_size[0], """width""": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( _SCREAMING_SNAKE_CASE , size=(size_dict["""height"""], size_dict["""width"""]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: 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_center_crop if do_center_crop is not None else self.do_center_crop 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_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_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.""" ) # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
75
0
import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py __A : List[Any] = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. __A : Any = direct_transformers_import(PATH_TO_TRANSFORMERS) __A : Optional[int] = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` __A : List[Any] = re.compile(R'\[(.+?)\]\((https://huggingface\.co/.+?)\)') __A : List[str] = { 'DecisionTransformerConfig', 'EncoderDecoderConfig', 'MusicgenConfig', 'RagConfig', 'SpeechEncoderDecoderConfig', 'TimmBackboneConfig', 'VisionEncoderDecoderConfig', 'VisionTextDualEncoderConfig', 'LlamaConfig', } def __UpperCamelCase ( _A : Optional[int] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =None # source code of `config_class` lowerCamelCase_ =inspect.getsource(_A ) lowerCamelCase_ =_re_checkpoint.findall(_A ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("""/""" ): lowerCamelCase_ =ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link lowerCamelCase_ =f'https://huggingface.co/{ckpt_name}' if ckpt_link == ckpt_link_from_name: lowerCamelCase_ =ckpt_name break return checkpoint def __UpperCamelCase ( ) ->str: """simple docstring""" lowerCamelCase_ =[] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue lowerCamelCase_ =get_checkpoint_from_config_class(_A ) lowerCamelCase_ =config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_A ) if len(_A ) > 0: lowerCamelCase_ ="""\n""".join(sorted(_A ) ) raise ValueError(f'The following configurations don\'t contain any valid checkpoint:\n{message}' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
714
# Imports import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Any: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: if red is not None: lowerCamelCase_ =red if green is not None: lowerCamelCase_ =green if blue is not None: lowerCamelCase_ =blue if red_edge is not None: lowerCamelCase_ =red_edge if nir is not None: lowerCamelCase_ =nir return True def _snake_case ( self , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def _snake_case ( self )-> Optional[Any]: return -0.1_8 + (1.1_7 * ((self.nir - self.red) / (self.nir + self.red))) def _snake_case ( self )-> Tuple: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _snake_case ( self )-> str: return self.nir * (self.red / (self.green**2)) def _snake_case ( self )-> Optional[int]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _snake_case ( self )-> Tuple: return (self.nir - self.red) / (self.nir + self.red) def _snake_case ( self )-> Dict: return (self.nir - self.blue) / (self.nir + self.blue) def _snake_case ( self )-> List[Any]: return (self.redEdge - self.red) / (self.redEdge + self.red) def _snake_case ( self )-> Tuple: return (self.nir - self.green) / (self.nir + self.green) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.0_8 , _SCREAMING_SNAKE_CASE=1.2_2 , _SCREAMING_SNAKE_CASE=0.0_3 )-> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _snake_case ( self )-> Tuple: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _snake_case ( self )-> Any: return (self.nir / self.green) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.nir / self.redEdge) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.red - self.blue) / self.red def _snake_case ( self )-> Dict: lowerCamelCase_ =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _snake_case ( self )-> int: return self.nir - self.green def _snake_case ( self )-> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.2_5 * n) - (self.red - 0.1_2_5) / (1 - self.red) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.1_6 )-> List[Any]: return (self.nir - self.green) / (self.nir + self.green + y) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.5 )-> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _snake_case ( self )-> int: return np.arctan( ((2 * self.red - self.green - self.blue) / 3_0.5) * (self.green - self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: return (self.nir - b) / (a * self.red) def _snake_case ( self )-> int: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _snake_case ( self )-> Optional[Any]: return (self.red + self.green + self.blue) / 3_0.5 def _snake_case ( self )-> List[str]: return self.nir / self.red def _snake_case ( self )-> List[str]: return (self.rvi() - 1) / (self.rvi() + 1) def _snake_case ( self )-> str: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _snake_case ( self )-> List[Any]: return self.green / (self.nir + self.red + self.green) def _snake_case ( self )-> Dict: return self.nir / (self.nir + self.red + self.green) def _snake_case ( self )-> List[str]: return self.red / (self.nir + self.red + self.green) def _snake_case ( self )-> int: return (self.green - self.red) / (self.green + self.red) def _snake_case ( self )-> str: return (self.red - self.green) / (self.red + self.green) def _snake_case ( self )-> str: lowerCamelCase_ =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCamelCase_ =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _snake_case ( self )-> List[str]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _snake_case ( self )-> List[Any]: return self.nir / self.red def _snake_case ( self )-> Optional[int]: return (self.ndvi() + 0.5) ** (1 / 2) def _snake_case ( self )-> str: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
75
0
from math import pi def __UpperCamelCase ( _A : int , _A : int ) ->float: """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
from __future__ import annotations def __UpperCamelCase ( _A : str ) ->list[int]: """simple docstring""" return [ord(_A ) - 96 for elem in plain] def __UpperCamelCase ( _A : list[int] ) ->str: """simple docstring""" return "".join(chr(elem + 96 ) for elem in encoded ) def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =encode(input("""-> """ ).strip().lower() ) print("""Encoded: """ , _A ) print("""Decoded:""" , decode(_A ) ) if __name__ == "__main__": main()
716
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def __UpperCamelCase ( _A : np.ndarray ) ->np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.mean(1 ) # Centralize the data of class i lowerCamelCase_ =data - column_reshape(_A ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_A , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =np.dot(_A , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =features.mean(1 ) lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.shape[1] lowerCamelCase_ =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" # Check if the features have been loaded if features.any(): lowerCamelCase_ =features.mean(1 ) # Center the dataset lowerCamelCase_ =features - np.reshape(_A , (data_mean.size, 1) ) lowerCamelCase_ =np.dot(_A , centered_data.T ) / features.shape[1] lowerCamelCase_ , lowerCamelCase_ =np.linalg.eigh(_A ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCamelCase_ =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCamelCase_ =np.dot(filtered_eigenvectors.T , _A ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: lowerCamelCase_ , lowerCamelCase_ =eigh( covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , ) lowerCamelCase_ =eigenvectors[:, ::-1][:, :dimensions] lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =np.linalg.svd(_A ) lowerCamelCase_ =svd_matrix[:, 0:dimensions] lowerCamelCase_ =np.dot(filtered_svd_matrix.T , _A ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" # Create dummy dataset with 2 classes and 3 features lowerCamelCase_ =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCamelCase_ =np.array([0, 0, 0, 1, 1] ) lowerCamelCase_ =2 lowerCamelCase_ =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_A ) as error_info: lowerCamelCase_ =linear_discriminant_analysis( _A , _A , _A , _A ) if isinstance(_A , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCamelCase_ =2 lowerCamelCase_ =np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_A ) as error_info: lowerCamelCase_ =principal_component_analysis(_A , _A ) if not np.allclose(_A , _A ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
75
0
'''simple docstring''' import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =num_stages lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =out_features lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =num_stages def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self )-> Union[str, Any]: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_SCREAMING_SNAKE_CASE , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_SCREAMING_SNAKE_CASE , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCamelCase:Any = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Dict = False _UpperCamelCase:int = False _UpperCamelCase:Any = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> int: lowerCamelCase_ =UperNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( 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 _snake_case ( self )-> Tuple: return def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _snake_case ( self )-> List[Any]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> str: pass def _snake_case ( self )-> Optional[int]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =_config_zero_init(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =_config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ =model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _snake_case ( self )-> Dict: pass @slow def _snake_case ( self )-> Tuple: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Tuple: """simple docstring""" lowerCamelCase_ =hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) lowerCamelCase_ =Image.open(_A ).convert("""RGB""" ) return image @require_torch @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def _snake_case ( self )-> int: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
717
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
75
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[Any] = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = "timm_backbone" def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone lowerCamelCase_ =num_channels lowerCamelCase_ =features_only lowerCamelCase_ =use_pretrained_backbone lowerCamelCase_ =True lowerCamelCase_ =out_indices if out_indices is not None else (-1,)
718
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
0
import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __UpperCamelCase ( _A : List[Any] , _A : Optional[int] , _A : Dict ) ->Optional[Any]: """simple docstring""" # Construct model if gpta_config_file == "": lowerCamelCase_ =GPTaConfig() else: lowerCamelCase_ =GPTaConfig.from_json_file(_A ) lowerCamelCase_ =GPTaModel(_A ) # Load weights from numpy load_tf_weights_in_gpta(_A , _A , _A ) # Save pytorch-model lowerCamelCase_ =pytorch_dump_folder_path + """/""" + WEIGHTS_NAME lowerCamelCase_ =pytorch_dump_folder_path + """/""" + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , _A ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(_A , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __A : int = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
719
from collections import namedtuple import requests from lxml import html # type: ignore __A : Dict = namedtuple('covid_data', 'cases deaths recovered') def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data: """simple docstring""" lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) ) __A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
75
0
'''simple docstring''' import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer __A : int = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:str = "AutoTokenizer" _UpperCamelCase:Union[str, Any] = ["tokenizer"] _UpperCamelCase:Optional[int] = { "semantic_prompt": 1, "coarse_prompt": 2, "fine_prompt": 2, } def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> Optional[Any]: super().__init__(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =speaker_embeddings @classmethod def _snake_case ( cls , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="speaker_embeddings_path.json" , **_SCREAMING_SNAKE_CASE )-> Tuple: if speaker_embeddings_dict_path is not None: lowerCamelCase_ =get_file_from_repo( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , subfolder=kwargs.pop("""subfolder""" , _SCREAMING_SNAKE_CASE ) , cache_dir=kwargs.pop("""cache_dir""" , _SCREAMING_SNAKE_CASE ) , force_download=kwargs.pop("""force_download""" , _SCREAMING_SNAKE_CASE ) , proxies=kwargs.pop("""proxies""" , _SCREAMING_SNAKE_CASE ) , resume_download=kwargs.pop("""resume_download""" , _SCREAMING_SNAKE_CASE ) , local_files_only=kwargs.pop("""local_files_only""" , _SCREAMING_SNAKE_CASE ) , use_auth_token=kwargs.pop("""use_auth_token""" , _SCREAMING_SNAKE_CASE ) , revision=kwargs.pop("""revision""" , _SCREAMING_SNAKE_CASE ) , ) if speaker_embeddings_path is None: logger.warning( f'`{os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}` does not exists\n , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.' ) lowerCamelCase_ =None else: with open(_SCREAMING_SNAKE_CASE ) as speaker_embeddings_json: lowerCamelCase_ =json.load(_SCREAMING_SNAKE_CASE ) else: lowerCamelCase_ =None lowerCamelCase_ =AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return cls(tokenizer=_SCREAMING_SNAKE_CASE , speaker_embeddings=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="speaker_embeddings_path.json" , _SCREAMING_SNAKE_CASE="speaker_embeddings" , _SCREAMING_SNAKE_CASE = False , **_SCREAMING_SNAKE_CASE , )-> int: if self.speaker_embeddings is not None: os.makedirs(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """v2""" ) , exist_ok=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={} lowerCamelCase_ =save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": lowerCamelCase_ =self._load_voice_preset(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict["""repo_or_path"""] , _SCREAMING_SNAKE_CASE , f'{prompt_key}_{key}' ) , voice_preset[key] , allow_pickle=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =os.path.join(_SCREAMING_SNAKE_CASE , f'{prompt_key}_{key}.npy' ) lowerCamelCase_ =tmp_dict with open(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , """w""" ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) super().save_pretrained(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =self.speaker_embeddings[voice_preset] lowerCamelCase_ ={} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( f'Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].' ) lowerCamelCase_ =get_file_from_repo( self.speaker_embeddings.get("""repo_or_path""" , """/""" ) , voice_preset_paths[key] , subfolder=kwargs.pop("""subfolder""" , _SCREAMING_SNAKE_CASE ) , cache_dir=kwargs.pop("""cache_dir""" , _SCREAMING_SNAKE_CASE ) , force_download=kwargs.pop("""force_download""" , _SCREAMING_SNAKE_CASE ) , proxies=kwargs.pop("""proxies""" , _SCREAMING_SNAKE_CASE ) , resume_download=kwargs.pop("""resume_download""" , _SCREAMING_SNAKE_CASE ) , local_files_only=kwargs.pop("""local_files_only""" , _SCREAMING_SNAKE_CASE ) , use_auth_token=kwargs.pop("""use_auth_token""" , _SCREAMING_SNAKE_CASE ) , revision=kwargs.pop("""revision""" , _SCREAMING_SNAKE_CASE ) , ) if path is None: raise ValueError( f'`{os.path.join(self.speaker_embeddings.get("repo_or_path" , "/" ) , voice_preset_paths[key] )}` does not exists\n , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n embeddings.' ) lowerCamelCase_ =np.load(_SCREAMING_SNAKE_CASE ) return voice_preset_dict def _snake_case ( self , _SCREAMING_SNAKE_CASE = None )-> List[Any]: for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(f'Voice preset unrecognized, missing {key} as a key.' ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(f'{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.' ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(f'{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.' ) def __call__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="pt" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , )-> Tuple: if voice_preset is not None and not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if ( isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): lowerCamelCase_ =self._load_voice_preset(_SCREAMING_SNAKE_CASE ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and not voice_preset.endswith(""".npz""" ): lowerCamelCase_ =voice_preset + """.npz""" lowerCamelCase_ =np.load(_SCREAMING_SNAKE_CASE ) if voice_preset is not None: self._validate_voice_preset_dict(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.tokenizer( _SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , return_token_type_ids=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) if voice_preset is not None: lowerCamelCase_ =voice_preset return encoded_text
720
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __UpperCamelCase ( _A : str , _A : Optional[Any] , _A : Any ) ->List[str]: """simple docstring""" lowerCamelCase_ =BertConfig.from_json_file(_A ) print(f'Building PyTorch model from configuration: {config}' ) lowerCamelCase_ =BertForPreTraining(_A ) # Load weights from tf checkpoint load_tf_weights_in_bert(_A , _A , _A ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , _A ) if __name__ == "__main__": __A : Tuple = 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( '--bert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __A : Optional[int] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
721
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
75
0
def __UpperCamelCase ( _A : list ) ->list: """simple docstring""" if len(_A ) <= 1: return [tuple(_A )] lowerCamelCase_ =[] def generate(_A : int , _A : list ): lowerCamelCase_ =[0] * n res.append(tuple(_A ) ) lowerCamelCase_ =0 while i < n: if c[i] < i: if i % 2 == 0: lowerCamelCase_ , lowerCamelCase_ =arr[i], arr[0] else: lowerCamelCase_ , lowerCamelCase_ =arr[i], arr[c[i]] res.append(tuple(_A ) ) c[i] += 1 lowerCamelCase_ =0 else: lowerCamelCase_ =0 i += 1 generate(len(_A ) , _A ) return res if __name__ == "__main__": __A : str = input('Enter numbers separated by a comma:\n').strip() __A : Optional[Any] = [int(item) for item in user_input.split(',')] print(heaps(arr))
700
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "deta" _UpperCamelCase:int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , **_SCREAMING_SNAKE_CASE , )-> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase_ =CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =backbone_config.pop("""model_type""" ) lowerCamelCase_ =CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ =config_class.from_dict(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone_config lowerCamelCase_ =num_queries lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =d_model lowerCamelCase_ =encoder_ffn_dim lowerCamelCase_ =encoder_layers lowerCamelCase_ =encoder_attention_heads lowerCamelCase_ =decoder_ffn_dim lowerCamelCase_ =decoder_layers lowerCamelCase_ =decoder_attention_heads lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =activation_dropout lowerCamelCase_ =activation_function lowerCamelCase_ =init_std lowerCamelCase_ =init_xavier_std lowerCamelCase_ =encoder_layerdrop lowerCamelCase_ =auxiliary_loss lowerCamelCase_ =position_embedding_type # deformable attributes lowerCamelCase_ =num_feature_levels lowerCamelCase_ =encoder_n_points lowerCamelCase_ =decoder_n_points lowerCamelCase_ =two_stage lowerCamelCase_ =two_stage_num_proposals lowerCamelCase_ =with_box_refine lowerCamelCase_ =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =mask_loss_coefficient lowerCamelCase_ =dice_loss_coefficient lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient lowerCamelCase_ =focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> int: return self.encoder_attention_heads @property def _snake_case ( self )-> int: return self.d_model def _snake_case ( self )-> str: lowerCamelCase_ =copy.deepcopy(self.__dict__ ) lowerCamelCase_ =self.backbone_config.to_dict() lowerCamelCase_ =self.__class__.model_type return output
75
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Dict = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : str = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
701
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __A : int = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Any = "albert" def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =vocab_size lowerCamelCase_ =embedding_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_hidden_groups lowerCamelCase_ =num_attention_heads lowerCamelCase_ =inner_group_num lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =position_embedding_type class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
75
0
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A : int = logging.get_logger(__name__) __A : str = [ ['attention', 'attn'], ['encoder_attention', 'encoder_attn'], ['q_lin', 'q_proj'], ['k_lin', 'k_proj'], ['v_lin', 'v_proj'], ['out_lin', 'out_proj'], ['norm_embeddings', 'layernorm_embedding'], ['position_embeddings', 'embed_positions'], ['embeddings', 'embed_tokens'], ['ffn.lin', 'fc'], ] def __UpperCamelCase ( _A : int ) ->Optional[Any]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: lowerCamelCase_ =k.replace(_A , _A ) if k.startswith("""encoder""" ): lowerCamelCase_ =k.replace(""".attn""" , """.self_attn""" ) lowerCamelCase_ =k.replace("""norm1""" , """self_attn_layer_norm""" ) lowerCamelCase_ =k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): lowerCamelCase_ =k.replace("""norm1""" , """self_attn_layer_norm""" ) lowerCamelCase_ =k.replace("""norm2""" , """encoder_attn_layer_norm""" ) lowerCamelCase_ =k.replace("""norm3""" , """final_layer_norm""" ) return k def __UpperCamelCase ( _A : Optional[int] ) ->int: """simple docstring""" lowerCamelCase_ =[ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: lowerCamelCase_ =sd.pop(_A ) lowerCamelCase_ =k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd lowerCamelCase_ =v __A : Optional[int] = ['START'] @torch.no_grad() def __UpperCamelCase ( _A : Optional[int] , _A : int , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ =torch.load(_A , map_location="""cpu""" ) lowerCamelCase_ =model["""model"""] lowerCamelCase_ =BlenderbotConfig.from_json_file(_A ) lowerCamelCase_ =BlenderbotForConditionalGeneration(_A ) lowerCamelCase_ =m.model.state_dict().keys() lowerCamelCase_ =[] lowerCamelCase_ ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue lowerCamelCase_ =rename_state_dict_key(_A ) if new_k not in valid_keys: failures.append([k, new_k] ) else: lowerCamelCase_ =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(_A ) m.model.load_state_dict(_A , strict=_A ) m.half() m.save_pretrained(_A ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() # Required parameters parser.add_argument('--src_path', type=str, help='like blenderbot-model.bin') parser.add_argument('--save_dir', default='hf_blenderbot', type=str, help='Where to save converted model.') parser.add_argument( '--hf_config_json', default='blenderbot-3b-config.json', type=str, help='Path to config to use' ) __A : Dict = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
702
from collections import deque from math import floor from random import random from time import time class _SCREAMING_SNAKE_CASE : def __init__( self )-> List[str]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[Any]: if self.graph.get(_SCREAMING_SNAKE_CASE ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase_ =[[w, v]] if not self.graph.get(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[] def _snake_case ( self )-> str: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> Optional[Any]: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Any: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return len(self.graph[u] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Union[str, Any]: lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =[] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return sorted_nodes def _snake_case ( self )-> str: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> List[str]: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin class _SCREAMING_SNAKE_CASE : def __init__( self )-> Optional[Any]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[str]: # check if the u exists if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase_ =[[w, v]] # add the other way if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase_ =[[w, u]] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) # the other way round if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> int: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return len(self.graph[u] ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self )-> Optional[Any]: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> str: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Dict: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin
75
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[str] = ["image_processor", "tokenizer"] _UpperCamelCase:int = "ViTImageProcessor" _UpperCamelCase:Union[str, Any] = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> Dict: lowerCamelCase_ =None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =kwargs.pop("""feature_extractor""" ) lowerCamelCase_ =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__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> str: if text is None and visual_prompt is None and images is None: raise ValueError("""You have to specify either text, visual prompt or images.""" ) if text is not None and visual_prompt is not None: raise ValueError("""You have to specify exactly one type of prompt. Either text or visual prompt.""" ) if text is not None: lowerCamelCase_ =self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if visual_prompt is not None: lowerCamelCase_ =self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if images is not None: lowerCamelCase_ =self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if visual_prompt is not None and images is not None: lowerCamelCase_ ={ """pixel_values""": image_features.pixel_values, """conditional_pixel_values""": prompt_features.pixel_values, } return encoding elif text is not None and images is not None: lowerCamelCase_ =image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: lowerCamelCase_ ={ """conditional_pixel_values""": prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**_SCREAMING_SNAKE_CASE ) , tensor_type=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Dict: return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Tuple: warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def _snake_case ( self )-> Any: warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , _SCREAMING_SNAKE_CASE , ) return self.image_processor
703
import os from datetime import datetime as dt from github import Github __A : Optional[int] = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase_ =g.get_repo("""huggingface/diffusers""" ) lowerCamelCase_ =repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase_ =sorted(issue.get_comments() , key=lambda _A : i.created_at , reverse=_A ) lowerCamelCase_ =comments[0] if len(_A ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
75
0
import random from typing import Any def SCREAMING_SNAKE_CASE_ ( _A : list ) ->list[Any]: """simple docstring""" for _ in range(len(_A ) ): lowerCamelCase_ =random.randint(0 , len(_A ) - 1 ) lowerCamelCase_ =random.randint(0 , len(_A ) - 1 ) lowerCamelCase_ , lowerCamelCase_ =data[b], data[a] return data if __name__ == "__main__": __A : Optional[Any] = [0, 1, 2, 3, 4, 5, 6, 7] __A : List[Any] = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
704
import argparse import os import re __A : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. __A : int = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. __A : int = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Optional[Any] = re.compile(R'\[([^\]]+)\]') def __UpperCamelCase ( _A : int ) ->Dict: """simple docstring""" lowerCamelCase_ =_re_indent.search(_A ) return "" if search is None else search.groups()[0] def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 lowerCamelCase_ =["""\n""".join(lines[:index] )] else: lowerCamelCase_ =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ =[lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_A ) ) if index < len(_A ) - 1: lowerCamelCase_ =[lines[index + 1]] index += 1 else: lowerCamelCase_ =[] else: blocks.append("""\n""".join(_A ) ) lowerCamelCase_ =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append("""\n""".join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def __UpperCamelCase ( _A : Optional[int] ) ->Optional[int]: """simple docstring""" def _inner(_A : Optional[Any] ): return key(_A ).lower().replace("""_""" , """""" ) return _inner def __UpperCamelCase ( _A : int , _A : List[Any]=None ) ->List[str]: """simple docstring""" # If no key is provided, we use a noop. def noop(_A : List[str] ): return x if key is None: lowerCamelCase_ =noop # Constants are all uppercase, they go first. lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()] lowerCamelCase_ =ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def __UpperCamelCase ( _A : List[str] ) ->List[str]: """simple docstring""" # This inner function sort imports between [ ]. def _replace(_A : Optional[Any] ): lowerCamelCase_ =match.groups()[0] if "," not in imports: return f'[{imports}]' lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" lowerCamelCase_ =import_statement.split("""\n""" ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase_ =2 if lines[1].strip() == """[""" else 1 lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] ) lowerCamelCase_ =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase_ =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] lowerCamelCase_ =get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase_ =_re_bracket_content.sub(_replace , _A ) return import_statement def __UpperCamelCase ( _A : List[Any] , _A : Optional[Any]=True ) ->str: """simple docstring""" with open(_A , """r""" ) as f: lowerCamelCase_ =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ =split_code_in_indented_blocks( _A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ =main_blocks[block_idx] lowerCamelCase_ =block.split("""\n""" ) # Get to the start of the imports. lowerCamelCase_ =0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase_ =len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] ) lowerCamelCase_ =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ =_re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase_ =[(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase_ =[(i, key) for i, key in enumerate(_A ) if key is not None] lowerCamelCase_ =[x[0] for x in sorted(_A , key=lambda _A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase_ =0 lowerCamelCase_ =[] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , """w""" ) as f: f.write("""\n""".join(_A ) ) def __UpperCamelCase ( _A : str=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A ) if result: lowerCamelCase_ =[os.path.join(_A , """__init__.py""" )] if len(_A ) > 0: raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') __A : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
75
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) __A : int = { 'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'], 'processing_trocr': ['TrOCRProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ 'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrOCRForCausalLM', 'TrOCRPreTrainedModel', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys __A : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : str = {'vocab_file': 'sentencepiece.model'} __A : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } __A : int = { 'google/rembert': 2_56, } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> Dict: return len(self.sp_model ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self )-> Optional[Any]: lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =d lowerCamelCase_ =spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return lowerCamelCase_ =os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
75
0
from collections.abc import Callable import numpy as np def __UpperCamelCase ( _A : Callable , _A : float , _A : float , _A : float , _A : float ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =int(np.ceil((x_end - xa) / step_size ) ) lowerCamelCase_ =np.zeros((n + 1,) ) lowerCamelCase_ =ya lowerCamelCase_ =xa for k in range(_A ): lowerCamelCase_ =y[k] + step_size * ode_func(_A , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
75
0
import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=[30, 30] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _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.0_2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=10 , )-> List[Any]: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =n_targets lowerCamelCase_ =num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens lowerCamelCase_ =(image_size[1] // patch_size) * (image_size[0] // patch_size) lowerCamelCase_ =num_patches + 1 + self.num_detection_tokens def _snake_case ( self )-> Any: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) lowerCamelCase_ =None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) lowerCamelCase_ =[] for i in range(self.batch_size ): lowerCamelCase_ ={} lowerCamelCase_ =torch.randint( high=self.num_labels , size=(self.n_targets,) , device=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.rand(self.n_targets , 4 , device=_SCREAMING_SNAKE_CASE ) labels.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return YolosConfig( 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 , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =YolosModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =YolosForObjectDetection(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(pixel_values=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) lowerCamelCase_ =model(pixel_values=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =self.prepare_config_and_inputs() lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Dict = (YolosModel, YolosForObjectDetection) if is_torch_available() else () _UpperCamelCase:List[str] = ( {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {} ) _UpperCamelCase:List[str] = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:int = False _UpperCamelCase:Optional[int] = False def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Any: lowerCamelCase_ =super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": lowerCamelCase_ =[] for i in range(self.model_tester.batch_size ): lowerCamelCase_ ={} lowerCamelCase_ =torch.ones( size=(self.model_tester.n_targets,) , device=_SCREAMING_SNAKE_CASE , dtype=torch.long ) lowerCamelCase_ =torch.ones( self.model_tester.n_targets , 4 , device=_SCREAMING_SNAKE_CASE , dtype=torch.float ) labels.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =labels return inputs_dict def _snake_case ( self )-> List[str]: lowerCamelCase_ =YolosModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self )-> int: self.config_tester.run_common_tests() def _snake_case ( self )-> Any: # YOLOS does not use inputs_embeds pass def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase_ =model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =True # in YOLOS, the seq_len is different lowerCamelCase_ =self.model_tester.expected_seq_len for model_class in self.all_model_classes: lowerCamelCase_ =True lowerCamelCase_ =False lowerCamelCase_ =True lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCamelCase_ =True lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine lowerCamelCase_ =True lowerCamelCase_ =True lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =1 self.assertEqual(out_len + added_hidden_states , len(_SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def _snake_case ( self )-> str: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.hidden_states lowerCamelCase_ =getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # YOLOS has a different seq_length lowerCamelCase_ =self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> str: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*_SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )-> List[str]: for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =YolosModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->List[Any]: """simple docstring""" lowerCamelCase_ =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @cached_property def _snake_case ( self )-> int: return AutoImageProcessor.from_pretrained("""hustvl/yolos-small""" ) if is_vision_available() else None @slow def _snake_case ( self )-> Any: lowerCamelCase_ =YolosForObjectDetection.from_pretrained("""hustvl/yolos-small""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.default_image_processor lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowerCamelCase_ =model(inputs.pixel_values ) # verify outputs lowerCamelCase_ =torch.Size((1, 100, 92) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] , device=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =torch.tensor( [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]] , device=_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify postprocessing lowerCamelCase_ =image_processor.post_process_object_detection( _SCREAMING_SNAKE_CASE , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] lowerCamelCase_ =torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1] ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =[75, 75, 17, 63, 17] lowerCamelCase_ =torch.tensor([335.0609, 79.3848, 375.4216, 187.2495] ).to(_SCREAMING_SNAKE_CASE ) self.assertEqual(len(results["""scores"""] ) , 5 ) self.assertTrue(torch.allclose(results["""scores"""] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) self.assertSequenceEqual(results["""labels"""].tolist() , _SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(results["""boxes"""][0, :] , _SCREAMING_SNAKE_CASE ) )
707
# 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.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input __A : List[str] = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def __UpperCamelCase ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =_ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase_ =get_sagemaker_input() else: lowerCamelCase_ =get_cluster_input() return config def __UpperCamelCase ( _A : List[str]=None ) ->str: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""config""" , description=_A ) else: lowerCamelCase_ =argparse.ArgumentParser("""Accelerate config command""" , description=_A ) parser.add_argument( """--config_file""" , default=_A , 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=_A ) return parser def __UpperCamelCase ( _A : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =get_user_input() if args.config_file is not None: lowerCamelCase_ =args.config_file else: if not os.path.isdir(_A ): os.makedirs(_A ) lowerCamelCase_ =default_yaml_config_file if config_file.endswith(""".json""" ): config.to_json_file(_A ) else: config.to_yaml_file(_A ) print(f'accelerate configuration saved at {config_file}' ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =config_command_parser() lowerCamelCase_ =parser.parse_args() config_command(_A ) if __name__ == "__main__": main()
75
0
'''simple docstring''' 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 ( lowerCAmelCase__): _UpperCamelCase:Union[List[PIL.Image.Image], np.ndarray] _UpperCamelCase:Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:np.ndarray _UpperCamelCase:List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
708
def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[[] for _ in range(_A )] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_A ) <= key: return input_string for position, character in enumerate(_A ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_A ) lowerCamelCase_ =["""""".join(_A ) for row in temp_grid] lowerCamelCase_ ="""""".join(_A ) return output_string def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string lowerCamelCase_ =[[] for _ in range(_A )] # generates template for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) lowerCamelCase_ =0 for row in temp_grid: # fills in the characters lowerCamelCase_ =input_string[counter : counter + len(_A )] grid.append(list(_A ) ) counter += len(_A ) lowerCamelCase_ ="""""" # reads as zigzag for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __UpperCamelCase ( _A : str ) ->dict[int, str]: """simple docstring""" lowerCamelCase_ ={} for key_guess in range(1 , len(_A ) ): # tries every key lowerCamelCase_ =decrypt(_A , _A ) return results if __name__ == "__main__": import doctest doctest.testmod()
75
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowercase ( _A : Any=None ) ->int: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""test""" ) else: lowerCamelCase_ =argparse.ArgumentParser("""Accelerate test command""" ) parser.add_argument( """--config_file""" , default=_A , 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=_A ) return parser def __lowercase ( _A : Any ) ->List[str]: """simple docstring""" lowerCamelCase_ =os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["""test_utils""", """scripts""", """test_script.py"""] ) if args.config_file is None: lowerCamelCase_ =script_name else: lowerCamelCase_ =f'--config_file={args.config_file} {script_name}' lowerCamelCase_ =["""accelerate-launch"""] + test_args.split() lowerCamelCase_ =execute_subprocess_async(_A , env=os.environ.copy() ) if result.returncode == 0: print("""Test is a success! You are ready for your distributed training!""" ) def __lowercase ( ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =test_command_parser() lowerCamelCase_ =parser.parse_args() test_command(_A ) if __name__ == "__main__": main()
709
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =data lowerCamelCase_ =None class _SCREAMING_SNAKE_CASE : def __init__( self )-> Any: lowerCamelCase_ =None def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.head while temp is not None: print(temp.data , end=""" """ ) lowerCamelCase_ =temp.next print() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =Node(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =self.head lowerCamelCase_ =new_node def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if node_data_a == node_data_a: return else: lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next lowerCamelCase_ =self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ =node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ =node_a.data, node_a.data if __name__ == "__main__": __A : Optional[int] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
75
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
710
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Dict = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "yolos" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=[512, 864] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , )-> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =qkv_bias lowerCamelCase_ =num_detection_tokens lowerCamelCase_ =use_mid_position_embeddings lowerCamelCase_ =auxiliary_loss # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = version.parse("1.11") @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self )-> float: return 1E-4 @property def _snake_case ( self )-> int: return 12
75
0
def __UpperCamelCase ( _A : int = 1000 ) ->int: """simple docstring""" return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
711
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py __A : List[Any] = 'src/transformers' __A : Tuple = 'docs/source/en' __A : Optional[int] = '.' def __UpperCamelCase ( _A : Tuple , _A : Tuple , _A : Optional[Any] ) ->Optional[Any]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | __A : Dict = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. __A : Optional[int] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Optional[int] = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : str = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. __A : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def __UpperCamelCase ( _A : List[Any] ) ->str: """simple docstring""" lowerCamelCase_ =re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _A ) return [m.group(0 ) for m in matches] def __UpperCamelCase ( _A : Union[str, Any] , _A : List[str] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =2 if text == """✅""" or text == """❌""" else len(_A ) lowerCamelCase_ =(width - text_length) // 2 lowerCamelCase_ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCamelCase_ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCamelCase_ ={name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) lowerCamelCase_ =collections.defaultdict(_A ) # Let's lookup through all transformers object (once). for attr_name in dir(_A ): lowerCamelCase_ =None if attr_name.endswith("""Tokenizer""" ): lowerCamelCase_ =slow_tokenizers lowerCamelCase_ =attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): lowerCamelCase_ =fast_tokenizers lowerCamelCase_ =attr_name[:-13] elif _re_tf_models.match(_A ) is not None: lowerCamelCase_ =tf_models lowerCamelCase_ =_re_tf_models.match(_A ).groups()[0] elif _re_flax_models.match(_A ) is not None: lowerCamelCase_ =flax_models lowerCamelCase_ =_re_flax_models.match(_A ).groups()[0] elif _re_pt_models.match(_A ) is not None: lowerCamelCase_ =pt_models lowerCamelCase_ =_re_pt_models.match(_A ).groups()[0] if lookup_dict is not None: while len(_A ) > 0: if attr_name in model_name_to_prefix.values(): lowerCamelCase_ =True break # Try again after removing the last word in the name lowerCamelCase_ ="""""".join(camel_case_split(_A )[:-1] ) # Let's build that table! lowerCamelCase_ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCamelCase_ =["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). lowerCamelCase_ =[len(_A ) + 2 for c in columns] lowerCamelCase_ =max([len(_A ) for name in model_names] ) + 2 # Build the table per se lowerCamelCase_ ="""|""" + """|""".join([_center_text(_A , _A ) for c, w in zip(_A , _A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" lowerCamelCase_ ={True: """✅""", False: """❌"""} for name in model_names: lowerCamelCase_ =model_name_to_prefix[name] lowerCamelCase_ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_A , _A ) for l, w in zip(_A , _A )] ) + "|\n" return table def __UpperCamelCase ( _A : str=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) lowerCamelCase_ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
75
0
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def __UpperCamelCase ( _A : int ) ->Optional[Any]: """simple docstring""" if isinstance(_A , collections.abc.Iterable ): return x return (x, x) @require_flax class _SCREAMING_SNAKE_CASE : def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: pass def _snake_case ( self )-> Optional[int]: pass def _snake_case ( self )-> List[Any]: pass def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Any: lowerCamelCase_ =np.abs((a - b) ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , f'Difference between torch and flax is {diff} (>= {tol}).' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], config.projection_dim) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ , lowerCamelCase_ =self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""vision_model""": vision_model, """text_model""": text_model} lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> List[str]: lowerCamelCase_ , lowerCamelCase_ =self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""vision_model""": vision_model, """text_model""": text_model} lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =after_output[0] lowerCamelCase_ =np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ , lowerCamelCase_ =self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""vision_model""": vision_model, """text_model""": text_model} lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model( input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =output.vision_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCamelCase_ =to_atuple(vision_model.config.image_size ) lowerCamelCase_ =to_atuple(vision_model.config.patch_size ) lowerCamelCase_ =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowerCamelCase_ =num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowerCamelCase_ =output.text_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Any: pt_model.to(_SCREAMING_SNAKE_CASE ) pt_model.eval() # prepare inputs lowerCamelCase_ =inputs_dict lowerCamelCase_ ={k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): lowerCamelCase_ =pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() lowerCamelCase_ =fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =VisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) pt_model_loaded.to(_SCREAMING_SNAKE_CASE ) pt_model_loaded.eval() with torch.no_grad(): lowerCamelCase_ =pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output_loaded.numpy() , 4E-2 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =fx_state self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =self.prepare_config_and_inputs() self.check_save_load(**_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def _snake_case ( self )-> Dict: lowerCamelCase_ =self.prepare_config_and_inputs() lowerCamelCase_ =config_inputs_dict.pop("""vision_config""" ) lowerCamelCase_ =config_inputs_dict.pop("""text_config""" ) lowerCamelCase_ =config_inputs_dict self.check_equivalence_pt_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.check_equivalence_flax_to_pt(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.get_pretrained_model_and_inputs() lowerCamelCase_ =model_a(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model_a(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =after_outputs[0] lowerCamelCase_ =np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-5 ) @require_flax class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , unittest.TestCase): def _snake_case ( self )-> Tuple: lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-vit""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =13 lowerCamelCase_ =floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) lowerCamelCase_ =ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) lowerCamelCase_ =random_attention_mask([batch_size, 4] ) lowerCamelCase_ ={"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =FlaxViTModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxBertModel(_SCREAMING_SNAKE_CASE ) return vision_model, text_model def _snake_case ( self )-> int: lowerCamelCase_ =FlaxViTModelTester(self ) lowerCamelCase_ =FlaxBertModelTester(self ) lowerCamelCase_ =vit_model_tester.prepare_config_and_inputs() lowerCamelCase_ =bert_model_tester.prepare_config_and_inputs() lowerCamelCase_ , lowerCamelCase_ =vision_config_and_inputs lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , unittest.TestCase): def _snake_case ( self )-> Tuple: lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-clip""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =13 lowerCamelCase_ =floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) lowerCamelCase_ =ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) lowerCamelCase_ =random_attention_mask([batch_size, 4] ) lowerCamelCase_ ={"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =FlaxCLIPVisionModel(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =FlaxBertModel(_SCREAMING_SNAKE_CASE ) return vision_model, text_model def _snake_case ( self )-> str: lowerCamelCase_ =FlaxCLIPVisionModelTester(self ) lowerCamelCase_ =FlaxBertModelTester(self ) lowerCamelCase_ =clip_model_tester.prepare_config_and_inputs() lowerCamelCase_ =bert_model_tester.prepare_config_and_inputs() lowerCamelCase_ , lowerCamelCase_ =vision_config_and_inputs lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @slow def _snake_case ( self )-> List[str]: lowerCamelCase_ =FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian""" , logit_scale_init_value=1.0 ) lowerCamelCase_ =VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian""" ) lowerCamelCase_ =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCamelCase_ =processor( text=["""una foto di un gatto""", """una foto di un cane"""] , images=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ) lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) lowerCamelCase_ =np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image , _SCREAMING_SNAKE_CASE , atol=1E-3 ) )
712
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Tuple: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =num_stages lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =out_features lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =num_stages def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =self.get_config() return config, pixel_values, labels def _snake_case ( self )-> List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self )-> Union[str, Any]: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_SCREAMING_SNAKE_CASE , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_SCREAMING_SNAKE_CASE , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self )-> str: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCamelCase:Any = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Dict = False _UpperCamelCase:int = False _UpperCamelCase:Any = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False def _snake_case ( self )-> int: lowerCamelCase_ =UperNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( 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 _snake_case ( self )-> Tuple: return def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""UperNet does not use inputs_embeds""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not support input and output embeddings""" ) def _snake_case ( self )-> str: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""UperNet does not have a base model""" ) def _snake_case ( self )-> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _snake_case ( self )-> List[Any]: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> str: pass def _snake_case ( self )-> Optional[int]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): lowerCamelCase_ =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =_config_zero_init(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =_config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ =model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason="""UperNet does not have tied weights""" ) def _snake_case ( self )-> Dict: pass @slow def _snake_case ( self )-> Tuple: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( ) ->Tuple: """simple docstring""" lowerCamelCase_ =hf_hub_download( repo_id="""hf-internal-testing/fixtures_ade20k""" , repo_type="""dataset""" , filename="""ADE_val_00000001.jpg""" ) lowerCamelCase_ =Image.open(_A ).convert("""RGB""" ) return image @require_torch @require_vision @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[Any]: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def _snake_case ( self )-> int: lowerCamelCase_ =AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""" ) lowerCamelCase_ =UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""" ).to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =prepare_img() lowerCamelCase_ =processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowerCamelCase_ =model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
75
0
from __future__ import annotations import math def __UpperCamelCase ( _A : int , _A : int , _A : bool , _A : list[int] , _A : float ) ->int: """simple docstring""" if depth < 0: raise ValueError("""Depth cannot be less than 0""" ) if not scores: raise ValueError("""Scores cannot be empty""" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , _A , _A , _A ) , minimax(depth + 1 , node_index * 2 + 1 , _A , _A , _A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , _A , _A , _A ) , minimax(depth + 1 , node_index * 2 + 1 , _A , _A , _A ) , ) ) def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =[90, 23, 6, 33, 21, 65, 123, 34423] lowerCamelCase_ =math.log(len(_A ) , 2 ) print(f'Optimal value : {minimax(0 , 0 , _A , _A , _A )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
713
from typing import Dict, Iterable, 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, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_MEAN , _SCREAMING_SNAKE_CASE = IMAGENET_DEFAULT_STD , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ =int((256 / 224) * size["""shortest_edge"""] ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""height""": output_size[0], """width""": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( _SCREAMING_SNAKE_CASE , size=(size_dict["""height"""], size_dict["""width"""]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> BatchFeature: 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_center_crop if do_center_crop is not None else self.do_center_crop 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_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_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.""" ) # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
75
0
def __UpperCamelCase ( _A : Optional[Any] , _A : str ) ->Optional[int]: """simple docstring""" lowerCamelCase_ ="""""" for i in table: res += inp[i - 1] return res def __UpperCamelCase ( _A : str ) ->int: """simple docstring""" return data[1:] + data[0] def __UpperCamelCase ( _A : Tuple , _A : int ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ ="""""" for i in range(len(_A ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def __UpperCamelCase ( _A : Union[str, Any] , _A : Optional[int] ) ->Tuple: """simple docstring""" lowerCamelCase_ =int("""0b""" + data[0] + data[-1] , 2 ) lowerCamelCase_ =int("""0b""" + data[1:3] , 2 ) return bin(s[row][col] )[2:] def __UpperCamelCase ( _A : str , _A : Optional[Any] , _A : Union[str, Any] , _A : Any , _A : Tuple ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =message[:4] lowerCamelCase_ =message[4:] lowerCamelCase_ =apply_table(_A , _A ) lowerCamelCase_ =xor(_A , _A ) lowerCamelCase_ =apply_sbox(_A , temp[:4] ) # noqa: E741 lowerCamelCase_ =apply_sbox(_A , temp[4:] ) lowerCamelCase_ ="""0""" * (2 - len(_A )) + l # noqa: E741 lowerCamelCase_ ="""0""" * (2 - len(_A )) + r lowerCamelCase_ =apply_table(l + r , _A ) lowerCamelCase_ =xor(_A , _A ) return temp + right if __name__ == "__main__": __A : List[str] = input('Enter 10 bit key: ') __A : Optional[Any] = input('Enter 8 bit message: ') __A : int = [6, 3, 7, 4, 8, 5, 10, 9] __A : Tuple = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] __A : Optional[int] = [2, 4, 3, 1] __A : Any = [2, 6, 3, 1, 4, 8, 5, 7] __A : Union[str, Any] = [4, 1, 3, 5, 7, 2, 8, 6] __A : Any = [4, 1, 2, 3, 2, 3, 4, 1] __A : List[str] = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] __A : Optional[Any] = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation __A : Dict = apply_table(key, paa_table) __A : List[str] = temp[:5] __A : Dict = temp[5:] __A : Tuple = left_shift(left) __A : List[str] = left_shift(right) __A : Union[str, Any] = apply_table(left + right, pa_table) __A : List[Any] = left_shift(left) __A : Dict = left_shift(right) __A : Tuple = left_shift(left) __A : Union[str, Any] = left_shift(right) __A : Optional[int] = apply_table(left + right, pa_table) # encryption __A : Optional[int] = apply_table(message, IP) __A : Dict = function(expansion, sa, sa, keya, temp) __A : Optional[int] = temp[4:] + temp[:4] __A : Tuple = function(expansion, sa, sa, keya, temp) __A : List[Any] = apply_table(temp, IP_inv) print('Cipher text is:', CT) # decryption __A : List[str] = apply_table(CT, IP) __A : int = function(expansion, sa, sa, keya, temp) __A : Dict = temp[4:] + temp[:4] __A : Optional[Any] = function(expansion, sa, sa, keya, temp) __A : Dict = apply_table(temp, IP_inv) print('Plain text after decypting is:', PT)
714
# Imports import numpy as np class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Any: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: if red is not None: lowerCamelCase_ =red if green is not None: lowerCamelCase_ =green if blue is not None: lowerCamelCase_ =blue if red_edge is not None: lowerCamelCase_ =red_edge if nir is not None: lowerCamelCase_ =nir return True def _snake_case ( self , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: self.set_matricies(red=_SCREAMING_SNAKE_CASE , green=_SCREAMING_SNAKE_CASE , blue=_SCREAMING_SNAKE_CASE , red_edge=_SCREAMING_SNAKE_CASE , nir=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={ """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def _snake_case ( self )-> Optional[Any]: return -0.1_8 + (1.1_7 * ((self.nir - self.red) / (self.nir + self.red))) def _snake_case ( self )-> Tuple: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _snake_case ( self )-> str: return self.nir * (self.red / (self.green**2)) def _snake_case ( self )-> Optional[int]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _snake_case ( self )-> Tuple: return (self.nir - self.red) / (self.nir + self.red) def _snake_case ( self )-> Dict: return (self.nir - self.blue) / (self.nir + self.blue) def _snake_case ( self )-> List[Any]: return (self.redEdge - self.red) / (self.redEdge + self.red) def _snake_case ( self )-> Tuple: return (self.nir - self.green) / (self.nir + self.green) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _snake_case ( self )-> List[str]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _snake_case ( self )-> Optional[int]: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.0_8 , _SCREAMING_SNAKE_CASE=1.2_2 , _SCREAMING_SNAKE_CASE=0.0_3 )-> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _snake_case ( self )-> Tuple: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _snake_case ( self )-> Any: return (self.nir / self.green) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.nir / self.redEdge) - 1 def _snake_case ( self )-> Union[str, Any]: return (self.red - self.blue) / self.red def _snake_case ( self )-> Dict: lowerCamelCase_ =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _snake_case ( self )-> int: return self.nir - self.green def _snake_case ( self )-> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.2_5 * n) - (self.red - 0.1_2_5) / (1 - self.red) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.1_6 )-> List[Any]: return (self.nir - self.green) / (self.nir + self.green + y) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0.5 )-> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _snake_case ( self )-> int: return np.arctan( ((2 * self.red - self.green - self.blue) / 3_0.5) * (self.green - self.blue) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> Union[str, Any]: return (self.nir - b) / (a * self.red) def _snake_case ( self )-> int: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _snake_case ( self )-> Optional[Any]: return (self.red + self.green + self.blue) / 3_0.5 def _snake_case ( self )-> List[str]: return self.nir / self.red def _snake_case ( self )-> List[str]: return (self.rvi() - 1) / (self.rvi() + 1) def _snake_case ( self )-> str: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _snake_case ( self )-> List[Any]: return self.green / (self.nir + self.red + self.green) def _snake_case ( self )-> Dict: return self.nir / (self.nir + self.red + self.green) def _snake_case ( self )-> List[str]: return self.red / (self.nir + self.red + self.green) def _snake_case ( self )-> int: return (self.green - self.red) / (self.green + self.red) def _snake_case ( self )-> str: return (self.red - self.green) / (self.red + self.green) def _snake_case ( self )-> str: lowerCamelCase_ =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCamelCase_ =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _snake_case ( self )-> List[str]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _snake_case ( self )-> List[Any]: return self.nir / self.red def _snake_case ( self )-> Optional[int]: return (self.ndvi() + 0.5) ** (1 / 2) def _snake_case ( self )-> str: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
75
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. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Optional[Any] = "dandelin/vilt-b32-finetuned-vqa" _UpperCamelCase:Union[str, Any] = ( "This is a tool that answers a question about an image. It takes an input named `image` which should be the " "image containing the information, as well as a `question` which should be the question in English. It " "returns a text that is the answer to the question." ) _UpperCamelCase:int = "image_qa" _UpperCamelCase:Dict = AutoProcessor _UpperCamelCase:List[str] = AutoModelForVisualQuestionAnswering _UpperCamelCase:Optional[int] = ["image", "text"] _UpperCamelCase:Dict = ["text"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: requires_backends(self , ["""vision"""] ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: return self.pre_processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> str: with torch.no_grad(): return self.model(**_SCREAMING_SNAKE_CASE ).logits def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
715
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[int] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_12, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __UpperCamelCase ( _A : int ) ->Optional[int]: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(f'could not parse string as bool {string}' ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) __A : List[Any] = parser.parse_args() __A : str = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
716
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def __UpperCamelCase ( _A : np.ndarray ) ->np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.mean(1 ) # Centralize the data of class i lowerCamelCase_ =data - column_reshape(_A ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_A , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =np.dot(_A , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" lowerCamelCase_ =features.mean(1 ) lowerCamelCase_ =np.nan for i in range(_A ): lowerCamelCase_ =features[:, labels == i] lowerCamelCase_ =data.shape[1] lowerCamelCase_ =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCamelCase_ =device_data * np.dot( column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( _A : np.ndarray , _A : int ) ->np.ndarray: """simple docstring""" # Check if the features have been loaded if features.any(): lowerCamelCase_ =features.mean(1 ) # Center the dataset lowerCamelCase_ =features - np.reshape(_A , (data_mean.size, 1) ) lowerCamelCase_ =np.dot(_A , centered_data.T ) / features.shape[1] lowerCamelCase_ , lowerCamelCase_ =np.linalg.eigh(_A ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCamelCase_ =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCamelCase_ =np.dot(filtered_eigenvectors.T , _A ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( _A : np.ndarray , _A : np.ndarray , _A : int , _A : int ) ->np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: lowerCamelCase_ , lowerCamelCase_ =eigh( covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , ) lowerCamelCase_ =eigenvectors[:, ::-1][:, :dimensions] lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =np.linalg.svd(_A ) lowerCamelCase_ =svd_matrix[:, 0:dimensions] lowerCamelCase_ =np.dot(filtered_svd_matrix.T , _A ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A ) logging.error("""Dataset empty""" ) raise AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" # Create dummy dataset with 2 classes and 3 features lowerCamelCase_ =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCamelCase_ =np.array([0, 0, 0, 1, 1] ) lowerCamelCase_ =2 lowerCamelCase_ =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_A ) as error_info: lowerCamelCase_ =linear_discriminant_analysis( _A , _A , _A , _A ) if isinstance(_A , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCamelCase_ =2 lowerCamelCase_ =np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_A ) as error_info: lowerCamelCase_ =principal_component_analysis(_A , _A ) if not np.allclose(_A , _A ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
75
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _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=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , )-> Optional[Any]: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =seq_length lowerCamelCase_ =is_training lowerCamelCase_ =use_token_type_ids lowerCamelCase_ =use_labels lowerCamelCase_ =vocab_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =num_labels lowerCamelCase_ =num_choices lowerCamelCase_ =scope lowerCamelCase_ =self.vocab_size - 1 def _snake_case ( self )-> str: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ =None if self.use_token_type_ids: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase_ =None lowerCamelCase_ =None lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ =ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ =OpenAIGPTConfig( 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 , pad_token_id=self.pad_token_id , ) lowerCamelCase_ =ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =OpenAIGPTModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =OpenAIGPTLMHeadModel(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> Optional[int]: lowerCamelCase_ =OpenAIGPTDoubleHeadsModel(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> Tuple: lowerCamelCase_ =self.num_labels lowerCamelCase_ =OpenAIGPTForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={ """input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Union[str, Any] = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) _UpperCamelCase:Union[str, Any] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly _UpperCamelCase:List[Any] = ( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> List[str]: lowerCamelCase_ =super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": lowerCamelCase_ =torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =inputs_dict["""labels"""] lowerCamelCase_ =inputs_dict["""labels"""] lowerCamelCase_ =torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE , ) lowerCamelCase_ =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) return inputs_dict def _snake_case ( self )-> str: lowerCamelCase_ =OpenAIGPTModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , n_embd=37 ) def _snake_case ( self )-> List[Any]: self.config_tester.run_common_tests() def _snake_case ( self )-> Any: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )-> List[str]: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =OpenAIGPTModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @slow def _snake_case ( self )-> Any: lowerCamelCase_ =OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt""" ) model.to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) # the president is lowerCamelCase_ =[ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 4_0477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the lowerCamelCase_ =model.generate(_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE ) self.assertListEqual(output_ids[0].tolist() , _SCREAMING_SNAKE_CASE )
717
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A : str = F"""https://www.google.com/search?q={query}&num=100""" __A : int = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: __A : str = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: __A : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
75
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = { 'configuration_funnel': ['FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FunnelConfig'], 'convert_funnel_original_tf_checkpoint_to_pytorch': [], 'tokenization_funnel': ['FunnelTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['FunnelTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : str = [ 'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'FunnelBaseModel', 'FunnelForMaskedLM', 'FunnelForMultipleChoice', 'FunnelForPreTraining', 'FunnelForQuestionAnswering', 'FunnelForSequenceClassification', 'FunnelForTokenClassification', 'FunnelModel', 'FunnelPreTrainedModel', 'load_tf_weights_in_funnel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ 'TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFFunnelBaseModel', 'TFFunnelForMaskedLM', 'TFFunnelForMultipleChoice', 'TFFunnelForPreTraining', 'TFFunnelForQuestionAnswering', 'TFFunnelForSequenceClassification', 'TFFunnelForTokenClassification', 'TFFunnelModel', 'TFFunnelPreTrainedModel', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys __A : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
718
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
0
import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py __A : Tuple = 'src/transformers' __A : Dict = 'docs/source/en/tasks' def __UpperCamelCase ( _A : str , _A : Any , _A : int ) ->List[str]: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase_ =f.readlines() # Find the start prompt. lowerCamelCase_ =0 while not lines[start_index].startswith(_A ): start_index += 1 start_index += 1 lowerCamelCase_ =start_index while not lines[end_index].startswith(_A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. __A : Dict = direct_transformers_import(TRANSFORMERS_PATH) __A : Any = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). __A : List[Any] = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def __UpperCamelCase ( _A : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =TASK_GUIDE_TO_MODELS[task_guide] lowerCamelCase_ =SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(_A , set() ) lowerCamelCase_ ={ code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([f'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def __UpperCamelCase ( _A : Tuple , _A : int=False ) ->str: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =_find_text_in_file( filename=os.path.join(_A , _A ) , start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""" , end_prompt="""<!--End of the generated tip-->""" , ) lowerCamelCase_ =get_model_list_for_task(_A ) if current_list != new_list: if overwrite: with open(os.path.join(_A , _A ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( f'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' """ to fix this.""" ) if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __A : List[str] = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
719
from collections import namedtuple import requests from lxml import html # type: ignore __A : Dict = namedtuple('covid_data', 'cases deaths recovered') def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data: """simple docstring""" lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) ) __A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
75
0
'''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.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input __A : List[str] = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def __UpperCamelCase ( ) ->List[str]: """simple docstring""" lowerCamelCase_ =_ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase_ =get_sagemaker_input() else: lowerCamelCase_ =get_cluster_input() return config def __UpperCamelCase ( _A : List[str]=None ) ->str: """simple docstring""" if subparsers is not None: lowerCamelCase_ =subparsers.add_parser("""config""" , description=_A ) else: lowerCamelCase_ =argparse.ArgumentParser("""Accelerate config command""" , description=_A ) parser.add_argument( """--config_file""" , default=_A , 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=_A ) return parser def __UpperCamelCase ( _A : Union[str, Any] ) ->Optional[int]: """simple docstring""" lowerCamelCase_ =get_user_input() if args.config_file is not None: lowerCamelCase_ =args.config_file else: if not os.path.isdir(_A ): os.makedirs(_A ) lowerCamelCase_ =default_yaml_config_file if config_file.endswith(""".json""" ): config.to_json_file(_A ) else: config.to_yaml_file(_A ) print(f'accelerate configuration saved at {config_file}' ) def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =config_command_parser() lowerCamelCase_ =parser.parse_args() config_command(_A ) if __name__ == "__main__": main()
720
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
75
0
from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _SCREAMING_SNAKE_CASE ( yaml.SafeLoader): def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Dict: lowerCamelCase_ =[self.constructed_objects[key_node] for key_node, _ in node.value] lowerCamelCase_ =[tuple(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else key for key in keys] lowerCamelCase_ =Counter(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =[key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'Got duplicate yaml keys: {duplicate_keys}' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> int: lowerCamelCase_ =super().construct_mapping(_SCREAMING_SNAKE_CASE , deep=_SCREAMING_SNAKE_CASE ) self._check_no_duplicates_on_constructed_node(_SCREAMING_SNAKE_CASE ) return mapping def __UpperCamelCase ( _A : str ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCamelCase_ =list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCamelCase_ =full_content[1:].index("""---""" ) + 1 lowerCamelCase_ ="""\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_A ) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): # class attributes _UpperCamelCase:str = {"train_eval_index"} # train-eval-index in the YAML metadata @classmethod def _snake_case ( cls , _SCREAMING_SNAKE_CASE )-> "DatasetMetadata": with open(_SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as readme_file: lowerCamelCase_ , lowerCamelCase_ =_split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(_SCREAMING_SNAKE_CASE ) else: return cls() def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: if path.exists(): with open(_SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as readme_file: lowerCamelCase_ =readme_file.read() else: lowerCamelCase_ =None lowerCamelCase_ =self._to_readme(_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE = None )-> str: if readme_content is not None: lowerCamelCase_ , lowerCamelCase_ =_split_yaml_from_readme(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ="""---\n""" + self.to_yaml_string() + """---\n""" + content else: lowerCamelCase_ ="""---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def _snake_case ( cls , _SCREAMING_SNAKE_CASE )-> "DatasetMetadata": lowerCamelCase_ =yaml.load(_SCREAMING_SNAKE_CASE , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCamelCase_ ={ (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> str: return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=_SCREAMING_SNAKE_CASE , allow_unicode=_SCREAMING_SNAKE_CASE , encoding="""utf-8""" , ).decode("""utf-8""" ) __A : List[str] = { 'image-classification': [], 'translation': [], 'image-segmentation': [], 'fill-mask': [], 'automatic-speech-recognition': [], 'token-classification': [], 'sentence-similarity': [], 'audio-classification': [], 'question-answering': [], 'summarization': [], 'zero-shot-classification': [], 'table-to-text': [], 'feature-extraction': [], 'other': [], 'multiple-choice': [], 'text-classification': [], 'text-to-image': [], 'text2text-generation': [], 'zero-shot-image-classification': [], 'tabular-classification': [], 'tabular-regression': [], 'image-to-image': [], 'tabular-to-text': [], 'unconditional-image-generation': [], 'text-retrieval': [], 'text-to-speech': [], 'object-detection': [], 'audio-to-audio': [], 'text-generation': [], 'conversational': [], 'table-question-answering': [], 'visual-question-answering': [], 'image-to-text': [], 'reinforcement-learning': [], 'voice-activity-detection': [], 'time-series-forecasting': [], 'document-question-answering': [], } if __name__ == "__main__": from argparse import ArgumentParser __A : Tuple = ArgumentParser(usage='Validate the yaml metadata block of a README.md file.') ap.add_argument('readme_filepath') __A : Any = ap.parse_args() __A : Dict = Path(args.readme_filepath) __A : Dict = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
721
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : str = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : List[Any] , _A : Union[str, Any] ) ->Dict: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any]="binary" ) ->List[Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(_A , _A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=_A , average=_A ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : int , _A : Union[str, Any] ) ->int: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(_A , _A ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*_A ) lowerCamelCase_ =fa_score(y_true=_A , y_pred=_A , average="""macro""" ) fas.append(_A ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(_A ) ) ems.append(_A ) lowerCamelCase_ =float(sum(_A ) / len(_A ) ) lowerCamelCase_ =sum(_A ) / len(_A ) lowerCamelCase_ =float(fa_score(y_true=_A , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Optional[int]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
75
0
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : Tuple = { 'nielsr/canine-s': 20_48, } # Unicode defines 1,114,112 total “codepoints” __A : int = 1_11_41_12 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py __A : List[str] = 0 __A : Tuple = 0Xe000 __A : str = 0Xe001 __A : Dict = 0Xe002 __A : str = 0Xe003 __A : str = 0Xe004 # Maps special codepoints to human-readable names. __A : Dict[int, str] = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. __A : Dict[str, int] = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _SCREAMING_SNAKE_CASE=chr(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE=chr(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE=chr(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE=chr(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE=chr(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE=chr(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=2048 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else bos_token lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else eos_token lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else sep_token lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else cls_token lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ =AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token super().__init__( bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , model_max_length=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Creates a mapping for looking up the IDs of special symbols. lowerCamelCase_ ={} for codepoint, name in SPECIAL_CODEPOINTS.items(): lowerCamelCase_ =codepoint # Creates a mapping for looking up the string forms of special symbol IDs. lowerCamelCase_ ={ codepoint: name for name, codepoint in self._special_codepoints.items() } lowerCamelCase_ =UNICODE_VOCAB_SIZE lowerCamelCase_ =len(self._special_codepoints ) @property def _snake_case ( self )-> int: return self._unicode_vocab_size def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> int: try: return ord(_SCREAMING_SNAKE_CASE ) except TypeError: raise ValueError(f'invalid token: \'{token}\'' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> str: try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(_SCREAMING_SNAKE_CASE ) except TypeError: raise ValueError(f'invalid id: {index}' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Tuple: return "".join(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] lowerCamelCase_ =cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_SCREAMING_SNAKE_CASE , token_ids_a=_SCREAMING_SNAKE_CASE , already_has_special_tokens=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =[1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] if token_ids_a is not None: result += ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return result def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]: lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] lowerCamelCase_ =len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Union[str, Any]: return ()
700
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A : Union[str, Any] = logging.get_logger(__name__) __A : Optional[Any] = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = "deta" _UpperCamelCase:int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , **_SCREAMING_SNAKE_CASE , )-> str: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase_ =CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =backbone_config.pop("""model_type""" ) lowerCamelCase_ =CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ =config_class.from_dict(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =backbone_config lowerCamelCase_ =num_queries lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =d_model lowerCamelCase_ =encoder_ffn_dim lowerCamelCase_ =encoder_layers lowerCamelCase_ =encoder_attention_heads lowerCamelCase_ =decoder_ffn_dim lowerCamelCase_ =decoder_layers lowerCamelCase_ =decoder_attention_heads lowerCamelCase_ =dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =activation_dropout lowerCamelCase_ =activation_function lowerCamelCase_ =init_std lowerCamelCase_ =init_xavier_std lowerCamelCase_ =encoder_layerdrop lowerCamelCase_ =auxiliary_loss lowerCamelCase_ =position_embedding_type # deformable attributes lowerCamelCase_ =num_feature_levels lowerCamelCase_ =encoder_n_points lowerCamelCase_ =decoder_n_points lowerCamelCase_ =two_stage lowerCamelCase_ =two_stage_num_proposals lowerCamelCase_ =with_box_refine lowerCamelCase_ =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher lowerCamelCase_ =class_cost lowerCamelCase_ =bbox_cost lowerCamelCase_ =giou_cost # Loss coefficients lowerCamelCase_ =mask_loss_coefficient lowerCamelCase_ =dice_loss_coefficient lowerCamelCase_ =bbox_loss_coefficient lowerCamelCase_ =giou_loss_coefficient lowerCamelCase_ =eos_coefficient lowerCamelCase_ =focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def _snake_case ( self )-> int: return self.encoder_attention_heads @property def _snake_case ( self )-> int: return self.d_model def _snake_case ( self )-> str: lowerCamelCase_ =copy.deepcopy(self.__dict__ ) lowerCamelCase_ =self.backbone_config.to_dict() lowerCamelCase_ =self.__class__.model_type return output
75
0
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __A : Tuple = logging.get_logger(__name__) def __UpperCamelCase ( _A : int ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: lowerCamelCase_ =128 elif "12-12" in model_name: lowerCamelCase_ =12 lowerCamelCase_ =12 elif "14-14" in model_name: lowerCamelCase_ =14 lowerCamelCase_ =14 elif "16-16" in model_name: lowerCamelCase_ =16 lowerCamelCase_ =16 else: raise ValueError("""Model not supported""" ) lowerCamelCase_ ="""huggingface/label-files""" if "speech-commands" in model_name: lowerCamelCase_ =35 lowerCamelCase_ ="""speech-commands-v2-id2label.json""" else: lowerCamelCase_ =527 lowerCamelCase_ ="""audioset-id2label.json""" lowerCamelCase_ =json.load(open(hf_hub_download(_A , _A , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase_ ={int(_A ): v for k, v in idalabel.items()} lowerCamelCase_ =idalabel lowerCamelCase_ ={v: k for k, v in idalabel.items()} return config def __UpperCamelCase ( _A : Optional[Any] ) ->str: """simple docstring""" if "module.v" in name: lowerCamelCase_ =name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: lowerCamelCase_ =name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: lowerCamelCase_ =name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: lowerCamelCase_ =name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: lowerCamelCase_ =name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: lowerCamelCase_ =name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: lowerCamelCase_ =name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: lowerCamelCase_ =name.replace("""attn""" , """attention.self""" ) if "norm1" in name: lowerCamelCase_ =name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: lowerCamelCase_ =name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: lowerCamelCase_ =name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: lowerCamelCase_ =name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: lowerCamelCase_ =name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: lowerCamelCase_ =name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: lowerCamelCase_ =name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def __UpperCamelCase ( _A : Optional[int] , _A : int ) ->List[str]: """simple docstring""" for key in orig_state_dict.copy().keys(): lowerCamelCase_ =orig_state_dict.pop(_A ) if "qkv" in key: lowerCamelCase_ =key.split(""".""" ) lowerCamelCase_ =int(key_split[3] ) lowerCamelCase_ =config.hidden_size if "weight" in key: lowerCamelCase_ =val[:dim, :] lowerCamelCase_ =val[dim : dim * 2, :] lowerCamelCase_ =val[-dim:, :] else: lowerCamelCase_ =val[:dim] lowerCamelCase_ =val[dim : dim * 2] lowerCamelCase_ =val[-dim:] else: lowerCamelCase_ =val return orig_state_dict def __UpperCamelCase ( _A : Any ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ =[ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(_A , _A ) @torch.no_grad() def __UpperCamelCase ( _A : Optional[int] , _A : str , _A : int=False ) ->Optional[Any]: """simple docstring""" lowerCamelCase_ =get_audio_spectrogram_transformer_config(_A ) lowerCamelCase_ ={ """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict lowerCamelCase_ =model_name_to_url[model_name] lowerCamelCase_ =torch.hub.load_state_dict_from_url(_A , map_location="""cpu""" ) # remove some keys remove_keys(_A ) # rename some keys lowerCamelCase_ =convert_state_dict(_A , _A ) # load 🤗 model lowerCamelCase_ =ASTForAudioClassification(_A ) model.eval() model.load_state_dict(_A ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 lowerCamelCase_ =-4.2_6_7_7_3_9_3 if """speech-commands""" not in model_name else -6.8_4_5_9_7_8 lowerCamelCase_ =4.5_6_8_9_9_7_4 if """speech-commands""" not in model_name else 5.5_6_5_4_5_2_6 lowerCamelCase_ =1024 if """speech-commands""" not in model_name else 128 lowerCamelCase_ =ASTFeatureExtractor(mean=_A , std=_A , max_length=_A ) if "speech-commands" in model_name: lowerCamelCase_ =load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) lowerCamelCase_ =dataset[0]["""audio"""]["""array"""] else: lowerCamelCase_ =hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) lowerCamelCase_ , lowerCamelCase_ =torchaudio.load(_A ) lowerCamelCase_ =waveform.squeeze().numpy() lowerCamelCase_ =feature_extractor(_A , sampling_rate=16000 , return_tensors="""pt""" ) # forward pass lowerCamelCase_ =model(**_A ) lowerCamelCase_ =outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": lowerCamelCase_ =torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": lowerCamelCase_ =torch.tensor([-1.1_9_8_6, -7.0_9_0_3, -8.2_7_1_8] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": lowerCamelCase_ =torch.tensor([-2.6_1_2_8, -8.0_0_8_0, -9.4_3_4_4] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": lowerCamelCase_ =torch.tensor([-1.5_0_8_0, -7.4_5_3_4, -8.8_9_1_7] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": lowerCamelCase_ =torch.tensor([-0.5_0_5_0, -6.5_8_3_3, -8.0_8_4_3] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": lowerCamelCase_ =torch.tensor([-0.3_8_2_6, -7.0_3_3_6, -8.2_4_1_3] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": lowerCamelCase_ =torch.tensor([-1.2_1_1_3, -6.9_1_0_1, -8.3_4_7_0] ) elif model_name == "ast-finetuned-speech-commands-v2": lowerCamelCase_ =torch.tensor([6.1_5_8_9, -8.0_5_6_6, -8.7_9_8_4] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , _A , atol=1E-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_A ).mkdir(exist_ok=_A ) print(f'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(_A ) print(f'Saving feature extractor to {pytorch_dump_folder_path}' ) feature_extractor.save_pretrained(_A ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f'MIT/{model_name}' ) feature_extractor.push_to_hub(f'MIT/{model_name}' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='ast-finetuned-audioset-10-10-0.4593', type=str, help='Name of the Audio Spectrogram Transformer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __A : Union[str, Any] = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
701
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __A : int = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Any = "albert" def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =vocab_size lowerCamelCase_ =embedding_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_hidden_groups lowerCamelCase_ =num_attention_heads lowerCamelCase_ =inner_group_num lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =position_embedding_type class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
75
0
from math import factorial def __UpperCamelCase ( _A : int , _A : int , _A : float ) ->float: """simple docstring""" if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(_A , _A ) or not isinstance(_A , _A ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) lowerCamelCase_ =(prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! lowerCamelCase_ =float(factorial(_A ) ) coefficient /= factorial(_A ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
702
from collections import deque from math import floor from random import random from time import time class _SCREAMING_SNAKE_CASE : def __init__( self )-> List[str]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[Any]: if self.graph.get(_SCREAMING_SNAKE_CASE ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase_ =[[w, v]] if not self.graph.get(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[] def _snake_case ( self )-> str: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> Optional[Any]: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Any: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return len(self.graph[u] ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Union[str, Any]: lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =[] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return sorted_nodes def _snake_case ( self )-> str: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> List[str]: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin class _SCREAMING_SNAKE_CASE : def __init__( self )-> Optional[Any]: lowerCamelCase_ ={} def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1 )-> List[str]: # check if the u exists if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase_ =[[w, v]] # add the other way if self.graph.get(_SCREAMING_SNAKE_CASE ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase_ =[[w, u]] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_SCREAMING_SNAKE_CASE ) # the other way round if self.graph.get(_SCREAMING_SNAKE_CASE ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> int: if s == d: return [] lowerCamelCase_ =[] lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_SCREAMING_SNAKE_CASE ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE=-1 )-> Optional[int]: if c == -1: lowerCamelCase_ =floor(random() * 1_0000 ) + 10 for i in range(_SCREAMING_SNAKE_CASE ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase_ =floor(random() * c ) + 1 if n != i: self.add_pair(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1 ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> List[str]: lowerCamelCase_ =deque() lowerCamelCase_ =[] if s == -2: lowerCamelCase_ =list(self.graph )[0] d.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) while d: lowerCamelCase_ =d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return len(self.graph[u] ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =list(self.graph )[0] stack.append(_SCREAMING_SNAKE_CASE ) visited.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =-2 lowerCamelCase_ =[] lowerCamelCase_ =s lowerCamelCase_ =False lowerCamelCase_ =set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase_ =s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase_ =len(_SCREAMING_SNAKE_CASE ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase_ =node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase_ =True if len(_SCREAMING_SNAKE_CASE ) != 0: lowerCamelCase_ =stack[len(_SCREAMING_SNAKE_CASE ) - 1] else: lowerCamelCase_ =False indirect_parents.append(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =s lowerCamelCase_ =ss # check if se have reached the starting point if len(_SCREAMING_SNAKE_CASE ) == 0: return False def _snake_case ( self )-> Optional[Any]: return list(self.graph ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 , _SCREAMING_SNAKE_CASE=-1 )-> str: lowerCamelCase_ =time() self.dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin def _snake_case ( self , _SCREAMING_SNAKE_CASE=-2 )-> Dict: lowerCamelCase_ =time() self.bfs(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =time() return end - begin
75
0
from datetime import datetime as dt import os from github import Github __A : List[str] = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase_ =g.get_repo("""huggingface/transformers""" ) lowerCamelCase_ =repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase_ =sorted([comment for comment in issue.get_comments()] , key=lambda _A : i.created_at , reverse=_A ) lowerCamelCase_ =comments[0] if len(_A ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="""closed""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) if __name__ == "__main__": main()
703
import os from datetime import datetime as dt from github import Github __A : Optional[int] = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __UpperCamelCase ( ) ->Dict: """simple docstring""" lowerCamelCase_ =Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase_ =g.get_repo("""huggingface/diffusers""" ) lowerCamelCase_ =repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase_ =sorted(issue.get_comments() , key=lambda _A : i.created_at , reverse=_A ) lowerCamelCase_ =comments[0] if len(_A ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
75
0
import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __A : List[str] = threading.Lock() __A : Optional[logging.Handler] = None __A : List[Any] = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __A : Optional[int] = logging.WARNING __A : List[Any] = True def SCREAMING_SNAKE_CASE_ ( ) ->List[Any]: """simple docstring""" lowerCamelCase_ =os.getenv("""TRANSFORMERS_VERBOSITY""" , _A ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' f'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def SCREAMING_SNAKE_CASE_ ( ) ->str: """simple docstring""" return __name__.split(""".""" )[0] def SCREAMING_SNAKE_CASE_ ( ) ->logging.Logger: """simple docstring""" return logging.getLogger(_get_library_name() ) def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return lowerCamelCase_ =logging.StreamHandler() # Set sys.stderr as stream. lowerCamelCase_ =sys.stderr.flush # Apply our default configuration to the library root logger. lowerCamelCase_ =_get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) lowerCamelCase_ =False def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" global _default_handler with _lock: if not _default_handler: return lowerCamelCase_ =_get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) lowerCamelCase_ =None def SCREAMING_SNAKE_CASE_ ( ) ->Optional[int]: """simple docstring""" return log_levels def SCREAMING_SNAKE_CASE_ ( _A : Optional[str] = None ) ->logging.Logger: """simple docstring""" if name is None: lowerCamelCase_ =_get_library_name() _configure_library_root_logger() return logging.getLogger(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->int: """simple docstring""" _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def SCREAMING_SNAKE_CASE_ ( _A : int ) ->None: """simple docstring""" _configure_library_root_logger() _get_library_root_logger().setLevel(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->int: """simple docstring""" return set_verbosity(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->List[Any]: """simple docstring""" return set_verbosity(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->Tuple: """simple docstring""" return set_verbosity(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->List[Any]: """simple docstring""" return set_verbosity(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def SCREAMING_SNAKE_CASE_ ( _A : logging.Handler ) ->None: """simple docstring""" _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(_A ) def SCREAMING_SNAKE_CASE_ ( _A : logging.Handler ) ->None: """simple docstring""" _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" _configure_library_root_logger() lowerCamelCase_ =False def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" _configure_library_root_logger() lowerCamelCase_ =True def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" lowerCamelCase_ =_get_library_root_logger().handlers for handler in handlers: lowerCamelCase_ =logging.Formatter("""[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s""" ) handler.setFormatter(_A ) def SCREAMING_SNAKE_CASE_ ( ) ->None: """simple docstring""" lowerCamelCase_ =_get_library_root_logger().handlers for handler in handlers: handler.setFormatter(_A ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , *_A : str , **_A : Any ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =os.getenv("""TRANSFORMERS_NO_ADVISORY_WARNINGS""" , _A ) if no_advisory_warnings: return self.warning(*_A , **_A ) __A : Optional[Any] = warning_advice @functools.lru_cache(_A ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , *_A : int , **_A : Tuple ) ->str: """simple docstring""" self.warning(*_A , **_A ) __A : Union[str, Any] = warning_once class _SCREAMING_SNAKE_CASE : def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> int: # pylint: disable=unused-argument lowerCamelCase_ =args[0] if args else None def __iter__( self )-> str: return iter(self._iterator ) def __getattr__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: def empty_fn(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # pylint: disable=unused-argument return return empty_fn def __enter__( self )-> List[Any]: return self def __exit__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: return class _SCREAMING_SNAKE_CASE : def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[Any]: if _tqdm_active: return tqdm_lib.tqdm(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) else: return EmptyTqdm(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: if _tqdm_active: return tqdm_lib.tqdm.get_lock() __A : Optional[Any] = _tqdm_cls() def SCREAMING_SNAKE_CASE_ ( ) ->bool: """simple docstring""" global _tqdm_active return bool(_tqdm_active ) def SCREAMING_SNAKE_CASE_ ( ) ->Any: """simple docstring""" global _tqdm_active lowerCamelCase_ =True hf_hub_utils.enable_progress_bars() def SCREAMING_SNAKE_CASE_ ( ) ->Tuple: """simple docstring""" global _tqdm_active lowerCamelCase_ =False hf_hub_utils.disable_progress_bars()
704
import argparse import os import re __A : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. __A : int = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. __A : int = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Optional[Any] = re.compile(R'\[([^\]]+)\]') def __UpperCamelCase ( _A : int ) ->Dict: """simple docstring""" lowerCamelCase_ =_re_indent.search(_A ) return "" if search is None else search.groups()[0] def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]: """simple docstring""" lowerCamelCase_ =0 lowerCamelCase_ =code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 lowerCamelCase_ =["""\n""".join(lines[:index] )] else: lowerCamelCase_ =[] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ =[lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_A ) ) if index < len(_A ) - 1: lowerCamelCase_ =[lines[index + 1]] index += 1 else: lowerCamelCase_ =[] else: blocks.append("""\n""".join(_A ) ) lowerCamelCase_ =[lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append("""\n""".join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def __UpperCamelCase ( _A : Optional[int] ) ->Optional[int]: """simple docstring""" def _inner(_A : Optional[Any] ): return key(_A ).lower().replace("""_""" , """""" ) return _inner def __UpperCamelCase ( _A : int , _A : List[Any]=None ) ->List[str]: """simple docstring""" # If no key is provided, we use a noop. def noop(_A : List[str] ): return x if key is None: lowerCamelCase_ =noop # Constants are all uppercase, they go first. lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()] lowerCamelCase_ =ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def __UpperCamelCase ( _A : List[str] ) ->List[str]: """simple docstring""" # This inner function sort imports between [ ]. def _replace(_A : Optional[Any] ): lowerCamelCase_ =match.groups()[0] if "," not in imports: return f'[{imports}]' lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" lowerCamelCase_ =import_statement.split("""\n""" ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase_ =2 if lines[1].strip() == """[""" else 1 lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] ) lowerCamelCase_ =[lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase_ =_re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ =keys[:-1] lowerCamelCase_ =get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase_ =_re_bracket_content.sub(_replace , _A ) return import_statement def __UpperCamelCase ( _A : List[Any] , _A : Optional[Any]=True ) ->str: """simple docstring""" with open(_A , """r""" ) as f: lowerCamelCase_ =f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ =split_code_in_indented_blocks( _A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ =main_blocks[block_idx] lowerCamelCase_ =block.split("""\n""" ) # Get to the start of the imports. lowerCamelCase_ =0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase_ =len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] ) lowerCamelCase_ =get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ =_re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase_ =[(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase_ =[(i, key) for i, key in enumerate(_A ) if key is not None] lowerCamelCase_ =[x[0] for x in sorted(_A , key=lambda _A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase_ =0 lowerCamelCase_ =[] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , """w""" ) as f: f.write("""\n""".join(_A ) ) def __UpperCamelCase ( _A : str=True ) ->List[Any]: """simple docstring""" lowerCamelCase_ =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A ) if result: lowerCamelCase_ =[os.path.join(_A , """__init__.py""" )] if len(_A ) > 0: raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') __A : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
75
0